text
stringlengths
54
60.6k
<commit_before>void runTTreeFilter() { // author: Redmer Alexander Bertens, Utrecht University // rbertens@cern.ch , rbertens@nikhef.nl , r.a.bertens@uu.nl // // example which converts input data (in this case local aod's put into a chain) // to a tree which holds // - AliFlowTTreeEvent : event object // - AliFlowTTreeTrack : track objects // see source of these classes for more details // load libraries gSystem->Load("libCore.so"); gSystem->Load("libGeom.so"); gSystem->Load("libVMC.so"); gSystem->Load("libPhysics.so"); gSystem->Load("libTree.so"); gSystem->Load("libSTEERBase.so"); gSystem->Load("libESD.so"); gSystem->Load("libAOD.so"); gSystem->Load("libANALYSIS.so"); gSystem->Load("libANALYSISalice.so"); // create the analysis manager AliAnalysisManager* mgr = new AliAnalysisManager("MyManager"); // create a tchain which will point to an aod tree TChain* chain = new TChain("aodTree"); // add a few files to the chain (change this so that your local files are added) chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0003/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0003/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0004/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0005/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0006/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0007/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0008/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0009/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0010/AliAOD.root"); // create an input handler AliVEventHandler* inputH = new AliAODInputHandler(); // and connect it to the manager mgr->SetInputEventHandler(inputH); // the manager is static, so get the existing manager via the static method AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { printf("No analysis manager to connect to!\n"); return NULL; } // just to see if all went well, check if the input event handler has been connected if (!mgr->GetInputEventHandler()) { printf("This task requires an input event handler!\n"); return NULL; } // compile the relevant classes // include paths, necessary for compilation gSystem->AddIncludePath("-Wno-deprecated"); gSystem->AddIncludePath("-I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/EMCAL"); gSystem->AddIncludePath("-I$ALICE_ROOT/PWGDQ/dielectron -I$ALICE_ROOT/PWGHF/hfe"); gSystem->AddIncludePath("-I$ALICE_ROOT/JETAN -I$ALICE_ROOT/JETAN/fastjet"); gROOT->LoadMacro("../objects/AliFlowTTreeEvent.cxx+"); gROOT->LoadMacro("../objects/AliFlowTTreeTrack.cxx+"); gROOT->LoadMacro("../objects/AliAnalysisTaskTTreeFilter.cxx+"); // load the addtask gROOT->LoadMacro("AddTaskTTreeFilter.C"); // launch the task AddTaskTTreeFilter(); // check if we can initialize the manager if(!mgr->InitAnalysis()) return; // print the status of the manager to screen mgr->PrintStatus(); // print to screen how the analysis is progressing mgr->SetUseProgressBar(1, 25); // start the analysis locally, reading the events from the tchain mgr->StartAnalysis("local", chain); } <commit_msg> remove redundant check from run macro<commit_after>void runTTreeFilter() { // author: Redmer Alexander Bertens, Utrecht University // rbertens@cern.ch , rbertens@nikhef.nl , r.a.bertens@uu.nl // // example which converts input data (in this case local aod's put into a chain) // to a tree which holds // - AliFlowTTreeEvent : event object // - AliFlowTTreeTrack : track objects // see source of these classes for more details // load libraries gSystem->Load("libCore.so"); gSystem->Load("libGeom.so"); gSystem->Load("libVMC.so"); gSystem->Load("libPhysics.so"); gSystem->Load("libTree.so"); gSystem->Load("libSTEERBase.so"); gSystem->Load("libESD.so"); gSystem->Load("libAOD.so"); gSystem->Load("libANALYSIS.so"); gSystem->Load("libANALYSISalice.so"); // create the analysis manager AliAnalysisManager* mgr = new AliAnalysisManager("MyManager"); // create a tchain which will point to an aod tree TChain* chain = new TChain("aodTree"); // add a few files to the chain (change this so that your local files are added) chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0003/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0003/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0004/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0005/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0006/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0007/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0008/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0009/AliAOD.root"); chain->Add("/home/rbertens/Documents/CERN/ALICE_DATA/data/2010/LHC10h/000139510/ESDs/pass2/AOD086/0010/AliAOD.root"); // create an input handler AliVEventHandler* inputH = new AliAODInputHandler(); // and connect it to the manager mgr->SetInputEventHandler(inputH); // compile the relevant classes // include paths, necessary for compilation gSystem->AddIncludePath("-Wno-deprecated"); gSystem->AddIncludePath("-I$ALICE_ROOT -I$ALICE_ROOT/include -I$ALICE_ROOT/EMCAL"); gSystem->AddIncludePath("-I$ALICE_ROOT/PWGDQ/dielectron -I$ALICE_ROOT/PWGHF/hfe"); gSystem->AddIncludePath("-I$ALICE_ROOT/JETAN -I$ALICE_ROOT/JETAN/fastjet"); gROOT->LoadMacro("../objects/AliFlowTTreeEvent.cxx+"); gROOT->LoadMacro("../objects/AliFlowTTreeTrack.cxx+"); gROOT->LoadMacro("../objects/AliAnalysisTaskTTreeFilter.cxx+"); // load the addtask gROOT->LoadMacro("AddTaskTTreeFilter.C"); // launch the task AddTaskTTreeFilter(); // check if we can initialize the manager if(!mgr->InitAnalysis()) return; // print the status of the manager to screen mgr->PrintStatus(); // print to screen how the analysis is progressing mgr->SetUseProgressBar(1, 25); // start the analysis locally, reading the events from the tchain mgr->StartAnalysis("local", chain); } <|endoftext|>
<commit_before><commit_msg>updates<commit_after><|endoftext|>
<commit_before>//****************************************************************************************************** // RoutingTables.cpp - Gbtc // // Copyright 2019, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 03/28/2019 - J. Ritchie Carroll // Generated original version of source code. // //****************************************************************************************************** #include "RoutingTables.h" using namespace std; using namespace GSF; using namespace GSF::TimeSeries; using namespace GSF::TimeSeries::Transport; RoutingTables::RoutingTables() : m_activeRoutes(NewSharedPtr<RoutingTable>()), m_enabled(true) { Thread([this]() { while (m_enabled) { m_routingTableOperations.WaitForData(); const auto operation = m_routingTableOperations.Dequeue(); operation.first(*this, operation.second); } }); } RoutingTables::~RoutingTables() { m_enabled = false; m_routingTableOperations.Release(); } RoutingTables::RoutingTablePtr RoutingTables::CloneActiveRoutes() { ReaderLock readLock(m_activeRoutesLock); RoutingTablePtr clonedRoutes = NewSharedPtr<RoutingTable>(*m_activeRoutes); return clonedRoutes; } void RoutingTables::SetActiveRoutes(RoutingTablePtr activeRoutes) { WriterLock writeLock(m_activeRoutesLock); m_activeRoutes = std::move(activeRoutes); } void RoutingTables::UpdateRoutesOperation(RoutingTables& routingTables, const DestinationRoutes& destinationRoutes) { const RoutingTablePtr activeRoutesPtr = routingTables.CloneActiveRoutes(); RoutingTable& activeRoutes = *activeRoutesPtr; const SubscriberConnectionPtr& destination = destinationRoutes.first; const unordered_set<GSF::Guid>& routes = destinationRoutes.second; // Remove subscriber connection from undesired measurement route destinations for (auto& pair : activeRoutes) { if (routes.find(pair.first) != routes.end()) pair.second->erase(destination); } // Add subscriber connection to desired measurement route destinations for (auto& signalID : routes) { DestinationsPtr destinations; if (!TryGetValue(activeRoutes, signalID, destinations, destinations)) { destinations = NewSharedPtr<Destinations>(); activeRoutes.emplace(signalID, destinations); } destinations->insert(destination); } routingTables.SetActiveRoutes(activeRoutesPtr); } void RoutingTables::RemoveRoutesOperation(RoutingTables& routingTables, const DestinationRoutes& destinationRoutes) { const RoutingTablePtr activeRoutesPtr = routingTables.CloneActiveRoutes(); const RoutingTable& activeRoutes = *activeRoutesPtr; const SubscriberConnectionPtr& destination = destinationRoutes.first; // Remove subscriber connection from existing measurement route destinations for (auto& pair : activeRoutes) pair.second->erase(destination); routingTables.SetActiveRoutes(activeRoutesPtr); } void RoutingTables::UpdateRoutes(const SubscriberConnectionPtr& destination, const unordered_set<Guid>& routes) { // Queue update routes operation m_routingTableOperations.Enqueue(RoutingTableOperation(&UpdateRoutesOperation, DestinationRoutes(destination, routes))); } void RoutingTables::RemoveRoutes(const SubscriberConnectionPtr& destination) { // Queue remove routes operation m_routingTableOperations.Enqueue(RoutingTableOperation(&RemoveRoutesOperation, DestinationRoutes(destination, unordered_set<Guid>()))); } void RoutingTables::PublishMeasurements(const vector<MeasurementPtr>& measurements) { typedef vector<MeasurementPtr> Measurements; typedef SharedPtr<Measurements> MeasurementsPtr; unordered_map<SubscriberConnectionPtr, MeasurementsPtr> routedMeasurementMap; const size_t size = measurements.size(); // Constrain read lock to this block { ReaderLock readLock(m_activeRoutesLock); const RoutingTable& activeRoutes = *m_activeRoutes; for (auto& measurement : measurements) { DestinationsPtr destinationsPtr; if (TryGetValue(activeRoutes, measurement->SignalID, destinationsPtr, destinationsPtr)) { const Destinations& destinations = *destinationsPtr; for (auto& destination : destinations) { MeasurementsPtr routedMeasurements; if (!TryGetValue(routedMeasurementMap, destination, routedMeasurements, routedMeasurements)) { routedMeasurements = NewSharedPtr<Measurements>(); routedMeasurements->reserve(size); routedMeasurementMap.emplace(destination, routedMeasurements); } routedMeasurements->push_back(measurement); } } } } // Publish routed measurements for (auto& pair : routedMeasurementMap) { auto& destination = pair.first; if (destination->GetIsSubscribed() && !destination->GetIsTemporalSubscription()) destination->PublishMeasurements(*pair.second); } } <commit_msg>TimeSeriesPlatformLibrary: RoutingTable post testing cleanup.<commit_after>//****************************************************************************************************** // RoutingTables.cpp - Gbtc // // Copyright 2019, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 03/28/2019 - J. Ritchie Carroll // Generated original version of source code. // //****************************************************************************************************** #include "RoutingTables.h" using namespace std; using namespace GSF; using namespace GSF::TimeSeries; using namespace GSF::TimeSeries::Transport; RoutingTables::RoutingTables() : m_activeRoutes(NewSharedPtr<RoutingTable>()), m_enabled(true) { Thread([this]() { while (m_enabled) { m_routingTableOperations.WaitForData(); const auto operation = m_routingTableOperations.Dequeue(); operation.first(*this, operation.second); } }); } RoutingTables::~RoutingTables() { m_enabled = false; m_routingTableOperations.Release(); } RoutingTables::RoutingTablePtr RoutingTables::CloneActiveRoutes() { ReaderLock readLock(m_activeRoutesLock); RoutingTablePtr clonedRoutes = NewSharedPtr<RoutingTable>(*m_activeRoutes); return clonedRoutes; } void RoutingTables::SetActiveRoutes(RoutingTablePtr activeRoutes) { WriterLock writeLock(m_activeRoutesLock); m_activeRoutes = std::move(activeRoutes); } void RoutingTables::UpdateRoutesOperation(RoutingTables& routingTables, const DestinationRoutes& destinationRoutes) { const RoutingTablePtr activeRoutesPtr = routingTables.CloneActiveRoutes(); RoutingTable& activeRoutes = *activeRoutesPtr; const SubscriberConnectionPtr& destination = destinationRoutes.first; const unordered_set<GSF::Guid>& routes = destinationRoutes.second; // Remove subscriber connection from undesired measurement route destinations for (auto& pair : activeRoutes) { if (routes.find(pair.first) != routes.end()) pair.second->erase(destination); } // Add subscriber connection to desired measurement route destinations for (auto& signalID : routes) { DestinationsPtr destinations; if (!TryGetValue(activeRoutes, signalID, destinations, destinations)) { destinations = NewSharedPtr<Destinations>(); activeRoutes.emplace(signalID, destinations); } destinations->insert(destination); } routingTables.SetActiveRoutes(activeRoutesPtr); } void RoutingTables::RemoveRoutesOperation(RoutingTables& routingTables, const DestinationRoutes& destinationRoutes) { const RoutingTablePtr activeRoutesPtr = routingTables.CloneActiveRoutes(); const RoutingTable& activeRoutes = *activeRoutesPtr; const SubscriberConnectionPtr& destination = destinationRoutes.first; // Remove subscriber connection from existing measurement route destinations for (auto& pair : activeRoutes) pair.second->erase(destination); routingTables.SetActiveRoutes(activeRoutesPtr); } void RoutingTables::UpdateRoutes(const SubscriberConnectionPtr& destination, const unordered_set<Guid>& routes) { // Queue update routes operation m_routingTableOperations.Enqueue(RoutingTableOperation(&UpdateRoutesOperation, DestinationRoutes(destination, routes))); } void RoutingTables::RemoveRoutes(const SubscriberConnectionPtr& destination) { // Queue remove routes operation m_routingTableOperations.Enqueue(RoutingTableOperation(&RemoveRoutesOperation, DestinationRoutes(destination, unordered_set<Guid>()))); } void RoutingTables::PublishMeasurements(const vector<MeasurementPtr>& measurements) { typedef vector<MeasurementPtr> Measurements; typedef SharedPtr<Measurements> MeasurementsPtr; unordered_map<SubscriberConnectionPtr, MeasurementsPtr> routedMeasurementMap; const size_t size = measurements.size(); // Constrain read lock to this block { ReaderLock readLock(m_activeRoutesLock); const RoutingTable& activeRoutes = *m_activeRoutes; for (auto& measurement : measurements) { DestinationsPtr destinationsPtr; if (TryGetValue(activeRoutes, measurement->SignalID, destinationsPtr, destinationsPtr)) { const Destinations& destinations = *destinationsPtr; for (auto& destination : destinations) { MeasurementsPtr routedMeasurements; if (!TryGetValue(routedMeasurementMap, destination, routedMeasurements, routedMeasurements)) { routedMeasurements = NewSharedPtr<Measurements>(); routedMeasurements->reserve(size); routedMeasurementMap.emplace(destination, routedMeasurements); } routedMeasurements->push_back(measurement); } } } } // Publish routed measurements for (auto& pair : routedMeasurementMap) { auto& destination = *pair.first; if (destination.GetIsSubscribed() && !destination.GetIsTemporalSubscription()) destination.PublishMeasurements(*pair.second); } } <|endoftext|>
<commit_before>#pragma once #include "string_view.hh" class ArgvParser { uint argc_; char** argv_; public: ArgvParser(int argc, char** argv) : argc_(std::max(argc - 1, 0)), argv_(argv + 1) {} ArgvParser(const ArgvParser&) = default; ArgvParser(ArgvParser&&) noexcept = default; ArgvParser& operator=(const ArgvParser&) = default; ArgvParser& operator=(ArgvParser&&) noexcept = default; uint size() const noexcept { return argc_; } CStringView operator[](uint n) const noexcept { return (n < argc_ ? CStringView(argv_[n]) : CStringView()); } CStringView next() const noexcept { return operator[](0); } CStringView extract_next() noexcept { if (argc_ > 0) { --argc_; return CStringView(argv_++[0]); } else { return {}; } } }; <commit_msg>ArgvParser: made it not skip the first argument and made it accept const char**<commit_after>#pragma once #include "string_view.hh" class ArgvParser { uint argc_; const char* const* argv_; public: ArgvParser(int argc, const char* const* argv) : argc_(std::max(argc, 0)), argv_(argv) {} ArgvParser(const ArgvParser&) = default; ArgvParser(ArgvParser&&) noexcept = default; ArgvParser& operator=(const ArgvParser&) = default; ArgvParser& operator=(ArgvParser&&) noexcept = default; uint size() const noexcept { return argc_; } CStringView operator[](uint n) const noexcept { return (n < argc_ ? CStringView(argv_[n]) : CStringView()); } CStringView next() const noexcept { return operator[](0); } CStringView extract_next() noexcept { if (argc_ > 0) { --argc_; return CStringView(argv_++[0]); } else { return {}; } } }; <|endoftext|>
<commit_before>/** @file @brief App that looks at each step of the patterns to find simultaneously bright beacons, records them all pairwise, and outputs them sorted by straight-line distance. @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, 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. // Internal Includes #include "Patterns.h" #include "Positions.h" // Library/third-party includes #include <Eigen/Eigen> // Standard includes #include <utility> #include <vector> #include <iostream> #include <cmath> #include <tuple> // for std::tie to make comparisons simpler. /// These are beacons we've chosen to mask off or disable, typically based on /// the results from this tool. #define APPLY_MASK static const auto MASKED_ONEBASED_BEACONIDS = {5, 13, 16}; using BeaconList = std::vector<int>; using Eigen::Vector3d; inline double beaconSquaredDistance(int a, int b) { return (Vector3d::Map(OsvrHdkLedLocations_SENSOR0[a].data()) - Vector3d::Map(OsvrHdkLedLocations_SENSOR0[b].data())) .squaredNorm(); } struct BeaconAdjacentBright { BeaconAdjacentBright(int idA, int idB, int patternStepNum) : beaconA(std::min(idA, idB)), beaconB(std::max(idA, idB)), patternStep(patternStepNum), squaredDistance(beaconSquaredDistance(beaconA, beaconB)) {} int beaconA; int beaconB; int patternStep; double squaredDistance; }; std::ostream &operator<<(std::ostream &os, BeaconAdjacentBright const &adj) { os << "(" << adj.beaconA + 1 << "--" << adj.beaconB + 1 << ") @ " << adj.patternStep << " [" << std::sqrt(adj.squaredDistance) << " mm]"; return os; } using AdjacentBrightnessList = std::vector<BeaconAdjacentBright>; class BrightnessTracking { public: void startPatternStep(int patternStep) { currentPatternStep_ = patternStep; } void recordBrightBeacon(int newBright) { for (auto &existingBright : brightBeacons_) { adjacentBrightness_.emplace_back(existingBright, newBright, currentPatternStep_); listSorted_ = false; } brightBeacons_.push_back(newBright); } void endPatternStep() { moveBrightBeaconsToList(); } /// Gets the list, lazily sorted if required, on demand AdjacentBrightnessList const &getSortedAdjacentBrightnessList() { if (!listSorted_) { sortAdjacentList(); } return adjacentBrightness_; } private: void moveBrightBeaconsToList() { brightBeaconsPerStep_.emplace_back(std::move(brightBeacons_)); brightBeacons_.clear(); } void sortAdjacentList() { #if 0 /// sort by distance, then by pattern step. auto comparison = [](BeaconAdjacentBright const &a, BeaconAdjacentBright const &b) { return a.squaredDistance < b.squaredDistance || (a.squaredDistance == b.squaredDistance && a.patternStep < b.patternStep); }; #else /// sort by distance, then by pattern step. auto comparison = [](BeaconAdjacentBright const &a, BeaconAdjacentBright const &b) { return std::tie(a.squaredDistance, a.patternStep, a.beaconA, a.beaconB) < std::tie(b.squaredDistance, b.patternStep, b.beaconA, b.beaconB); }; #endif std::sort(begin(adjacentBrightness_), end(adjacentBrightness_), comparison); listSorted_ = true; } std::vector<BeaconList> brightBeaconsPerStep_; AdjacentBrightnessList adjacentBrightness_; bool listSorted_ = false; BeaconList brightBeacons_; int currentPatternStep_; }; int main() { initPatterns(); auto numLeds = static_cast<int>(NUM_LEDS_SENSOR0); auto patternLength = static_cast<int>(PATTERN_LENGTH); #ifdef APPLY_MASK /// Replace the pattern in every "masked" LED with all dim for the purposes of /// this tool. auto maskString = std::string(PATTERN_LENGTH, '.'); for (auto &&maskId : MASKED_ONEBASED_BEACONIDS) { OsvrHdkLedIdentifier_SENSOR0_PATTERNS[maskId - 1] = maskString; } #endif BrightnessTracking brightness; /// For each pattern step... for (int patternStep = 0; patternStep < patternLength; ++patternStep) { brightness.startPatternStep(patternStep); /// go through each beacon... for (int ledNum = 0; ledNum < numLeds; ++ledNum) { /// checking to see if it's bright if (OsvrHdkLedIdentifier_SENSOR0_PATTERNS[ledNum][patternStep] == '*') { /// and if so, recording it with the brightness tracker (which takes /// care of the pairwise comparison, etc) brightness.recordBrightBeacon(ledNum); } } brightness.endPatternStep(); } for (auto &adj : brightness.getSortedAdjacentBrightnessList()) { std::cout << adj << std::endl; } return 0; } <commit_msg>Add a greedy algorithm to select which LEDs to mask<commit_after>/** @file @brief App that looks at each step of the patterns to find simultaneously bright beacons, records them all pairwise, and outputs them sorted by straight-line distance. @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, 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. // Internal Includes #include "Patterns.h" #include "Positions.h" // Library/third-party includes #include <Eigen/Eigen> // Standard includes #include <utility> #include <vector> #include <iostream> #include <iomanip> #include <cmath> #include <tuple> // for std::tie to make comparisons simpler. #include <stdexcept> #include <numeric> #include <cstddef> #include <sstream> static const int MAX_AUTO_RUNS = 7; using BeaconList = std::vector<int>; using Eigen::Vector3d; inline double beaconSquaredDistance(Point3Vector const &locationVec, int a, int b) { return (Vector3d::Map(locationVec[a].data()) - Vector3d::Map(locationVec[b].data())) .squaredNorm(); } struct BeaconAdjacentBright { BeaconAdjacentBright(Point3Vector const &locationVec, int idA, int idB, int patternStepNum) : beaconA_(std::min(idA, idB)), beaconB_(std::max(idA, idB)), patternStep_(patternStepNum), squaredDistance_(beaconSquaredDistance( locationVec, beaconA_, beaconB_)) {} int beaconA() const { return beaconA_; } int beaconB() const { return beaconB_; } int patternStep() const { return patternStep_; } double squaredDistance() const { return squaredDistance_; } int oneBasedBeaconA() const { return beaconA_ + 1; } int oneBasedBeaconB() const { return beaconB_ + 1; } double distance() const { return std::sqrt(squaredDistance()); } double cost() const { return 1. / squaredDistance(); } friend bool operator<(BeaconAdjacentBright const &a, BeaconAdjacentBright const &b); private: int beaconA_; int beaconB_; int patternStep_; double squaredDistance_; }; inline bool operator<(BeaconAdjacentBright const &a, BeaconAdjacentBright const &b) { /// sort by distance, then by pattern step. return std::tie(a.squaredDistance_, a.patternStep_, a.beaconA_, a.beaconB_) < std::tie(b.squaredDistance_, b.patternStep_, b.beaconA_, b.beaconB_); } std::ostream &operator<<(std::ostream &os, BeaconAdjacentBright const &adj) { os << "(" << std::setw(2) << adj.oneBasedBeaconA(); os << "--" << std::setw(2) << adj.oneBasedBeaconB(); os << ") @ " << std::setw(2) << adj.patternStep(); os << " [" << std::setw(8) << adj.distance() << " mm]"; return os; } using AdjacentBrightnessList = std::vector<BeaconAdjacentBright>; namespace detail { class BrightnessTracking { public: explicit BrightnessTracking(Point3Vector const &locationVec) : locationVec_(locationVec) {} BrightnessTracking &operator=(BrightnessTracking const &) = delete; void startPatternStep(int patternStep) { currentPatternStep_ = patternStep; } void recordBrightBeacon(int newBright) { for (auto &existingBright : brightBeacons_) { adjacentBrightness_.emplace_back(locationVec_, existingBright, newBright, currentPatternStep_); listSorted_ = false; } brightBeacons_.push_back(newBright); } void endPatternStep() { moveBrightBeaconsToList(); } /// Gets the list, lazily sorted if required, on demand AdjacentBrightnessList const &getSortedAdjacentBrightnessList() { if (!listSorted_) { sortAdjacentList(); } return adjacentBrightness_; } private: void moveBrightBeaconsToList() { brightBeaconsPerStep_.emplace_back(std::move(brightBeacons_)); brightBeacons_.clear(); } void sortAdjacentList() { #if 0 auto comparison = [](BeaconAdjacentBright const &a, BeaconAdjacentBright const &b) { return std::tie(a.squaredDistance, a.patternStep, a.beaconA, a.beaconB) < std::tie(b.squaredDistance, b.patternStep, b.beaconA, b.beaconB); }; #endif std::sort(begin(adjacentBrightness_), end(adjacentBrightness_)); listSorted_ = true; } Point3Vector const &locationVec_; std::vector<BeaconList> brightBeaconsPerStep_; AdjacentBrightnessList adjacentBrightness_; bool listSorted_ = false; BeaconList brightBeacons_; int currentPatternStep_; }; } // namespace detail /// Takes in parallel location and pattern vectors, as well as an optional list /// of one-based beacon IDs to "mask" (in this case, mark as being always dim), /// and returns the completed, sorted AdjacentBrightnessList. AdjacentBrightnessList computeAdjacentBrightnessList( Point3Vector const &locationVec, std::vector<std::string> patternVec, std::vector<int> const &oneBasedBeaconIdsToMask = {}) { if (locationVec.size() != patternVec.size()) { throw std::length_error("Location vec and pattern vec were different " "sizes, but must be the same!"); } // Took the patternVec by value since we want a locally-writable copy. auto patternLength = static_cast<int>(patternVec.back().size()); auto numLeds = static_cast<int>(patternVec.size()); /// Replace the pattern in every "masked" LED with all dim for the purposes of /// this tool. auto maskString = std::string(PATTERN_LENGTH, DIM_CHAR); for (auto &maskId : oneBasedBeaconIdsToMask) { // going to do range checking here patternVec.at(maskId - 1) = maskString; } /// Set up helper object for the remainder of the computation. auto brightness = detail::BrightnessTracking{locationVec}; /// For each pattern step... for (int patternStep = 0; patternStep < patternLength; ++patternStep) { brightness.startPatternStep(patternStep); /// go through each beacon... for (int ledNum = 0; ledNum < numLeds; ++ledNum) { /// checking to see if it's bright if (patternVec[ledNum][patternStep] == BRIGHT_CHAR) { /// and if so, recording it with the brightness tracker (which takes /// care of the pairwise comparison, etc) brightness.recordBrightBeacon(ledNum); } } brightness.endPatternStep(); } return brightness.getSortedAdjacentBrightnessList(); } struct BeaconCost { int id; std::size_t count; double totalCost; double avgCost() const { return totalCost / static_cast<double>(count); } int oneBasedId() const { return id + 1; } }; using BeaconCostComparator = std::function<bool(BeaconCost const &lhs, BeaconCost const &rhs)>; /// operator > on the total (distance-based) cost, then count, then I suppose /// the ID just for comparison sake. inline bool compareBeaconCostByTotalDistanceCost(BeaconCost const &lhs, BeaconCost const &rhs) { return std::tie(lhs.totalCost, lhs.count, lhs.id) > std::tie(rhs.totalCost, lhs.count, rhs.id); } /// operator > on the count, then total (distance-based) cost, then I suppose /// the ID just for comparison sake. inline bool compareBeaconCostByCount(BeaconCost const &lhs, BeaconCost const &rhs) { return std::tie(lhs.count, lhs.totalCost, lhs.id) > std::tie(rhs.count, rhs.totalCost, rhs.id); } /// @param comparator A greater-than comparator of some sort that will bring /// your most-expensive (by your desired operational definition of that term) to /// the top. std::vector<BeaconCost> getMostExpensiveLeds( AdjacentBrightnessList const &adj, BeaconCostComparator comparator = &compareBeaconCostByTotalDistanceCost) { using IndivCosts = std::vector<double>; // Each beacon with a simultaneous bright will have a vector of the "cost" of // each simultaneous bright period. std::vector<IndivCosts> allCosts; auto recordCost = [&](int id, double cost) { if (!(id < allCosts.size())) { // we need to enlarge the vector allCosts.resize(id + 1); } allCosts.at(id).push_back(cost); }; // Go through and record the costs of each beacon. for (auto &adjElt : adj) { auto cost = adjElt.cost(); recordCost(adjElt.beaconA(), cost); recordCost(adjElt.beaconB(), cost); } std::vector<BeaconCost> ret; // Now, we need to somehow reduce the vector of costs to a single cost per // LED. Right now, just doing a mean. auto n = static_cast<int>(allCosts.size()); for (int id = 0; id < n; ++id) { auto const &thisBeaconCosts = allCosts[id]; if (thisBeaconCosts.empty()) { // no costs for this beacon continue; } auto count = thisBeaconCosts.size(); auto totalCost = std::accumulate(begin(thisBeaconCosts), end(thisBeaconCosts), 0.); ret.push_back(BeaconCost{id, count, totalCost}); } /// Finally, the sort: want operator > in some sense. std::sort(begin(ret), end(ret), comparator); return ret; } struct OverallCosts { double totalCost = 0.; int count = 0; double avgCostPerPair() const { return totalCost / static_cast<double>(count); } }; OverallCosts computeCostOfFullList(AdjacentBrightnessList const &adj) { OverallCosts ret; ret.count = adj.size(); auto accumHelper = [](double prev, BeaconAdjacentBright const &cur) { return prev + cur.cost(); }; ret.totalCost = std::accumulate(begin(adj), end(adj), 0., accumHelper); return ret; } void printOutput(int runNumber, std::vector<int> const &maskList, AdjacentBrightnessList const &adj, std::vector<BeaconCost> const &beaconCost, OverallCosts const &overall) { /// make and immediately call the lambda, so we can use a stringstream to /// create and effectively return a string while keeping scopes narrow. auto makeRunNumberId = [](int run) { std::ostringstream os; os << " (Run #" << run << ")"; return os.str(); }; const std::string runNumberId = makeRunNumberId(runNumber); static const auto DIVIDING_LINE = "--------------------\n"; std::cout << DIVIDING_LINE; std::cout << "Run Information" << runNumberId << "\n" << DIVIDING_LINE << std::endl; auto printMaskList = [&] { std::cout << "Masked LEDs:" << runNumberId << "\n"; for (auto &mask : maskList) { std::cout << mask << std::endl; } std::cout << "\n"; }; printMaskList(); std::cout << "Adjacent brightness list" << runNumberId << "\n" << DIVIDING_LINE; for (auto &adjElt : adj) { std::cout << adjElt << std::endl; } std::cout << "\n\n\n"; std::cout << "Beacon expense list" << runNumberId << "\n" << DIVIDING_LINE; for (auto &beacon : beaconCost) { std::cout << "Beacon: " << beacon.oneBasedId() << " \tCount: " << beacon.count << " \tTotal Cost: " << beacon.totalCost << " \tAvg rt Cost: " << std::sqrt(beacon.avgCost()) << std::endl; } std::cout << "\n\n\n"; std::cout << "Overall expense" << runNumberId << "\n" << DIVIDING_LINE; std::cout << "Total number of pairs:\t" << overall.count << std::endl; std::cout << "Total cost (counting each pair once):\t" << overall.totalCost << std::endl; std::cout << "Average cost per pair:\t" << overall.avgCostPerPair() << std::endl; std::cout << "\n"; printMaskList(); std::cout << "\n\n End of output for run" << runNumberId << "\n" << DIVIDING_LINE << "\n"; } void autoCreateMask(int maxRuns, BeaconCostComparator const &comparator) { std::vector<int> maskList; /// turn off up to 4 leds (running 5 passes) for (int i = 0; i < MAX_AUTO_RUNS; ++i) { auto adj = computeAdjacentBrightnessList( OsvrHdkLedLocations_SENSOR0, OsvrHdkLedIdentifier_SENSOR0_PATTERNS, maskList); auto beaconCosts = getMostExpensiveLeds(adj, comparator); auto overall = computeCostOfFullList(adj); /// Dump current output. printOutput(i, maskList, adj, beaconCosts, overall); /// Now, add the most expensive beacon to the mask list for next round. auto newMaskOneBased = beaconCosts.front().oneBasedId(); std::cout << "Adding one-based beacon ID " << newMaskOneBased << " to the mask list for next round." << std::endl; maskList.push_back(newMaskOneBased); } } int main() { initPatterns(); // autoCreateMask(MAX_AUTO_RUNS, &compareBeaconCostByCount); autoCreateMask(MAX_AUTO_RUNS, &compareBeaconCostByTotalDistanceCost); return 0; } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // // ImageLib Sources // Copyright (C) 2000-2008 by Denton Woods // Last modified: 08/29/2008 // // Filename: src-IL/src/il_exr.cpp // // Description: Reads from an OpenEXR (.exr) file. // //----------------------------------------------------------------------------- #include "il_internal.h" #ifndef IL_NO_EXR #include "il_exr.h" #include <ImfRgba.h> #include <ImfArray.h> #include <ImfRgbaFile.h> //#include <ImfTiledRgbaFile.h> //#include <ImfInputFile.h> //#include <ImfTiledInputFile.h> //#include <ImfPreviewImage.h> //#include <ImfChannelList.h> using namespace Imath; using namespace Imf; using namespace std; //! Reads an icon file. ILboolean ilLoadExr(ILconst_string FileName) { return iLoadExrInternal(FileName); } ILboolean iLoadExrInternal(const char FileName[]) { Array<Rgba> pixels; Box2i displayWindow, dataWindow; float pixelAspectRatio; RgbaInputFile in (FileName); displayWindow = in.displayWindow(); dataWindow = in.dataWindow(); pixelAspectRatio = in.pixelAspectRatio(); int dw, dh, dx, dy; dw = dataWindow.max.x - dataWindow.min.x + 1; dh = dataWindow.max.y - dataWindow.min.y + 1; dx = dataWindow.min.x; dy = dataWindow.min.y; pixels.resizeErase (dw * dh); in.setFrameBuffer (pixels - dx - dy * dw, 1, dw); //try //{ in.readPixels (dataWindow.min.y, dataWindow.max.y); //} //catch (const exception &e) //{ // // If some of the pixels in the file cannot be read, // print an error message, and return a partial image // to the caller. // // return IL_FALSE; //} return ilTexImage(dw, dh, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, NULL); } #endif //IL_NO_EXR <commit_msg>*** empty log message ***<commit_after>//----------------------------------------------------------------------------- // // ImageLib Sources // Copyright (C) 2000-2008 by Denton Woods // Last modified: 08/29/2008 // // Filename: src-IL/src/il_exr.cpp // // Description: Reads from an OpenEXR (.exr) file. // //----------------------------------------------------------------------------- #include "il_internal.h" #ifndef IL_NO_EXR #include "il_exr.h" #include <ImfRgba.h> #include <ImfArray.h> #include <ImfRgbaFile.h> //#include <ImfTiledRgbaFile.h> //#include <ImfInputFile.h> //#include <ImfTiledInputFile.h> //#include <ImfPreviewImage.h> //#include <ImfChannelList.h> //! Reads an .exr file. ILboolean ilLoadExr(ILconst_string FileName) { return iLoadExrInternal(FileName); } using namespace Imath; using namespace Imf; using namespace std; ILboolean iLoadExrInternal(const char FileName[]) { Array<Rgba> pixels; Box2i displayWindow, dataWindow; float pixelAspectRatio; RgbaInputFile in (FileName); displayWindow = in.displayWindow(); dataWindow = in.dataWindow(); pixelAspectRatio = in.pixelAspectRatio(); int dw, dh, dx, dy; dw = dataWindow.max.x - dataWindow.min.x + 1; dh = dataWindow.max.y - dataWindow.min.y + 1; dx = dataWindow.min.x; dy = dataWindow.min.y; pixels.resizeErase (dw * dh); in.setFrameBuffer (pixels - dx - dy * dw, 1, dw); //try //{ in.readPixels (dataWindow.min.y, dataWindow.max.y); //} //catch (const exception &e) //{ // // If some of the pixels in the file cannot be read, // print an error message, and return a partial image // to the caller. // // return IL_FALSE; //} return ilTexImage(dw, dh, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, NULL); } #endif //IL_NO_EXR <|endoftext|>
<commit_before>//#include <mavros/RCIn.h> #include <mavros/mavros_plugin.h> #include <pluginlib/class_list_macros.h> #include "mavros/OverrideRCIn.h" #include <guidance_node_amsl/Directive.h> #include <guidance_node_amsl/Position.h> #include <mms/Ack_arm.h> #include <mms/Arm.h> #include <mms/Sys_status.h> namespace mavplugin { /** * @brief Mavros plugin */ class UniboControllerAMSLPlugin : public MavRosPlugin { public: UniboControllerAMSLPlugin() : nodeHandle(), uas(nullptr), safetyOn(true), v_xy_max(3.0), v_z_max(1.5), v_psi_max(3.14) {}; void initialize(UAS &uas_) { uas = &uas_; directive_sub = nodeHandle.subscribe("/directive", 10, &UniboControllerAMSLPlugin::directive_cb, this); position_pub = nodeHandle.advertise<guidance_node_amsl::Position>("/position", 10); arm_sub = nodeHandle.subscribe("/arm", 10, &UniboControllerAMSLPlugin::arming, this); arm_ack_pub = nodeHandle.advertise<mms::Ack_arm>("acknowledge_arming", 10); //velocity_publisher_=nodeHandle.advertise<mavros::OverrideRCIn>("mavros/rc/override", 10); sys_status_pub = nodeHandle.advertise<mms::Sys_status>("/system_status", 10); nodeHandle.param("guidance_node_amsl/param/sat_xy", v_xy_max, 3.0); nodeHandle.param("guidance_node_amsl/param/sat_z", v_z_max, 1.5); nodeHandle.param("guidance_node_amsl/param/sat_yaw", v_psi_max, 3.14); //DEBUG // ROS_INFO("INITIALIZE UNIBO PLUGIN"); } //should be logic mapping between id number and message type const message_map get_rx_handlers() { return { MESSAGE_HANDLER(MAVLINK_MSG_ID_GLOBAL_POSITION_INT, &UniboControllerAMSLPlugin::handle_global_position_int), MESSAGE_HANDLER(MAVLINK_MSG_ID_ATTITUDE, &UniboControllerAMSLPlugin::handle_attitude), MESSAGE_HANDLER(MAVLINK_MSG_ID_RC_CHANNELS_RAW, &UniboControllerAMSLPlugin::handle_rc_channels_raw), MESSAGE_HANDLER(MAVLINK_MSG_ID_COMMAND_ACK, &UniboControllerAMSLPlugin::handle_arm_ack), MESSAGE_HANDLER(MAVLINK_MSG_ID_HEARTBEAT, &UniboControllerAMSLPlugin::handle_heartbeat), MESSAGE_HANDLER(MAVLINK_MSG_ID_SYS_STATUS, &UniboControllerAMSLPlugin::handle_status) }; } private: ros::NodeHandle nodeHandle; UAS *uas; ros::Publisher position_pub; ros::Subscriber directive_sub; //ros::Publisher velocity_publisher_; ros::Subscriber arm_sub; ros::Publisher arm_ack_pub; ros::Publisher sys_status_pub; mms::Sys_status _system_status; //message to move the quadcopter mavros::OverrideRCIn velocity_; //common message to join data from handles guidance_node_amsl::Position commonMessage; //safety flag bool safetyOn; //saturation parameters /* * Questi tipi di dato sono matlab per specifiche ros del param server. * Nel nodo "guidance_node" sono convertiti a float perchè la legge di guida matlab ha come input * dei float. Adesso non sono convertiti perchè tanto possono essere usati così */ double v_xy_max, v_z_max, v_psi_max; //check if safety is on void handle_rc_channels_raw(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_rc_channels_raw_t channels_raw; mavlink_msg_rc_channels_raw_decode(msg,&channels_raw); /* * If safety is on, chan5_raw must be less than 1200 */ //DEBUG //ROS_INFO("CHANNEL 6 IS: %u",channels_raw.chan6_raw); if(channels_raw.chan6_raw > 1800){ safetyOn = false; commonMessage.Safety = 0; } else { safetyOn=true; commonMessage.Safety= 1; } //DEBUG // ROS_INFO("HANDLE RC RAW"); } void handle_attitude(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_attitude_t attitude; mavlink_msg_attitude_decode(msg, &attitude); auto position_msg = boost::make_shared<guidance_node_amsl::Position>(); //getting new data position_msg->Yawangle=attitude.yaw; //copying data from commonMessage position_msg->Timestamp=commonMessage.Timestamp; position_msg->AltitudeRelative=commonMessage.AltitudeRelative; position_msg->AltitudeAMSL=commonMessage.AltitudeAMSL; position_msg->Latitude=commonMessage.Latitude; position_msg->Longitude=commonMessage.Longitude; position_msg->Safety = commonMessage.Safety; //saving data commonMessage.Yawangle=attitude.yaw; //DEBUG // ROS_INFO("%f", commonMessage.Yawangle); position_pub.publish(position_msg); } void handle_heartbeat(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_heartbeat_t heart; mavlink_msg_heartbeat_decode(msg, &heart); //auto position_msg = boost::make_shared<guidance_node_amsl::Position>(); //ROS_INFO("Heatbeat. Base Mode: %d - Sys Status: %d ",heart.base_mode, heart.system_status); if (heart.base_mode >= 128) _system_status.armed = true; else _system_status.armed = false; sys_status_pub.publish(_system_status); } void handle_status(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_sys_status_t status; mavlink_msg_sys_status_decode(msg, &status); //ROS_INFO("Received sys status mavlink. Battery: %d", status.voltage_battery); _system_status.voltage_battery = status.voltage_battery; sys_status_pub.publish(_system_status); } void handle_arm_ack(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_command_ack_t cmd_ack; mavlink_msg_command_ack_decode(msg, &cmd_ack); auto arm_ack_msg = boost::make_shared<mms::Ack_arm>(); if (cmd_ack.command == 400){ //ARM_DISARM command ROS_INFO("Received arm_disarm"); if (cmd_ack.result == MAV_RESULT_ACCEPTED){ arm_ack_msg->mav_result = true; ROS_INFO("Arm-disarm: succsessful"); } else { arm_ack_msg->mav_result = false; ROS_INFO("Arm-disarm: fail"); } arm_ack_pub.publish(arm_ack_msg); } } void handle_global_position_int(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_global_position_int_t global_position; mavlink_msg_global_position_int_decode(msg, &global_position); auto position_msg = boost::make_shared<guidance_node_amsl::Position>(); //getting new data position_msg->Timestamp=global_position.time_boot_ms; position_msg->AltitudeRelative=global_position.relative_alt; position_msg->AltitudeAMSL = global_position.alt; position_msg->Latitude=global_position.lat; position_msg->Longitude=global_position.lon; //copying data from commonMessage position_msg->Yawangle=commonMessage.Yawangle; position_msg->Safety = commonMessage.Safety; //saving data commonMessage.Timestamp=global_position.time_boot_ms; commonMessage.AltitudeRelative=global_position.relative_alt; commonMessage.AltitudeAMSL=global_position.alt; commonMessage.Latitude=global_position.lat; commonMessage.Longitude=global_position.lon; //DEBUG // ROS_INFO("HANDLE POSITION"); position_pub.publish(position_msg); } /* * From directive to RC */ void directive_cb(const guidance_node_amsl::Directive::ConstPtr msg){ /* * Initializing values, if safety is on, these values will remain */ velocity_.channels[0]=0; velocity_.channels[1]=0; velocity_.channels[2]=0; velocity_.channels[3]=0; velocity_.channels[4]=0; velocity_.channels[5]=0; velocity_.channels[6]=0; velocity_.channels[7]=0; if(!safetyOn){ /* * If safety is off, I translate velocity in RC values */ uint16_t vx_RC= (uint16_t)400.0f*(-msg->vxBody)/v_xy_max + 1520; //New: 400 + 1520; Old: 500 + 1500 uint16_t vy_RC=(uint16_t)400.0f*(msg->vyBody)/v_xy_max + 1520; //New: 400 + 1520; Old: 500 + 1500 /* * it seems it loiters with 1420 instead of 1500... */ uint16_t vz_RC= 1420; if (msg->vzBody > 0){ //going down, mapped only in 420us vz_RC = vz_RC + (uint16_t)320.0f*(-msg->vzBody)/v_z_max; //New: 320; Old: 420 } else { //going up, mapped in 580us vz_RC = vz_RC + (uint16_t)480.0f*(-msg->vzBody)/v_z_max; //New: 480 Old: 580 } uint16_t v_psi_RC = (uint16_t)400.0f*(msg->yawRate)/v_psi_max + 1520; //New: 400 + 1520; Old: 500 + 1500 velocity_.channels[0]=vy_RC; velocity_.channels[1]=vx_RC; velocity_.channels[2]=vz_RC; velocity_.channels[3]=v_psi_RC; } //DEBUG /*ROS_INFO("RC_OVERRIDE: [CH1:%u, CH2:%u, CH3:%u, CH4:%u, CH5:%u, CH6:%u, CH7:%u, CH8:%u]", velocity_.channels[0], velocity_.channels[1], velocity_.channels[2], velocity_.channels[3], velocity_.channels[4], velocity_.channels[5], velocity_.channels[6], velocity_.channels[7]);*/ //velocity_publisher_.publish(velocity_); mavlink_message_t msg_mav; mavlink_msg_rc_channels_raw_pack_chan(UAS_PACK_CHAN(uas),&msg_mav,0,1,velocity_.channels[0],velocity_.channels[1],velocity_.channels[2],velocity_.channels[3],0,0,0,0,100); //1 is the sequence that we are not considering right now UAS_FCU(uas)->send_message(&msg_mav); } /* * Arming/disarming the UAV */ void arming(const mms::Arm::ConstPtr msg){ mavlink_message_t msg_mav; if (msg->arm_disarm){ enum MAV_CMD command = MAV_CMD_COMPONENT_ARM_DISARM; float param1 = 1; //1-->arm 0-->disarm float param2 = 0; //not used float param3 = 0; //not used float param4 = 0; //not used float param5 = 0; //not used float param6 = 0; //not used float param7 = 0; //not used uint8_t confirmation = 1; mavlink_msg_command_long_pack_chan(UAS_PACK_CHAN(uas), &msg_mav, uas->get_tgt_system(), uas->get_tgt_component(), command, confirmation, param1, param2, param3, param4, param5, param6, param7); UAS_FCU(uas)->send_message(&msg_mav); ROS_INFO("Arming UAV"); } else { enum MAV_CMD command = MAV_CMD_COMPONENT_ARM_DISARM; float param1 = 0; //1-->arm 0-->disarm float param2 = 0; //not used float param3 = 0; //not used float param4 = 0; //not used float param5 = 0; //not used float param6 = 0; //not used float param7 = 0; //not used uint8_t confirmation = 1; mavlink_msg_command_long_pack_chan(UAS_PACK_CHAN(uas), &msg_mav, uas->get_tgt_system(), uas->get_tgt_component(), command, confirmation, param1, param2, param3, param4, param5, param6, param7); UAS_FCU(uas)->send_message(&msg_mav); //TODO decide if send or not disarm by software ROS_INFO("Disarming UAV"); } } }; }; // namespace mavplugin PLUGINLIB_EXPORT_CLASS(mavplugin::UniboControllerAMSLPlugin, mavplugin::MavRosPlugin) <commit_msg>added: software security check<commit_after>//#include <mavros/RCIn.h> #include <mavros/mavros_plugin.h> #include <pluginlib/class_list_macros.h> #include "mavros/OverrideRCIn.h" #include <guidance_node_amsl/Directive.h> #include <guidance_node_amsl/Position.h> #include <mms/Ack_arm.h> #include <mms/Arm.h> #include <mms/Sys_status.h> namespace mavplugin { /** * @brief Mavros plugin */ class UniboControllerAMSLPlugin : public MavRosPlugin { public: UniboControllerAMSLPlugin() : nodeHandle(), uas(nullptr), safetyOn(true), v_xy_max(3.0), v_z_max(1.5), v_psi_max(3.14) {}; void initialize(UAS &uas_) { uas = &uas_; directive_sub = nodeHandle.subscribe("/directive", 10, &UniboControllerAMSLPlugin::directive_cb, this); position_pub = nodeHandle.advertise<guidance_node_amsl::Position>("/position", 10); arm_sub = nodeHandle.subscribe("/arm", 10, &UniboControllerAMSLPlugin::arming, this); arm_ack_pub = nodeHandle.advertise<mms::Ack_arm>("acknowledge_arming", 10); //velocity_publisher_=nodeHandle.advertise<mavros::OverrideRCIn>("mavros/rc/override", 10); sys_status_pub = nodeHandle.advertise<mms::Sys_status>("/system_status", 10); nodeHandle.param("guidance_node_amsl/param/sat_xy", v_xy_max, 3.0); nodeHandle.param("guidance_node_amsl/param/sat_z", v_z_max, 1.5); nodeHandle.param("guidance_node_amsl/param/sat_yaw", v_psi_max, 3.14); //DEBUG // ROS_INFO("INITIALIZE UNIBO PLUGIN"); } //should be logic mapping between id number and message type const message_map get_rx_handlers() { return { MESSAGE_HANDLER(MAVLINK_MSG_ID_GLOBAL_POSITION_INT, &UniboControllerAMSLPlugin::handle_global_position_int), MESSAGE_HANDLER(MAVLINK_MSG_ID_ATTITUDE, &UniboControllerAMSLPlugin::handle_attitude), MESSAGE_HANDLER(MAVLINK_MSG_ID_RC_CHANNELS_RAW, &UniboControllerAMSLPlugin::handle_rc_channels_raw), MESSAGE_HANDLER(MAVLINK_MSG_ID_COMMAND_ACK, &UniboControllerAMSLPlugin::handle_arm_ack), MESSAGE_HANDLER(MAVLINK_MSG_ID_HEARTBEAT, &UniboControllerAMSLPlugin::handle_heartbeat), MESSAGE_HANDLER(MAVLINK_MSG_ID_SYS_STATUS, &UniboControllerAMSLPlugin::handle_status) }; } private: ros::NodeHandle nodeHandle; UAS *uas; ros::Publisher position_pub; ros::Subscriber directive_sub; //ros::Publisher velocity_publisher_; ros::Subscriber arm_sub; ros::Publisher arm_ack_pub; ros::Publisher sys_status_pub; mms::Sys_status _system_status; //message to move the quadcopter mavros::OverrideRCIn velocity_; //common message to join data from handles guidance_node_amsl::Position commonMessage; //safety flag bool safetyOn; //saturation parameters /* * Questi tipi di dato sono matlab per specifiche ros del param server. * Nel nodo "guidance_node" sono convertiti a float perchè la legge di guida matlab ha come input * dei float. Adesso non sono convertiti perchè tanto possono essere usati così */ double v_xy_max, v_z_max, v_psi_max; //check if safety is on void handle_rc_channels_raw(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_rc_channels_raw_t channels_raw; mavlink_msg_rc_channels_raw_decode(msg,&channels_raw); /* * If safety is on, chan5_raw must be less than 1200 */ //DEBUG //ROS_INFO("CHANNEL 6 IS: %u",channels_raw.chan6_raw); if(channels_raw.chan6_raw > 1700 && channels_raw.chan5_raw > 1300 && channels_raw.chan5_raw < 1700){ // ODROID_ON HIGHER THAN STABILIZE && LOWER THAN RTL --> LOITER safetyOn = false; commonMessage.Safety = 0; } else { safetyOn=true; commonMessage.Safety= 1; } //DEBUG // ROS_INFO("HANDLE RC RAW"); } void handle_attitude(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_attitude_t attitude; mavlink_msg_attitude_decode(msg, &attitude); auto position_msg = boost::make_shared<guidance_node_amsl::Position>(); //getting new data position_msg->Yawangle=attitude.yaw; //copying data from commonMessage position_msg->Timestamp=commonMessage.Timestamp; position_msg->AltitudeRelative=commonMessage.AltitudeRelative; position_msg->AltitudeAMSL=commonMessage.AltitudeAMSL; position_msg->Latitude=commonMessage.Latitude; position_msg->Longitude=commonMessage.Longitude; position_msg->Safety = commonMessage.Safety; //saving data commonMessage.Yawangle=attitude.yaw; //DEBUG // ROS_INFO("%f", commonMessage.Yawangle); position_pub.publish(position_msg); } void handle_heartbeat(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_heartbeat_t heart; mavlink_msg_heartbeat_decode(msg, &heart); //auto position_msg = boost::make_shared<guidance_node_amsl::Position>(); //ROS_INFO("Heatbeat. Base Mode: %d - Sys Status: %d ",heart.base_mode, heart.system_status); if (heart.base_mode >= 128) _system_status.armed = true; else _system_status.armed = false; sys_status_pub.publish(_system_status); } void handle_status(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_sys_status_t status; mavlink_msg_sys_status_decode(msg, &status); //ROS_INFO("Received sys status mavlink. Battery: %d", status.voltage_battery); _system_status.voltage_battery = status.voltage_battery; sys_status_pub.publish(_system_status); } void handle_arm_ack(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_command_ack_t cmd_ack; mavlink_msg_command_ack_decode(msg, &cmd_ack); auto arm_ack_msg = boost::make_shared<mms::Ack_arm>(); if (cmd_ack.command == 400){ //ARM_DISARM command ROS_INFO("Received arm_disarm"); if (cmd_ack.result == MAV_RESULT_ACCEPTED){ arm_ack_msg->mav_result = true; ROS_INFO("Arm-disarm: succsessful"); } else { arm_ack_msg->mav_result = false; ROS_INFO("Arm-disarm: fail"); } arm_ack_pub.publish(arm_ack_msg); } } void handle_global_position_int(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) { mavlink_global_position_int_t global_position; mavlink_msg_global_position_int_decode(msg, &global_position); auto position_msg = boost::make_shared<guidance_node_amsl::Position>(); //getting new data position_msg->Timestamp=global_position.time_boot_ms; position_msg->AltitudeRelative=global_position.relative_alt; position_msg->AltitudeAMSL = global_position.alt; position_msg->Latitude=global_position.lat; position_msg->Longitude=global_position.lon; //copying data from commonMessage position_msg->Yawangle=commonMessage.Yawangle; position_msg->Safety = commonMessage.Safety; //saving data commonMessage.Timestamp=global_position.time_boot_ms; commonMessage.AltitudeRelative=global_position.relative_alt; commonMessage.AltitudeAMSL=global_position.alt; commonMessage.Latitude=global_position.lat; commonMessage.Longitude=global_position.lon; //DEBUG // ROS_INFO("HANDLE POSITION"); position_pub.publish(position_msg); } /* * From directive to RC */ void directive_cb(const guidance_node_amsl::Directive::ConstPtr msg){ /* * Initializing values, if safety is on, these values will remain */ velocity_.channels[0]=0; velocity_.channels[1]=0; velocity_.channels[2]=0; velocity_.channels[3]=0; velocity_.channels[4]=0; velocity_.channels[5]=0; velocity_.channels[6]=0; velocity_.channels[7]=0; if(!safetyOn){ /* * If safety is off, I translate velocity in RC values */ uint16_t vx_RC= (uint16_t)400.0f*(-msg->vxBody)/v_xy_max + 1520; //New: 400 + 1520; Old: 500 + 1500 uint16_t vy_RC=(uint16_t)400.0f*(msg->vyBody)/v_xy_max + 1520; //New: 400 + 1520; Old: 500 + 1500 /* * it seems it loiters with 1420 instead of 1500... */ uint16_t vz_RC= 1420; if (msg->vzBody > 0){ //going down, mapped only in 420us vz_RC = vz_RC + (uint16_t)320.0f*(-msg->vzBody)/v_z_max; //New: 320; Old: 420 } else { //going up, mapped in 580us vz_RC = vz_RC + (uint16_t)480.0f*(-msg->vzBody)/v_z_max; //New: 480 Old: 580 } uint16_t v_psi_RC = (uint16_t)400.0f*(msg->yawRate)/v_psi_max + 1520; //New: 400 + 1520; Old: 500 + 1500 velocity_.channels[0]=vy_RC; velocity_.channels[1]=vx_RC; velocity_.channels[2]=vz_RC; velocity_.channels[3]=v_psi_RC; } //DEBUG /*ROS_INFO("RC_OVERRIDE: [CH1:%u, CH2:%u, CH3:%u, CH4:%u, CH5:%u, CH6:%u, CH7:%u, CH8:%u]", velocity_.channels[0], velocity_.channels[1], velocity_.channels[2], velocity_.channels[3], velocity_.channels[4], velocity_.channels[5], velocity_.channels[6], velocity_.channels[7]);*/ //velocity_publisher_.publish(velocity_); mavlink_message_t msg_mav; mavlink_msg_rc_channels_raw_pack_chan(UAS_PACK_CHAN(uas),&msg_mav,0,1,velocity_.channels[0],velocity_.channels[1],velocity_.channels[2],velocity_.channels[3],0,0,0,0,100); //1 is the sequence that we are not considering right now UAS_FCU(uas)->send_message(&msg_mav); } /* * Arming/disarming the UAV */ void arming(const mms::Arm::ConstPtr msg){ mavlink_message_t msg_mav; if (msg->arm_disarm){ enum MAV_CMD command = MAV_CMD_COMPONENT_ARM_DISARM; float param1 = 1; //1-->arm 0-->disarm float param2 = 0; //not used float param3 = 0; //not used float param4 = 0; //not used float param5 = 0; //not used float param6 = 0; //not used float param7 = 0; //not used uint8_t confirmation = 1; mavlink_msg_command_long_pack_chan(UAS_PACK_CHAN(uas), &msg_mav, uas->get_tgt_system(), uas->get_tgt_component(), command, confirmation, param1, param2, param3, param4, param5, param6, param7); UAS_FCU(uas)->send_message(&msg_mav); ROS_INFO("Arming UAV"); } else { enum MAV_CMD command = MAV_CMD_COMPONENT_ARM_DISARM; float param1 = 0; //1-->arm 0-->disarm float param2 = 0; //not used float param3 = 0; //not used float param4 = 0; //not used float param5 = 0; //not used float param6 = 0; //not used float param7 = 0; //not used uint8_t confirmation = 1; mavlink_msg_command_long_pack_chan(UAS_PACK_CHAN(uas), &msg_mav, uas->get_tgt_system(), uas->get_tgt_component(), command, confirmation, param1, param2, param3, param4, param5, param6, param7); UAS_FCU(uas)->send_message(&msg_mav); //TODO decide if send or not disarm by software ROS_INFO("Disarming UAV"); } } }; }; // namespace mavplugin PLUGINLIB_EXPORT_CLASS(mavplugin::UniboControllerAMSLPlugin, mavplugin::MavRosPlugin) <|endoftext|>
<commit_before>/* * NDC.hh * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_NDC_HH #define _LOG4CPP_NDC_HH #include <string> #include <vector> namespace log4cpp { class NDC { public: struct DiagnosticContext { DiagnosticContext(const std::string& message); DiagnosticContext(const std::string& message, const DiagnosticContext& parent); std::string message; std::string fullMessage; }; typedef vector<DiagnosticContext> ContextStack; static void clear(); static ContextStack* cloneStack(); static const std::string& get(); static int getDepth(); static void inherit(ContextStack* stack); static std::string pop(); static void push(const std::string& message); static void setMaxDepth(int maxDepth); static NDC& getNDC(); protected: NDC(); #if defined(__GNUG__) && (__GNUC__ == 2) && (__GNUC_MINOR__ <= 95) public: virtual ~NDC(); #else protected: virtual ~NDC(); #endif protected: virtual void _clear(); virtual ContextStack* _cloneStack(); virtual const std::string& _get() const; virtual int _getDepth() const; virtual void _inherit(ContextStack* stack); virtual std::string _pop(); virtual void _push(const std::string& message); virtual void _setMaxDepth(int maxDepth); ContextStack _stack; private: static NDC _nDC; }; } #endif // _LOG4CPP_NDC_HH <commit_msg>Making NDC() and ~NDC() protected was overly paranoid. They're public now.<commit_after>/* * NDC.hh * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_NDC_HH #define _LOG4CPP_NDC_HH #include <string> #include <vector> namespace log4cpp { class NDC { public: struct DiagnosticContext { DiagnosticContext(const std::string& message); DiagnosticContext(const std::string& message, const DiagnosticContext& parent); std::string message; std::string fullMessage; }; typedef vector<DiagnosticContext> ContextStack; static void clear(); static ContextStack* cloneStack(); static const std::string& get(); static int getDepth(); static void inherit(ContextStack* stack); static std::string pop(); static void push(const std::string& message); static void setMaxDepth(int maxDepth); static NDC& getNDC(); NDC(); virtual ~NDC(); protected: virtual void _clear(); virtual ContextStack* _cloneStack(); virtual const std::string& _get() const; virtual int _getDepth() const; virtual void _inherit(ContextStack* stack); virtual std::string _pop(); virtual void _push(const std::string& message); virtual void _setMaxDepth(int maxDepth); ContextStack _stack; private: static NDC _nDC; }; } #endif // _LOG4CPP_NDC_HH <|endoftext|>
<commit_before>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); }<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); }<|endoftext|>
<commit_before>#define STR_EXPAND(tok) #tok #define STR(tok) STR_EXPAND(tok) #include "ros_visitor.hpp" #include <QStandardPaths> #include <algorithm> #include <filesystem> #include <memory> #include <nlohmann/json_fwd.hpp> #include <regex> #include <string> #include "label.hpp" #include "inja/inja.hpp" #include "node.hpp" using namespace std; namespace fs = std::filesystem; vector<string> split(string s, const char separator) { istringstream ss; ss.str(s); string segment; std::vector<std::string> seglist; while (std::getline(ss, segment, separator)) { seglist.push_back(segment); } return seglist; } bool contains(const nlohmann::json& container, const nlohmann::json& value) { for (const auto& i : container) { if (i[0] == value[0] && i[1] == value[1]) { return true; } } return false; } tuple<string, string> prepareTopic(string topic_in) { string topic(topic_in); // ROS4HRI regex human_faces_regex("/h/f/\\*/(.*)", regex_constants::ECMAScript); smatch faces; if (regex_search(topic_in, faces, human_faces_regex)) { return {string("/humans/faces/<id>/") + string(faces[1]), string("face_") + string(faces[1])}; } regex human_bodies_regex("/h/b/\\*/(.*)", regex_constants::ECMAScript); smatch bodies; if (regex_search(topic_in, bodies, human_bodies_regex)) { return {string("/humans/bodies/<id>/") + string(bodies[1]), string("body_") + string(bodies[1])}; } regex human_voices_regex("/h/v/\\*/(.*)", regex_constants::ECMAScript); smatch voices; if (regex_search(topic_in, voices, human_voices_regex)) { return {string("/humans/voices/<id>/") + string(voices[1]), string("voice_") + string(voices[1])}; } regex human_persons_regex("/h/f/\\*/(.*)", regex_constants::ECMAScript); smatch persons; if (regex_search(topic_in, persons, human_persons_regex)) { return {string("/humans/persons/<id>/") + string(persons[1]), string("person_") + string(persons[1])}; } auto shortname = split(topic, '/').back(); return {topic, shortname}; } RosVisitor::RosVisitor(const Architecture& architecture, const string& ws_path) : Visitor(architecture), ws_path(ws_path) { fs::path tpl_path; for (auto p : QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)) { tpl_path = fs::path(p.toStdString()) / "templates" / "ros"; cout << "Looking for ROS templates in " << tpl_path << endl; if (fs::exists(tpl_path)) { break; } } if (!tpl_path.empty()) { cout << "Using ROS templates found at " << tpl_path << endl; env_ = make_unique<inja::Environment>( (tpl_path / "default").string() + fs::path::preferred_separator, ws_path + fs::path::preferred_separator); env_->set_line_statement("$$$$$"); env_->set_trim_blocks(true); env_->set_lstrip_blocks(true); env_main_node_ = make_unique<inja::Environment>( (tpl_path / "main_node").string() + fs::path::preferred_separator, ws_path + fs::path::preferred_separator); env_main_node_->set_line_statement("$$$$$"); env_main_node_->set_trim_blocks(true); env_main_node_->set_lstrip_blocks(true); } else { cout << "[EE] ROS templates not found! Can not generate ROS nodes." << endl; } } void RosVisitor::startUp() { data_["path"] = ws_path; data_["name"] = architecture.name; auto [id, id_capitalized] = make_id(architecture.name); data_["id"] = id; data_["boxology_version"] = STR(BOXOLOGY_VERSION); data_["version"] = architecture.version; data_["description"] = architecture.description; } void RosVisitor::tearDown() { if (!env_) return; /////////////////////////////////////////////////////// // Create parent node with main launchfile // vector<string> main_node_tpls{"package.xml", "CMakeLists.txt", "launch/start_all.launch"}; auto [id, id_capitalized] = make_id(architecture.name); auto rel_path = fs::path("src") / id; auto abs_path = fs::path(ws_path) / rel_path; auto launch_path = abs_path / "launch"; fs::create_directories(launch_path); // will also create 'path' for (const auto& file : main_node_tpls) { auto tpl = env_main_node_->parse_template(file); env_main_node_->write(tpl, data_, (rel_path / file).string()); } /////////////////////////////////////////////////////// // Create all the nodes // vector<string> default_tpls{"package.xml", "CMakeLists.txt", "src/main.cpp"}; for (auto node : data_["nodes"]) { string id(node["id"]); cout << "Generating " << node["name"] << " as node [" << id << "]..." << endl; auto rel_path = fs::path("src") / id; auto abs_path = fs::path(ws_path) / rel_path; auto src_path = abs_path / "src"; fs::create_directories(src_path); // will also create 'path' for (const auto& file : default_tpls) { auto tpl = env_->parse_template(file); // cout << "\t- " << (abs_path / file).string() << endl; env_->write(tpl, node, (rel_path / file).string()); } } cout << "Generation of ROS nodes complete. The generated nodes can be " "found in " << ws_path << endl; } void RosVisitor::beginNodes() {} void RosVisitor::onNode(shared_ptr<const Node> node) { // ignore TF nodes if (node->name() == "TF" || node->name() == "tf") return; nlohmann::json jnode; auto name = node->name().substr(0, node->name().find("[")); auto [id, id_capitalized] = make_id(name); jnode["id"] = id; jnode["id_capitalized"] = id_capitalized; jnode["name"] = name; jnode["label"] = LABEL_NAMES.at(node->label()); jnode["dependencies"] = nlohmann::json::array(); jnode["boxology_version"] = STR(BOXOLOGY_VERSION); if (node->sub_architecture) { jnode["version"] = node->sub_architecture->version; jnode["description"] = node->sub_architecture->description; } else { jnode["version"] = "1.0.0"; jnode["description"] = ""; } ////////////////////////////////////////////// // Ports // jnode["inputs"] = nlohmann::json::array(); jnode["outputs"] = nlohmann::json::array(); for (auto p : node->ports()) { nlohmann::json jport; bool isInput = (p->direction == Port::Direction::IN); auto name = p->name; jport["name"] = name; regex topic_regex("^(/.*) \\[(.*)\\]$", regex_constants::ECMAScript); smatch topic_matches; regex tf_regex("^tf: (.*)$", regex_constants::ECMAScript); smatch tf_matches; if (regex_search(name, topic_matches, topic_regex)) { jport["type"] = "topic"; auto [topic, shortname] = prepareTopic(topic_matches[1]); jport["topic"] = topic; jport["short"] = shortname; auto type = split(topic_matches[2], '/'); jport["datatype"] = {type.front(), type.back()}; if (!contains(jnode["dependencies"], jport["datatype"])) { jnode["dependencies"].push_back(jport["datatype"]); } cout << "[II] Node " << jnode["id"] << ": " << (isInput ? "subscribes to" : "publishes") << " topic " << jport["topic"] << " (short: " << jport["short"] << ") of type " << jport["type"] << endl; } else if (regex_search(name, tf_matches, tf_regex)) { jport["type"] = "tf"; jport["frame"] = tf_matches[1]; if (isInput) { jport["datatype"] = {"tf", "transform_listener"}; } else { jport["datatype"] = {"tf", "transform_broadcaster"}; } if (!contains(jnode["dependencies"], jport["datatype"])) { jnode["dependencies"].push_back(jport["datatype"]); } cout << "[II] Node " << jnode["id"] << ": " << (isInput ? "listen to" : "broadcasts") << " TF frame " << jport["frame"] << endl; } else { jport["type"] = "undefined"; auto [id, id_capitalized] = make_id(name); jport["topic"] = id; jport["short"] = id; jport["datatype"] = {"std_msgs", "Empty"}; if (!contains(jnode["dependencies"], jport["datatype"])) { jnode["dependencies"].push_back(jport["datatype"]); } } if (isInput) { jnode["inputs"].push_back(jport); } else { jnode["outputs"].push_back(jport); } } // ensure package dependencies are only listed *one* time // otherwise catkin complains. set<string> packages; for (const auto& dep : jnode["dependencies"]) { packages.insert(string(dep[0])); } for (const auto& p : packages) { jnode["packages"].push_back(p); } data_["nodes"].push_back(jnode); nodes_.push_back(node); } void RosVisitor::endNodes() {} void RosVisitor::beginConnections() {} void RosVisitor::onConnection(shared_ptr<const Connection> connection) {} <commit_msg>remove 'DEPENDENCY: ' from node name if present<commit_after>#define STR_EXPAND(tok) #tok #define STR(tok) STR_EXPAND(tok) #include "ros_visitor.hpp" #include <QStandardPaths> #include <algorithm> #include <filesystem> #include <memory> #include <nlohmann/json_fwd.hpp> #include <regex> #include <string> #include "inja/inja.hpp" #include "label.hpp" #include "node.hpp" using namespace std; namespace fs = std::filesystem; vector<string> split(string s, const char separator) { istringstream ss; ss.str(s); string segment; std::vector<std::string> seglist; while (std::getline(ss, segment, separator)) { seglist.push_back(segment); } return seglist; } bool contains(const nlohmann::json& container, const nlohmann::json& value) { for (const auto& i : container) { if (i[0] == value[0] && i[1] == value[1]) { return true; } } return false; } tuple<string, string> prepareTopic(string topic_in) { string topic(topic_in); // ROS4HRI regex human_faces_regex("/h/f/\\*/(.*)", regex_constants::ECMAScript); smatch faces; if (regex_search(topic_in, faces, human_faces_regex)) { return {string("/humans/faces/<id>/") + string(faces[1]), string("face_") + string(faces[1])}; } regex human_bodies_regex("/h/b/\\*/(.*)", regex_constants::ECMAScript); smatch bodies; if (regex_search(topic_in, bodies, human_bodies_regex)) { return {string("/humans/bodies/<id>/") + string(bodies[1]), string("body_") + string(bodies[1])}; } regex human_voices_regex("/h/v/\\*/(.*)", regex_constants::ECMAScript); smatch voices; if (regex_search(topic_in, voices, human_voices_regex)) { return {string("/humans/voices/<id>/") + string(voices[1]), string("voice_") + string(voices[1])}; } regex human_persons_regex("/h/f/\\*/(.*)", regex_constants::ECMAScript); smatch persons; if (regex_search(topic_in, persons, human_persons_regex)) { return {string("/humans/persons/<id>/") + string(persons[1]), string("person_") + string(persons[1])}; } auto shortname = split(topic, '/').back(); return {topic, shortname}; } RosVisitor::RosVisitor(const Architecture& architecture, const string& ws_path) : Visitor(architecture), ws_path(ws_path) { fs::path tpl_path; for (auto p : QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)) { tpl_path = fs::path(p.toStdString()) / "templates" / "ros"; cout << "Looking for ROS templates in " << tpl_path << endl; if (fs::exists(tpl_path)) { break; } } if (!tpl_path.empty()) { cout << "Using ROS templates found at " << tpl_path << endl; env_ = make_unique<inja::Environment>( (tpl_path / "default").string() + fs::path::preferred_separator, ws_path + fs::path::preferred_separator); env_->set_line_statement("$$$$$"); env_->set_trim_blocks(true); env_->set_lstrip_blocks(true); env_main_node_ = make_unique<inja::Environment>( (tpl_path / "main_node").string() + fs::path::preferred_separator, ws_path + fs::path::preferred_separator); env_main_node_->set_line_statement("$$$$$"); env_main_node_->set_trim_blocks(true); env_main_node_->set_lstrip_blocks(true); } else { cout << "[EE] ROS templates not found! Can not generate ROS nodes." << endl; } } void RosVisitor::startUp() { data_["path"] = ws_path; data_["name"] = architecture.name; auto [id, id_capitalized] = make_id(architecture.name); data_["id"] = id; data_["boxology_version"] = STR(BOXOLOGY_VERSION); data_["version"] = architecture.version; data_["description"] = architecture.description; } void RosVisitor::tearDown() { if (!env_) return; /////////////////////////////////////////////////////// // Create parent node with main launchfile // vector<string> main_node_tpls{"package.xml", "CMakeLists.txt", "launch/start_all.launch"}; auto [id, id_capitalized] = make_id(architecture.name); auto rel_path = fs::path("src") / id; auto abs_path = fs::path(ws_path) / rel_path; auto launch_path = abs_path / "launch"; fs::create_directories(launch_path); // will also create 'path' for (const auto& file : main_node_tpls) { auto tpl = env_main_node_->parse_template(file); env_main_node_->write(tpl, data_, (rel_path / file).string()); } /////////////////////////////////////////////////////// // Create all the nodes // vector<string> default_tpls{"package.xml", "CMakeLists.txt", "src/main.cpp"}; for (auto node : data_["nodes"]) { string id(node["id"]); cout << "Generating " << node["name"] << " as node [" << id << "]..." << endl; auto rel_path = fs::path("src") / id; auto abs_path = fs::path(ws_path) / rel_path; auto src_path = abs_path / "src"; fs::create_directories(src_path); // will also create 'path' for (const auto& file : default_tpls) { auto tpl = env_->parse_template(file); // cout << "\t- " << (abs_path / file).string() << endl; env_->write(tpl, node, (rel_path / file).string()); } } cout << "Generation of ROS nodes complete. The generated nodes can be " "found in " << ws_path << endl; } void RosVisitor::beginNodes() {} void RosVisitor::onNode(shared_ptr<const Node> node) { // ignore TF nodes if (node->name() == "TF" || node->name() == "tf") return; nlohmann::json jnode; auto name = node->name().substr(0, node->name().find("[")); if (name.find("DEPENDENCY:") != string::npos) { name = name.substr(string("DEPENDENCY:").size()); } auto [id, id_capitalized] = make_id(name); jnode["id"] = id; jnode["id_capitalized"] = id_capitalized; jnode["name"] = name; jnode["label"] = LABEL_NAMES.at(node->label()); jnode["dependencies"] = nlohmann::json::array(); jnode["boxology_version"] = STR(BOXOLOGY_VERSION); if (node->sub_architecture) { jnode["version"] = node->sub_architecture->version; jnode["description"] = node->sub_architecture->description; } else { jnode["version"] = "1.0.0"; jnode["description"] = ""; } ////////////////////////////////////////////// // Ports // jnode["inputs"] = nlohmann::json::array(); jnode["outputs"] = nlohmann::json::array(); for (auto p : node->ports()) { nlohmann::json jport; bool isInput = (p->direction == Port::Direction::IN); auto name = p->name; jport["name"] = name; regex topic_regex("^(/.*) \\[(.*)\\]$", regex_constants::ECMAScript); smatch topic_matches; regex tf_regex("^tf: (.*)$", regex_constants::ECMAScript); smatch tf_matches; if (regex_search(name, topic_matches, topic_regex)) { jport["type"] = "topic"; auto [topic, shortname] = prepareTopic(topic_matches[1]); jport["topic"] = topic; jport["short"] = shortname; auto type = split(topic_matches[2], '/'); jport["datatype"] = {type.front(), type.back()}; if (!contains(jnode["dependencies"], jport["datatype"])) { jnode["dependencies"].push_back(jport["datatype"]); } cout << "[II] Node " << jnode["id"] << ": " << (isInput ? "subscribes to" : "publishes") << " topic " << jport["topic"] << " (short: " << jport["short"] << ") of type " << jport["type"] << endl; } else if (regex_search(name, tf_matches, tf_regex)) { jport["type"] = "tf"; jport["frame"] = tf_matches[1]; if (isInput) { jport["datatype"] = {"tf", "transform_listener"}; } else { jport["datatype"] = {"tf", "transform_broadcaster"}; } if (!contains(jnode["dependencies"], jport["datatype"])) { jnode["dependencies"].push_back(jport["datatype"]); } cout << "[II] Node " << jnode["id"] << ": " << (isInput ? "listen to" : "broadcasts") << " TF frame " << jport["frame"] << endl; } else { jport["type"] = "undefined"; auto [id, id_capitalized] = make_id(name); jport["topic"] = id; jport["short"] = id; jport["datatype"] = {"std_msgs", "Empty"}; if (!contains(jnode["dependencies"], jport["datatype"])) { jnode["dependencies"].push_back(jport["datatype"]); } } if (isInput) { jnode["inputs"].push_back(jport); } else { jnode["outputs"].push_back(jport); } } // ensure package dependencies are only listed *one* time // otherwise catkin complains. set<string> packages; for (const auto& dep : jnode["dependencies"]) { packages.insert(string(dep[0])); } for (const auto& p : packages) { jnode["packages"].push_back(p); } data_["nodes"].push_back(jnode); nodes_.push_back(node); } void RosVisitor::endNodes() {} void RosVisitor::beginConnections() {} void RosVisitor::onConnection(shared_ptr<const Connection> connection) {} <|endoftext|>
<commit_before>// Each task has an entry in the ObjectArchive, which is described in this file. // // The entry is composed of a set of keys required to compute the task and get // its value. Additionally, flags "should_save" and "run_locally", the same in // ComputingUnit, are provided for faster and easier management, as the unit // would have to be loaded otherwise. // // As the id of the computing unit is required to call it, a key to it is stored // in the entry. This may lead to data duplication (all nodes can create // differente keys for the same id), but allows faster lookup and transmission. #ifndef __TASK_DISTRIBUTION__TASK_ENTRY_HPP__ #define __TASK_DISTRIBUTION__TASK_ENTRY_HPP__ #include "key.hpp" namespace TaskDistribution { // Archive entry for a task, having all values required work with it. struct TaskEntry { Key task_key; // Key to this entry Key computing_unit_key; // Key to the computing unit Key arguments_key; // Key to the tuple of arguments Key arguments_tasks_key; // Key to the tuple of tasks as arguments Key result_key; // Key to the result Key computing_unit_id_key; // Key to the unit id Key parents_key; // Key to a list of keys of parent tasks Key children_key; // Key to a list of keys of children tasks size_t active_parents; // Number of parents that have to be computed bool run_locally; TaskEntry(): active_parents(0), run_locally(false) { } template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & task_key; ar & computing_unit_key; ar & arguments_key; ar & arguments_tasks_key; ar & result_key; ar & computing_unit_id_key; ar & parents_key; ar & children_key; ar & active_parents; ar & run_locally; } }; }; // Enables faster MPI transmission. #if ENABLE_MPI BOOST_IS_MPI_DATATYPE(TaskDistribution::TaskEntry); #endif #endif <commit_msg>Added documentation to task_entry.hpp.<commit_after>// Each task has an entry in the ObjectArchive, which is described in this file. // // The entry is composed of a set of keys required to compute the task and get // its value. Additionally, a flag "run_locally", the same in ComputingUnit, is // provided for faster and easier management, as the unit would have to be // loaded otherwise. // // As the id of the computing unit is required to call it, a key to it is stored // in the entry. This may lead to data duplication (all nodes can create // different keys for the same id), but allows faster lookup and transmission. #ifndef __TASK_DISTRIBUTION__TASK_ENTRY_HPP__ #define __TASK_DISTRIBUTION__TASK_ENTRY_HPP__ #include "key.hpp" namespace TaskDistribution { // Archive entry for a task, having all values required work with it. struct TaskEntry { Key task_key; // Key to this entry Key computing_unit_key; // Key to the computing unit Key arguments_key; // Key to the tuple of arguments Key arguments_tasks_key; // Key to the tuple of tasks as arguments Key result_key; // Key to the result Key computing_unit_id_key; // Key to the unit id Key parents_key; // Key to a list of keys of parent tasks Key children_key; // Key to a list of keys of children tasks size_t active_parents; // Number of parents that have to be computed bool run_locally; TaskEntry(): active_parents(0), run_locally(false) { } template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & task_key; ar & computing_unit_key; ar & arguments_key; ar & arguments_tasks_key; ar & result_key; ar & computing_unit_id_key; ar & parents_key; ar & children_key; ar & active_parents; ar & run_locally; } }; }; // Enables faster MPI transmission. #if ENABLE_MPI BOOST_IS_MPI_DATATYPE(TaskDistribution::TaskEntry); #endif #endif <|endoftext|>
<commit_before>#ifndef INCLUDED_U5E_FILTER #define INCLUDED_U5E_FILTER namespace u5e { /** * \brief Walks an input iterator through a filter * * This will go from the begin to the end of the input iterator and * will execute the filter function once for every input element. * * Unlike std::transform, the filter function does not return the * output element, but it receives the output object and will do * whatever makes sense with the output object. * * That means that the type of filter will define what type of * object can be used as output. The filter function itself will not * touch the output object, but simply forward it to the operator * function. * * The operator function returns an int that is meant to indicate * how much output was produced. The filter function will accumulate * those values and return the sum. * * The filter is not required to produce a constant number of * outputs for each input. The function can be produce many outputs * or even none at all during the processing of each element. * * The value type for input and output is not required to be the * same. The input type is resolved by the value_type member type of * the input iterator type. * * \tparam InputIteratorType the type of the input iterator * \tparam OutputType the type of the output iterator * \tparam Functor the callback function type called for each element * * \param input_from starting position for the input iterator * \param input_to end position for the input iterator * \param output output container sent to the operator function * \param operation function that takes the element, the output * container and returns the number of outputted elements */ template <typename InputIteratorType, typename OutputType, typename Functor > inline int filter(InputIteratorType input_from, InputIteratorType input_to, OutputType& output, Functor operation) { int counter = 0; while (input_from != input_to) { counter += operation(*input_from, output); input_from++; } return counter; } } #endif <commit_msg>More explicit coding to make it easier to debug<commit_after>#ifndef INCLUDED_U5E_FILTER #define INCLUDED_U5E_FILTER namespace u5e { /** * \brief Walks an input iterator through a filter * * This will go from the begin to the end of the input iterator and * will execute the filter function once for every input element. * * Unlike std::transform, the filter function does not return the * output element, but it receives the output object and will do * whatever makes sense with the output object. * * That means that the type of filter will define what type of * object can be used as output. The filter function itself will not * touch the output object, but simply forward it to the operator * function. * * The operator function returns an int that is meant to indicate * how much output was produced. The filter function will accumulate * those values and return the sum. * * The filter is not required to produce a constant number of * outputs for each input. The function can be produce many outputs * or even none at all during the processing of each element. * * The value type for input and output is not required to be the * same. The input type is resolved by the value_type member type of * the input iterator type. * * \tparam InputIteratorType the type of the input iterator * \tparam OutputType the type of the output iterator * \tparam Functor the callback function type called for each element * * \param input_from starting position for the input iterator * \param input_to end position for the input iterator * \param output output container sent to the operator function * \param operation function that takes the element, the output * container and returns the number of outputted elements */ template <typename InputIteratorType, typename OutputType, typename Functor > inline int filter(InputIteratorType input_from, InputIteratorType input_to, OutputType& output, Functor operation) { int counter = 0; while (input_from != input_to) { typename InputIteratorType::value_type item = *input_from; counter += operation(item, output); input_from++; } return counter; } } #endif <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2022 * * * * 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 "sgctedit/filesupport.h" FileSupport::FileSupport(QVBoxLayout* parentLayout, UserConfigurationElements& cfgElements, SgctConfigElements& sgctElements, std::function<void(bool)> finishedCallback) : _displayWidget(cfgElements.display) , _orientationWidget(cfgElements.orientation) , _monitors(cfgElements.monitorList) , _cluster(sgctElements.cluster) , _windowList(sgctElements.windowList) , _finishedCallback(finishedCallback) , _userConfigPath(cfgElements.configSavePath) { QVBoxLayout* layoutFullVertical = new QVBoxLayout; _saveButton = new QPushButton("Save As"); _saveButton->setToolTip("Save configuration changes (opens file chooser dialog)"); connect(_saveButton, &QPushButton::released, this, &FileSupport::save); _cancelButton = new QPushButton("Cancel"); _cancelButton->setToolTip("Cancel changes"); connect(_cancelButton, &QPushButton::released, this, &FileSupport::cancel); _applyButton = new QPushButton("Apply Without Saving"); _applyButton->setToolTip("Apply configuration changes without saving to file"); connect(_applyButton, &QPushButton::released, this, &FileSupport::apply); { QHBoxLayout* layoutButtonBox = new QHBoxLayout; layoutButtonBox->addStretch(1); layoutButtonBox->addWidget(_cancelButton); layoutButtonBox->addWidget(_saveButton); layoutButtonBox->addWidget(_applyButton); layoutFullVertical->addLayout(layoutButtonBox); } parentLayout->addLayout(layoutFullVertical); } void FileSupport::saveCluster() { if (_orientationWidget) { sgct::config::Scene initScene; initScene.orientation = _orientationWidget->orientationValue(); _cluster.nodes.clear(); sgct::config::Node tmpNode; tmpNode.address = "localhost"; tmpNode.port = 20401; _cluster.nodes.push_back(tmpNode); _cluster.masterAddress = "localhost"; _cluster.scene = std::move(initScene); _cluster.firmSync = _orientationWidget->vsyncValue(); } } void FileSupport::saveUser() { if (_orientationWidget) { sgct::config::User user; user.eyeSeparation = 0.065f; user.position = {0.0f, 0.0f, 4.0f}; _cluster.users.push_back(user); } } bool FileSupport::isWindowFullscreen(unsigned int monitorIdx, sgct::ivec2 wDims) { return (_monitors[monitorIdx].width() == wDims.x && _monitors[monitorIdx].height() == wDims.y); } std::optional<unsigned int> FileSupport::findGuiWindow() { unsigned int windowIndex = 0; for (unsigned int w = 0; w < _displayWidget->nWindows(); ++w) { if (_displayWidget->windowControls()[w]->isGuiWindow()) { return std::optional<unsigned int>(windowIndex); } windowIndex++; } return std::nullopt; } void FileSupport::saveWindows() { unsigned int windowIndex = 0; for (unsigned int w = 0; w < _displayWidget->nWindows(); ++w) { std::shared_ptr<WindowControl> wCtrl = _displayWidget->windowControls()[w]; sgct::config::Window tmpWindow = saveWindowsDimensions(wCtrl); tmpWindow.viewports.push_back(generateViewport()); tmpWindow.viewports.back().projection = saveProjectionInformation(wCtrl); tmpWindow.isDecorated = wCtrl->isDecorated(); tmpWindow.isFullScreen = isWindowFullscreen( wCtrl->monitorNum(), wCtrl->windowSize() ); saveWindowsWebGui(windowIndex, tmpWindow); if (!wCtrl->windowName().empty()) { tmpWindow.name = wCtrl->windowName(); } tmpWindow.id = windowIndex++; _windowList.push_back(tmpWindow); } } sgct::config::Viewport FileSupport::generateViewport() { sgct::config::Viewport vp; vp.isTracked = true; vp.position = {0.f, 0.f}; vp.size = {1.f, 1.f}; return vp; } sgct::config::Window FileSupport::saveWindowsDimensions( std::shared_ptr<WindowControl> wCtrl) { sgct::config::Window tmpWindow; tmpWindow.size = wCtrl->windowSize(); tmpWindow.pos = { _monitors[wCtrl->monitorNum()].x() + wCtrl->windowPos().x, _monitors[wCtrl->monitorNum()].y() + wCtrl->windowPos().y, }; return tmpWindow; } void FileSupport::saveWindowsWebGui(unsigned int wIdx, sgct::config::Window& win) { win.viewports.back().isTracked = true; std::optional<unsigned int> webGuiWindowIndex = findGuiWindow(); bool isOneOfWindowsSetAsWebGui = webGuiWindowIndex.has_value(); if (isOneOfWindowsSetAsWebGui) { if (wIdx == webGuiWindowIndex.value()) { win.viewports.back().isTracked = false; win.tags.push_back("GUI"); } win.draw2D = (wIdx == webGuiWindowIndex.value()); win.draw3D = !(win.draw2D.value()); } } ProjectionOptions FileSupport::saveProjectionInformation( std::shared_ptr<WindowControl> winControl) { if (winControl->isSpoutSelected()) { return saveProjectionSpout(winControl); } else { return saveProjectionNoSpout(winControl); } } ProjectionOptions FileSupport::saveProjectionSpout( std::shared_ptr<WindowControl> winControl) { sgct::config::SpoutOutputProjection projection; switch(winControl->projectionSelectedIndex()) { case WindowControl::ProjectionIndeces::Fisheye: projection.mapping = sgct::config::SpoutOutputProjection::Mapping::Fisheye; break; case WindowControl::ProjectionIndeces::Equirectangular: default: projection.mapping = sgct::config::SpoutOutputProjection::Mapping::Equirectangular; break; } projection.quality = winControl->qualitySelectedValue(); projection.mappingSpoutName = "OpenSpace"; return projection; } ProjectionOptions FileSupport::saveProjectionNoSpout( std::shared_ptr<WindowControl> winControl) { switch(winControl->projectionSelectedIndex()) { case WindowControl::ProjectionIndeces::Fisheye: { sgct::config::FisheyeProjection projection; projection.quality = winControl->qualitySelectedValue(); projection.fov = 180.f; projection.tilt = 0.f; return projection; } break; case WindowControl::ProjectionIndeces::SphericalMirror: { sgct::config::SphericalMirrorProjection projection; projection.quality = winControl->qualitySelectedValue(); return projection; } break; case WindowControl::ProjectionIndeces::Cylindrical: { sgct::config::CylindricalProjection projection; projection.quality = winControl->qualitySelectedValue(); projection.heightOffset = winControl->heightOffset(); return projection; } break; case WindowControl::ProjectionIndeces::Equirectangular: { sgct::config::EquirectangularProjection projection; projection.quality = winControl->qualitySelectedValue(); return projection; } break; case WindowControl::ProjectionIndeces::Planar: default: { // The negative values for left & down are according to sgct's convention sgct::config::PlanarProjection projection; projection.fov.right = winControl->fovH() / 2.0; projection.fov.left = -projection.fov.right; projection.fov.up = winControl->fovV() / 2.0; projection.fov.down = -projection.fov.up; return projection; } break; } } std::string FileSupport::saveFilename() { return _saveTarget; } void FileSupport::save() { QString fileName = QFileDialog::getSaveFileName(this, "Save Window Configuration File", QString::fromStdString(_userConfigPath), "Window Configuration (*.json);;(*.json)", nullptr, QFileDialog::DontUseNativeDialog); if (fileName.length() != 0) { _saveTarget = fileName.toStdString(); saveConfigToSgctFormat(); _finishedCallback(true); } } void FileSupport::cancel() { _finishedCallback(false); } void FileSupport::apply() { std::string userCfgTempDir = _userConfigPath; if (userCfgTempDir.back() != '/') { userCfgTempDir += "/"; } userCfgTempDir += "temp"; if (!std::filesystem::is_directory(userCfgTempDir)) { std::filesystem::create_directories(absPath(userCfgTempDir)); } _saveTarget = userCfgTempDir + "/" + "apply-without-saving.json"; saveConfigToSgctFormat(); _finishedCallback(true); } void FileSupport::saveConfigToSgctFormat() { saveCluster(); saveWindows(); saveUser(); } <commit_msg>Change option for native OS file chooser dialog to linux only<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2022 * * * * 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 "sgctedit/filesupport.h" FileSupport::FileSupport(QVBoxLayout* parentLayout, UserConfigurationElements& cfgElements, SgctConfigElements& sgctElements, std::function<void(bool)> finishedCallback) : _displayWidget(cfgElements.display) , _orientationWidget(cfgElements.orientation) , _monitors(cfgElements.monitorList) , _cluster(sgctElements.cluster) , _windowList(sgctElements.windowList) , _finishedCallback(finishedCallback) , _userConfigPath(cfgElements.configSavePath) { QVBoxLayout* layoutFullVertical = new QVBoxLayout; _saveButton = new QPushButton("Save As"); _saveButton->setToolTip("Save configuration changes (opens file chooser dialog)"); connect(_saveButton, &QPushButton::released, this, &FileSupport::save); _cancelButton = new QPushButton("Cancel"); _cancelButton->setToolTip("Cancel changes"); connect(_cancelButton, &QPushButton::released, this, &FileSupport::cancel); _applyButton = new QPushButton("Apply Without Saving"); _applyButton->setToolTip("Apply configuration changes without saving to file"); connect(_applyButton, &QPushButton::released, this, &FileSupport::apply); { QHBoxLayout* layoutButtonBox = new QHBoxLayout; layoutButtonBox->addStretch(1); layoutButtonBox->addWidget(_cancelButton); layoutButtonBox->addWidget(_saveButton); layoutButtonBox->addWidget(_applyButton); layoutFullVertical->addLayout(layoutButtonBox); } parentLayout->addLayout(layoutFullVertical); } void FileSupport::saveCluster() { if (_orientationWidget) { sgct::config::Scene initScene; initScene.orientation = _orientationWidget->orientationValue(); _cluster.nodes.clear(); sgct::config::Node tmpNode; tmpNode.address = "localhost"; tmpNode.port = 20401; _cluster.nodes.push_back(tmpNode); _cluster.masterAddress = "localhost"; _cluster.scene = std::move(initScene); _cluster.firmSync = _orientationWidget->vsyncValue(); } } void FileSupport::saveUser() { if (_orientationWidget) { sgct::config::User user; user.eyeSeparation = 0.065f; user.position = {0.0f, 0.0f, 4.0f}; _cluster.users.push_back(user); } } bool FileSupport::isWindowFullscreen(unsigned int monitorIdx, sgct::ivec2 wDims) { return (_monitors[monitorIdx].width() == wDims.x && _monitors[monitorIdx].height() == wDims.y); } std::optional<unsigned int> FileSupport::findGuiWindow() { unsigned int windowIndex = 0; for (unsigned int w = 0; w < _displayWidget->nWindows(); ++w) { if (_displayWidget->windowControls()[w]->isGuiWindow()) { return std::optional<unsigned int>(windowIndex); } windowIndex++; } return std::nullopt; } void FileSupport::saveWindows() { unsigned int windowIndex = 0; for (unsigned int w = 0; w < _displayWidget->nWindows(); ++w) { std::shared_ptr<WindowControl> wCtrl = _displayWidget->windowControls()[w]; sgct::config::Window tmpWindow = saveWindowsDimensions(wCtrl); tmpWindow.viewports.push_back(generateViewport()); tmpWindow.viewports.back().projection = saveProjectionInformation(wCtrl); tmpWindow.isDecorated = wCtrl->isDecorated(); tmpWindow.isFullScreen = isWindowFullscreen( wCtrl->monitorNum(), wCtrl->windowSize() ); saveWindowsWebGui(windowIndex, tmpWindow); if (!wCtrl->windowName().empty()) { tmpWindow.name = wCtrl->windowName(); } tmpWindow.id = windowIndex++; _windowList.push_back(tmpWindow); } } sgct::config::Viewport FileSupport::generateViewport() { sgct::config::Viewport vp; vp.isTracked = true; vp.position = {0.f, 0.f}; vp.size = {1.f, 1.f}; return vp; } sgct::config::Window FileSupport::saveWindowsDimensions( std::shared_ptr<WindowControl> wCtrl) { sgct::config::Window tmpWindow; tmpWindow.size = wCtrl->windowSize(); tmpWindow.pos = { _monitors[wCtrl->monitorNum()].x() + wCtrl->windowPos().x, _monitors[wCtrl->monitorNum()].y() + wCtrl->windowPos().y, }; return tmpWindow; } void FileSupport::saveWindowsWebGui(unsigned int wIdx, sgct::config::Window& win) { win.viewports.back().isTracked = true; std::optional<unsigned int> webGuiWindowIndex = findGuiWindow(); bool isOneOfWindowsSetAsWebGui = webGuiWindowIndex.has_value(); if (isOneOfWindowsSetAsWebGui) { if (wIdx == webGuiWindowIndex.value()) { win.viewports.back().isTracked = false; win.tags.push_back("GUI"); } win.draw2D = (wIdx == webGuiWindowIndex.value()); win.draw3D = !(win.draw2D.value()); } } ProjectionOptions FileSupport::saveProjectionInformation( std::shared_ptr<WindowControl> winControl) { if (winControl->isSpoutSelected()) { return saveProjectionSpout(winControl); } else { return saveProjectionNoSpout(winControl); } } ProjectionOptions FileSupport::saveProjectionSpout( std::shared_ptr<WindowControl> winControl) { sgct::config::SpoutOutputProjection projection; switch(winControl->projectionSelectedIndex()) { case WindowControl::ProjectionIndeces::Fisheye: projection.mapping = sgct::config::SpoutOutputProjection::Mapping::Fisheye; break; case WindowControl::ProjectionIndeces::Equirectangular: default: projection.mapping = sgct::config::SpoutOutputProjection::Mapping::Equirectangular; break; } projection.quality = winControl->qualitySelectedValue(); projection.mappingSpoutName = "OpenSpace"; return projection; } ProjectionOptions FileSupport::saveProjectionNoSpout( std::shared_ptr<WindowControl> winControl) { switch(winControl->projectionSelectedIndex()) { case WindowControl::ProjectionIndeces::Fisheye: { sgct::config::FisheyeProjection projection; projection.quality = winControl->qualitySelectedValue(); projection.fov = 180.f; projection.tilt = 0.f; return projection; } break; case WindowControl::ProjectionIndeces::SphericalMirror: { sgct::config::SphericalMirrorProjection projection; projection.quality = winControl->qualitySelectedValue(); return projection; } break; case WindowControl::ProjectionIndeces::Cylindrical: { sgct::config::CylindricalProjection projection; projection.quality = winControl->qualitySelectedValue(); projection.heightOffset = winControl->heightOffset(); return projection; } break; case WindowControl::ProjectionIndeces::Equirectangular: { sgct::config::EquirectangularProjection projection; projection.quality = winControl->qualitySelectedValue(); return projection; } break; case WindowControl::ProjectionIndeces::Planar: default: { // The negative values for left & down are according to sgct's convention sgct::config::PlanarProjection projection; projection.fov.right = winControl->fovH() / 2.0; projection.fov.left = -projection.fov.right; projection.fov.up = winControl->fovV() / 2.0; projection.fov.down = -projection.fov.up; return projection; } break; } } std::string FileSupport::saveFilename() { return _saveTarget; } void FileSupport::save() { QString fileName = QFileDialog::getSaveFileName( this, "Save Window Configuration File", QString::fromStdString(_userConfigPath), "Window Configuration (*.json);;(*.json)", nullptr #ifdef __linux__ , QFileDialog::DontUseNativeDialog #endif ); if (fileName.length() != 0) { _saveTarget = fileName.toStdString(); saveConfigToSgctFormat(); _finishedCallback(true); } } void FileSupport::cancel() { _finishedCallback(false); } void FileSupport::apply() { std::string userCfgTempDir = _userConfigPath; if (userCfgTempDir.back() != '/') { userCfgTempDir += "/"; } userCfgTempDir += "temp"; if (!std::filesystem::is_directory(userCfgTempDir)) { std::filesystem::create_directories(absPath(userCfgTempDir)); } _saveTarget = userCfgTempDir + "/" + "apply-without-saving.json"; saveConfigToSgctFormat(); _finishedCallback(true); } void FileSupport::saveConfigToSgctFormat() { saveCluster(); saveWindows(); saveUser(); } <|endoftext|>
<commit_before>/* dtkPluginManager.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Tue Aug 4 12:20:59 2009 (+0200) * Version: $Id$ * Last-Updated: Sun Jul 18 14:57:08 2010 (+0200) * By: Julien Wintz * Update #: 126 */ /* Commentary: * */ /* Change log: * */ #include "dtkAbstractData.h" #include "dtkPluginManager.h" #include <dtkCore/dtkPlugin.h> #include <dtkCore/dtkLog.h> #define DTK_VERBOSE_LOAD false class dtkPluginManagerPrivate { public: QString path; QHash<QString, QPluginLoader *> loaders; }; dtkPluginManager *dtkPluginManager::instance(void) { if(!s_instance) { s_instance = new dtkPluginManager; qRegisterMetaType<dtkAbstractData>("dtkAbstractData"); } return s_instance; } void dtkPluginManager::initialize(void) { if(d->path.isNull()) this->readSettings(); QString paths = ""; if (!d->path.isEmpty()) paths = d->path + ":"; paths = paths + #ifdef Q_WS_WIN qApp->applicationDirPath() + "\\..\\plugins"; #else #ifdef Q_WS_MAC qApp->applicationDirPath() + "/../PlugIns"; #else qApp->applicationDirPath() + "/../plugins"; #endif #endif foreach(QString path, paths.split(":", QString::SkipEmptyParts)) { QDir dir(path); dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); foreach (QFileInfo entry, dir.entryInfoList()) loadPlugin(entry.absoluteFilePath()); } } void dtkPluginManager::uninitialize(void) { this->writeSettings(); // foreach(QString path, d->loaders.keys()) // unloadPlugin(path); } void dtkPluginManager::readSettings(void) { QSettings settings("inria", "dtk"); settings.beginGroup("plugins"); #ifdef Q_WS_WIN d->path = settings.value("path", "C:\\Program Files\\inria\\plugins").toString(); #else d->path = settings.value("path", "/usr/local/inria/plugins").toString(); #endif settings.endGroup(); if(d->path.isEmpty()) { dtkWarning() << "Your dtk config does not seem to be set correctly."; dtkWarning() << "Please set plugins.path."; } } void dtkPluginManager::writeSettings(void) { QSettings settings("inria", "dtk"); settings.beginGroup("plugins"); settings.setValue("path", d->path); settings.endGroup(); } void dtkPluginManager::printPlugins(void) { foreach(QString path, d->loaders.keys()) dtkOutput() << path; } dtkPlugin *dtkPluginManager::plugin(QString name) { foreach(QPluginLoader *loader, d->loaders) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if(plugin->name() == name) return plugin; } return NULL; } QList<dtkPlugin *> dtkPluginManager::plugins(void) { QList<dtkPlugin *> list; foreach(QPluginLoader *loader, d->loaders) list << qobject_cast<dtkPlugin *>(loader->instance()); return list; } void dtkPluginManager::setPath(const QString& path) { d->path = path; } dtkPluginManager::dtkPluginManager(void) : d(new dtkPluginManagerPrivate) { } dtkPluginManager::~dtkPluginManager(void) { delete d; d = NULL; } void dtkPluginManager::loadPlugin(const QString& path) { QPluginLoader *loader = new QPluginLoader(path); loader->setLoadHints (QLibrary::ExportExternalSymbolsHint); if(!loader->load()) { if(DTK_VERBOSE_LOAD) dtkDebug() << "Unable to load - " << loader->errorString(); delete loader; return; } dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if(!plugin) { if(DTK_VERBOSE_LOAD) dtkDebug() << "Unable to retrieve" << path; return; } if(!plugin->initialize()) { if(DTK_VERBOSE_LOAD) dtkOutput() << "Unable to initialize" << plugin->name() << "plugin"; return; } d->loaders.insert(path, loader); emit loaded(plugin->name()); } void dtkPluginManager::unloadPlugin(const QString& path) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(d->loaders.value(path)->instance()); if(!plugin) { if(DTK_VERBOSE_LOAD) dtkDebug() << "dtkPluginManager - Unable to retrieve" << plugin->name() << "plugin"; return; } if(!plugin->uninitialize()) { if(DTK_VERBOSE_LOAD) dtkOutput() << "Unable to uninitialize" << plugin->name() << "plugin"; return; } QPluginLoader *loader = d->loaders.value(path); if(!loader->unload()) { if(DTK_VERBOSE_LOAD) dtkDebug() << "dtkPluginManager - Unable to unload plugin:" << loader->errorString(); return; } delete loader; d->loaders.remove(path); // emit unloaded(plugin->name()); } dtkPluginManager *dtkPluginManager::s_instance = NULL; <commit_msg>- uncommented the call to the unload operation when calling uninitialize.<commit_after>/* dtkPluginManager.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Tue Aug 4 12:20:59 2009 (+0200) * Version: $Id$ * Last-Updated: Sun Jul 18 14:57:08 2010 (+0200) * By: Julien Wintz * Update #: 126 */ /* Commentary: * */ /* Change log: * */ #include "dtkAbstractData.h" #include "dtkPluginManager.h" #include <dtkCore/dtkPlugin.h> #include <dtkCore/dtkLog.h> #define DTK_VERBOSE_LOAD false class dtkPluginManagerPrivate { public: QString path; QHash<QString, QPluginLoader *> loaders; }; dtkPluginManager *dtkPluginManager::instance(void) { if(!s_instance) { s_instance = new dtkPluginManager; qRegisterMetaType<dtkAbstractData>("dtkAbstractData"); } return s_instance; } void dtkPluginManager::initialize(void) { if(d->path.isNull()) this->readSettings(); QString paths = ""; if (!d->path.isEmpty()) paths = d->path + ":"; paths = paths + #ifdef Q_WS_WIN qApp->applicationDirPath() + "\\..\\plugins"; #else #ifdef Q_WS_MAC qApp->applicationDirPath() + "/../PlugIns"; #else qApp->applicationDirPath() + "/../plugins"; #endif #endif foreach(QString path, paths.split(":", QString::SkipEmptyParts)) { QDir dir(path); dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); foreach (QFileInfo entry, dir.entryInfoList()) loadPlugin(entry.absoluteFilePath()); } } void dtkPluginManager::uninitialize(void) { this->writeSettings(); foreach(QString path, d->loaders.keys()) unloadPlugin(path); } void dtkPluginManager::readSettings(void) { QSettings settings("inria", "dtk"); settings.beginGroup("plugins"); #ifdef Q_WS_WIN d->path = settings.value("path", "C:\\Program Files\\inria\\plugins").toString(); #else d->path = settings.value("path", "/usr/local/inria/plugins").toString(); #endif settings.endGroup(); if(d->path.isEmpty()) { dtkWarning() << "Your dtk config does not seem to be set correctly."; dtkWarning() << "Please set plugins.path."; } } void dtkPluginManager::writeSettings(void) { QSettings settings("inria", "dtk"); settings.beginGroup("plugins"); settings.setValue("path", d->path); settings.endGroup(); } void dtkPluginManager::printPlugins(void) { foreach(QString path, d->loaders.keys()) dtkOutput() << path; } dtkPlugin *dtkPluginManager::plugin(QString name) { foreach(QPluginLoader *loader, d->loaders) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if(plugin->name() == name) return plugin; } return NULL; } QList<dtkPlugin *> dtkPluginManager::plugins(void) { QList<dtkPlugin *> list; foreach(QPluginLoader *loader, d->loaders) list << qobject_cast<dtkPlugin *>(loader->instance()); return list; } void dtkPluginManager::setPath(const QString& path) { d->path = path; } dtkPluginManager::dtkPluginManager(void) : d(new dtkPluginManagerPrivate) { } dtkPluginManager::~dtkPluginManager(void) { delete d; d = NULL; } void dtkPluginManager::loadPlugin(const QString& path) { QPluginLoader *loader = new QPluginLoader(path); loader->setLoadHints (QLibrary::ExportExternalSymbolsHint); if(!loader->load()) { if(DTK_VERBOSE_LOAD) dtkDebug() << "Unable to load - " << loader->errorString(); delete loader; return; } dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if(!plugin) { if(DTK_VERBOSE_LOAD) dtkDebug() << "Unable to retrieve" << path; return; } if(!plugin->initialize()) { if(DTK_VERBOSE_LOAD) dtkOutput() << "Unable to initialize" << plugin->name() << "plugin"; return; } d->loaders.insert(path, loader); emit loaded(plugin->name()); } void dtkPluginManager::unloadPlugin(const QString& path) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(d->loaders.value(path)->instance()); if(!plugin) { if(DTK_VERBOSE_LOAD) dtkDebug() << "dtkPluginManager - Unable to retrieve" << plugin->name() << "plugin"; return; } if(!plugin->uninitialize()) { if(DTK_VERBOSE_LOAD) dtkOutput() << "Unable to uninitialize" << plugin->name() << "plugin"; return; } QPluginLoader *loader = d->loaders.value(path); if(!loader->unload()) { if(DTK_VERBOSE_LOAD) dtkDebug() << "dtkPluginManager - Unable to unload plugin:" << loader->errorString(); return; } delete loader; d->loaders.remove(path); // emit unloaded(plugin->name()); } dtkPluginManager *dtkPluginManager::s_instance = NULL; <|endoftext|>
<commit_before>/* * Copyright (c) 2019, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "application_manager/display_capabilities_builder.h" #include "application_manager/message_helper.h" #include "application_manager/smart_object_keys.h" namespace application_manager { CREATE_LOGGERPTR_GLOBAL(logger_, "DisplayCapabilitiesBuilder") const WindowID kMainWindowID = 0; DisplayCapabilitiesBuilder::DisplayCapabilitiesBuilder(Application& application) : owner_(application) { LOG4CXX_AUTO_TRACE(logger_); } void DisplayCapabilitiesBuilder::InitBuilder( DisplayCapabilitiesBuilder::ResumeCallback resume_callback, const smart_objects::SmartObject& windows_info) { LOG4CXX_AUTO_TRACE(logger_); sync_primitives::AutoLock lock(display_capabilities_lock_); resume_callback_ = resume_callback; window_ids_to_resume_.insert(kMainWindowID); for (size_t i = 0; i < windows_info.length(); ++i) { auto window_id = windows_info[i][strings::window_id].asInt(); LOG4CXX_DEBUG(logger_, "Inserting " << window_id << " to waiting container"); window_ids_to_resume_.insert(window_id); } } void DisplayCapabilitiesBuilder::UpdateDisplayCapabilities( const smart_objects::SmartObject& incoming_display_capabilities) { LOG4CXX_AUTO_TRACE(logger_); using namespace smart_objects; sync_primitives::AutoLock lock(display_capabilities_lock_); if (!display_capabilities_) { display_capabilities_ = std::make_shared<SmartObject>(SmartType_Array); } // As per v6.0, only single display is supported auto cur_window_caps = (*display_capabilities_)[0][strings::window_capabilities]; const auto& inc_window_caps = incoming_display_capabilities[0][strings::window_capabilities]; for (size_t i = 0; i < inc_window_caps.length(); ++i) { const WindowID window_id = inc_window_caps[i].keyExists(strings::window_id) ? inc_window_caps[i][strings::window_id].asInt() : kMainWindowID; if (window_ids_to_resume_.end() != window_ids_to_resume_.find(window_id)) { cur_window_caps[cur_window_caps.length()] = inc_window_caps[i]; LOG4CXX_DEBUG(logger_, "Stop waiting for: " << window_id); window_ids_to_resume_.erase(window_id); } } *display_capabilities_ = incoming_display_capabilities; (*display_capabilities_)[0][strings::window_capabilities] = cur_window_caps; if (window_ids_to_resume_.empty()) { LOG4CXX_TRACE(logger_, "Invoking resume callback"); resume_callback_(owner_, *display_capabilities_); display_capabilities_.reset(); } } // namespace application_manager const smart_objects::SmartObjectSPtr DisplayCapabilitiesBuilder::display_capabilities() const { LOG4CXX_AUTO_TRACE(logger_); return display_capabilities_; } void DisplayCapabilitiesBuilder::ResetDisplayCapabilities() { LOG4CXX_AUTO_TRACE(logger_); sync_primitives::AutoLock lock(display_capabilities_lock_); display_capabilities_.reset(); } void DisplayCapabilitiesBuilder::StopWaitingForWindow( const WindowID window_id) { LOG4CXX_AUTO_TRACE(logger_); sync_primitives::AutoLock lock(display_capabilities_lock_); LOG4CXX_DEBUG(logger_, "Window id " << window_id << " will be erased due to failure"); window_ids_to_resume_.erase(window_id); if (window_ids_to_resume_.empty()) { LOG4CXX_TRACE(logger_, window_id << " was the last window pending resumption. " "Invoking resume callback"); resume_callback_(owner_, *display_capabilities_); display_capabilities_.reset(); } } } // namespace application_manager <commit_msg>fixup! Send one OnSystemCapabilitiesUpdated on resumption<commit_after>/* * Copyright (c) 2019, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "application_manager/display_capabilities_builder.h" #include "application_manager/message_helper.h" #include "application_manager/smart_object_keys.h" namespace application_manager { CREATE_LOGGERPTR_GLOBAL(logger_, "DisplayCapabilitiesBuilder") const WindowID kDefaultWindowID = 0; DisplayCapabilitiesBuilder::DisplayCapabilitiesBuilder(Application& application) : owner_(application) { LOG4CXX_AUTO_TRACE(logger_); } void DisplayCapabilitiesBuilder::InitBuilder( DisplayCapabilitiesBuilder::ResumeCallback resume_callback, const smart_objects::SmartObject& windows_info) { LOG4CXX_AUTO_TRACE(logger_); sync_primitives::AutoLock lock(display_capabilities_lock_); resume_callback_ = resume_callback; window_ids_to_resume_.insert(kDefaultWindowID); for (size_t i = 0; i < windows_info.length(); ++i) { auto window_id = windows_info[i][strings::window_id].asInt(); LOG4CXX_DEBUG(logger_, "Inserting " << window_id << " to waiting container"); window_ids_to_resume_.insert(window_id); } } void DisplayCapabilitiesBuilder::UpdateDisplayCapabilities( const smart_objects::SmartObject& incoming_display_capabilities) { LOG4CXX_AUTO_TRACE(logger_); using namespace smart_objects; sync_primitives::AutoLock lock(display_capabilities_lock_); if (!display_capabilities_) { display_capabilities_ = std::make_shared<SmartObject>(SmartType_Array); } // As per v6.0, only single display is supported auto cur_window_caps = (*display_capabilities_)[0][strings::window_capabilities]; const auto& inc_window_caps = incoming_display_capabilities[0][strings::window_capabilities]; for (size_t i = 0; i < inc_window_caps.length(); ++i) { const WindowID window_id = inc_window_caps[i].keyExists(strings::window_id) ? inc_window_caps[i][strings::window_id].asInt() : kDefaultWindowID; if (window_ids_to_resume_.end() != window_ids_to_resume_.find(window_id)) { cur_window_caps[cur_window_caps.length()] = inc_window_caps[i]; LOG4CXX_DEBUG(logger_, "Stop waiting for: " << window_id); window_ids_to_resume_.erase(window_id); } } *display_capabilities_ = incoming_display_capabilities; (*display_capabilities_)[0][strings::window_capabilities] = cur_window_caps; if (window_ids_to_resume_.empty()) { LOG4CXX_TRACE(logger_, "Invoking resume callback"); resume_callback_(owner_, *display_capabilities_); display_capabilities_.reset(); } } // namespace application_manager const smart_objects::SmartObjectSPtr DisplayCapabilitiesBuilder::display_capabilities() const { LOG4CXX_AUTO_TRACE(logger_); return display_capabilities_; } void DisplayCapabilitiesBuilder::ResetDisplayCapabilities() { LOG4CXX_AUTO_TRACE(logger_); sync_primitives::AutoLock lock(display_capabilities_lock_); display_capabilities_.reset(); } void DisplayCapabilitiesBuilder::StopWaitingForWindow( const WindowID window_id) { LOG4CXX_AUTO_TRACE(logger_); sync_primitives::AutoLock lock(display_capabilities_lock_); LOG4CXX_DEBUG(logger_, "Window id " << window_id << " will be erased due to failure"); window_ids_to_resume_.erase(window_id); if (window_ids_to_resume_.empty()) { LOG4CXX_TRACE(logger_, window_id << " was the last window pending resumption. " "Invoking resume callback"); resume_callback_(owner_, *display_capabilities_); display_capabilities_.reset(); } } } // namespace application_manager <|endoftext|>
<commit_before>// main.cpp - Copyright 2013-2016 Will Cassella, All Rights Reserved #include <Core/Application.h> #include <Core/IO/Console.h> #include "../include/AssetConverter/AssetConversion.h" int main(int32 argCount, char** args) { using namespace Willow; Application::Initialize(); // If files were passed in via the command line if (argCount > 1) { AssetConversion::Convert(args[1], Array<String>()); return 0; } Console::WriteLine("---Asset Converter---"); Console::NewLine(); Console::WriteLine("Enter the path to a file to convert:"); while (true) { String path = Console::Prompt(); Console::NewLine(); if (path.IsEmpty()) { break; } // @TODO: Parse options (setting compression level, renaming output) AssetConversion::Convert(path, Array<String>()); } Application::Terminate(); }<commit_msg>Fixed some things that were bothering me with AssetConverter<commit_after>// main.cpp - Copyright 2013-2016 Will Cassella, All Rights Reserved #include <Core/Application.h> #include <Core/IO/Console.h> #include "../include/AssetConverter/AssetConversion.h" int main(int argCount, char** args) { using namespace Willow; Application::Initialize(); // If files were passed in via the command line if (argCount > 1) { AssetConversion::Convert(args[1], Array<String>()); return 0; } Console::WriteLine("---Asset Converter---"); Console::NewLine(); Console::WriteLine("Enter the path to a file to convert:"); while (true) { String path = Console::Prompt(); Console::NewLine(); if (path.IsEmpty()) { break; } // @TODO: Parse options (setting compression level, renaming output) AssetConversion::Convert(path, Array<String>()); } Application::Terminate(); }<|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetReaderTest #include <cstddef> #include <iostream> #include <vector> #include <boost/test/unit_test.hpp> #include <TError.h> /// gErrorIgnoreLevel #include <TObjString.h> #include "../JPetReader/JPetReader.h" #include "../JPetWriter/JPetWriter.h" // method list //JPetReader(void); //maybe remove this one //explicit JPetReader(const char* p_filename); //virtual Event& getCurrentEvent(); //virtual bool nextEvent(); //virtual bool firstEvent(); //virtual bool lastEvent(); //virtual bool nthEvent(int n); //virtual long long getCurrentEventNumber(); //virtual long long getNbOfAllEvents(); //virtual bool openFileAndLoadData(const char* filename, const char* treename = "tree"); //virtual void closeFile(); // //JPetTreeHeader* getHeaderClone() const; //virtual TObject* getObjectFromFile(const char* name); //virtual bool isOpen() const; BOOST_AUTO_TEST_SUITE (JPetReaderTestSuite) BOOST_AUTO_TEST_CASE (default_constructor) { JPetReader reader; BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("Empty event")); BOOST_REQUIRE(!reader.isOpen()); BOOST_REQUIRE(!reader.nextEvent()); BOOST_REQUIRE(!reader.firstEvent()); BOOST_REQUIRE(!reader.lastEvent()); BOOST_REQUIRE(!reader.nthEvent(0)); BOOST_REQUIRE(!reader.nthEvent(1)); BOOST_REQUIRE(!reader.nthEvent(-1)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0); BOOST_REQUIRE(!reader.getHeaderClone()); BOOST_REQUIRE(!reader.getObjectFromFile("testObj")); } BOOST_AUTO_TEST_CASE (bad_file) { gErrorIgnoreLevel = 6000; /// we turn off the ROOT error messages JPetReader reader; /// not a ROOT file BOOST_REQUIRE(!reader.openFileAndLoadData("bad_file.txt", "tree")); BOOST_REQUIRE(!reader.isOpen()); BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("Empty event")); BOOST_REQUIRE(!reader.nextEvent()); BOOST_REQUIRE(!reader.firstEvent()); BOOST_REQUIRE(!reader.lastEvent()); BOOST_REQUIRE(!reader.nthEvent(0)); BOOST_REQUIRE(!reader.nthEvent(1)); BOOST_REQUIRE(!reader.nthEvent(-1)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0); BOOST_REQUIRE(!reader.getHeaderClone()); BOOST_REQUIRE(!reader.getObjectFromFile("testObj")); } BOOST_AUTO_TEST_CASE (good_file_with_constructor) { JPetReader reader("unitTestData/JPetReaderTest/timewindows.root"); BOOST_REQUIRE(reader.isOpen()); BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("JPetTimeWindow")); BOOST_REQUIRE(reader.nextEvent()); BOOST_REQUIRE(reader.firstEvent()); BOOST_REQUIRE(reader.lastEvent()); BOOST_REQUIRE(reader.nthEvent(0)); BOOST_REQUIRE(reader.nthEvent(5)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), 5); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 10); BOOST_REQUIRE(reader.getHeaderClone()); } BOOST_AUTO_TEST_CASE (good_file_getObject) { JPetReader reader("unitTestData/JPetReaderTest/timewindows.root"); BOOST_REQUIRE(!reader.getObjectFromFile("nonExistentObj")); BOOST_REQUIRE(reader.getObjectFromFile("tree")); } BOOST_AUTO_TEST_CASE (good_file_openFileAndLoadData) { JPetReader reader; BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetReaderTest/timewindows.root","tree")); BOOST_REQUIRE(reader.isOpen()); BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("JPetTimeWindow")); BOOST_REQUIRE(reader.firstEvent()); BOOST_REQUIRE(reader.nextEvent()); BOOST_REQUIRE(reader.lastEvent()); BOOST_REQUIRE(reader.nthEvent(0)); BOOST_REQUIRE(reader.nthEvent(5)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), 5); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 10); BOOST_REQUIRE(reader.getHeaderClone()); } BOOST_AUTO_TEST_CASE (good_file_closeFile) { JPetReader reader; BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetReaderTest/timewindows.root","tree")); BOOST_REQUIRE(reader.isOpen()); reader.closeFile(); BOOST_REQUIRE(!reader.isOpen()); BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("Empty event")); BOOST_REQUIRE(!reader.nextEvent()); BOOST_REQUIRE(!reader.firstEvent()); BOOST_REQUIRE(!reader.lastEvent()); BOOST_REQUIRE(!reader.nthEvent(0)); BOOST_REQUIRE(!reader.nthEvent(1)); BOOST_REQUIRE(!reader.nthEvent(-1)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0); BOOST_REQUIRE(!reader.getHeaderClone()); BOOST_REQUIRE(!reader.getObjectFromFile("testObj")); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Change name of test file used for develop version<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetReaderTest #include <cstddef> #include <iostream> #include <vector> #include <boost/test/unit_test.hpp> #include <TError.h> /// gErrorIgnoreLevel #include <TObjString.h> #include "../JPetReader/JPetReader.h" #include "../JPetWriter/JPetWriter.h" // method list //JPetReader(void); //maybe remove this one //explicit JPetReader(const char* p_filename); //virtual Event& getCurrentEvent(); //virtual bool nextEvent(); //virtual bool firstEvent(); //virtual bool lastEvent(); //virtual bool nthEvent(int n); //virtual long long getCurrentEventNumber(); //virtual long long getNbOfAllEvents(); //virtual bool openFileAndLoadData(const char* filename, const char* treename = "tree"); //virtual void closeFile(); // //JPetTreeHeader* getHeaderClone() const; //virtual TObject* getObjectFromFile(const char* name); //virtual bool isOpen() const; BOOST_AUTO_TEST_SUITE (JPetReaderTestSuite) BOOST_AUTO_TEST_CASE (default_constructor) { JPetReader reader; BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("Empty event")); BOOST_REQUIRE(!reader.isOpen()); BOOST_REQUIRE(!reader.nextEvent()); BOOST_REQUIRE(!reader.firstEvent()); BOOST_REQUIRE(!reader.lastEvent()); BOOST_REQUIRE(!reader.nthEvent(0)); BOOST_REQUIRE(!reader.nthEvent(1)); BOOST_REQUIRE(!reader.nthEvent(-1)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0); BOOST_REQUIRE(!reader.getHeaderClone()); BOOST_REQUIRE(!reader.getObjectFromFile("testObj")); } BOOST_AUTO_TEST_CASE (bad_file) { gErrorIgnoreLevel = 6000; /// we turn off the ROOT error messages JPetReader reader; /// not a ROOT file BOOST_REQUIRE(!reader.openFileAndLoadData("bad_file.txt", "tree")); BOOST_REQUIRE(!reader.isOpen()); BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("Empty event")); BOOST_REQUIRE(!reader.nextEvent()); BOOST_REQUIRE(!reader.firstEvent()); BOOST_REQUIRE(!reader.lastEvent()); BOOST_REQUIRE(!reader.nthEvent(0)); BOOST_REQUIRE(!reader.nthEvent(1)); BOOST_REQUIRE(!reader.nthEvent(-1)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0); BOOST_REQUIRE(!reader.getHeaderClone()); BOOST_REQUIRE(!reader.getObjectFromFile("testObj")); } BOOST_AUTO_TEST_CASE (good_file_with_constructor) { JPetReader reader("unitTestData/JPetReaderTest/timewindows_v2.root"); BOOST_REQUIRE(reader.isOpen()); BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("JPetTimeWindow")); BOOST_REQUIRE(reader.nextEvent()); BOOST_REQUIRE(reader.firstEvent()); BOOST_REQUIRE(reader.lastEvent()); BOOST_REQUIRE(reader.nthEvent(0)); BOOST_REQUIRE(reader.nthEvent(5)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), 5); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 10); BOOST_REQUIRE(reader.getHeaderClone()); } BOOST_AUTO_TEST_CASE (good_file_getObject) { JPetReader reader("unitTestData/JPetReaderTest/timewindows_v2.root"); BOOST_REQUIRE(!reader.getObjectFromFile("nonExistentObj")); BOOST_REQUIRE(reader.getObjectFromFile("tree")); } BOOST_AUTO_TEST_CASE (good_file_openFileAndLoadData) { JPetReader reader; BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetReaderTest/timewindows_v2.root","tree")); BOOST_REQUIRE(reader.isOpen()); BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("JPetTimeWindow")); BOOST_REQUIRE(reader.firstEvent()); BOOST_REQUIRE(reader.nextEvent()); BOOST_REQUIRE(reader.lastEvent()); BOOST_REQUIRE(reader.nthEvent(0)); BOOST_REQUIRE(reader.nthEvent(5)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), 5); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 10); BOOST_REQUIRE(reader.getHeaderClone()); } BOOST_AUTO_TEST_CASE (good_file_closeFile) { JPetReader reader; BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetReaderTest/timewindows_v2.root","tree")); BOOST_REQUIRE(reader.isOpen()); reader.closeFile(); BOOST_REQUIRE(!reader.isOpen()); BOOST_REQUIRE(std::string(reader.getCurrentEvent().GetName())==std::string("Empty event")); BOOST_REQUIRE(!reader.nextEvent()); BOOST_REQUIRE(!reader.firstEvent()); BOOST_REQUIRE(!reader.lastEvent()); BOOST_REQUIRE(!reader.nthEvent(0)); BOOST_REQUIRE(!reader.nthEvent(1)); BOOST_REQUIRE(!reader.nthEvent(-1)); BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0); BOOST_REQUIRE(!reader.getHeaderClone()); BOOST_REQUIRE(!reader.getObjectFromFile("testObj")); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetWriterTest #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> // for filesystem::remove #include <TNamed.h> #include "../JPetSigCh/JPetSigCh.h" #include "../JPetTimeWindow/JPetTimeWindow.h" #include "../JPetBaseSignal/JPetBaseSignal.h" #include "../JPetRawSignal/JPetRawSignal.h" #include "../JPetRecoSignal/JPetRecoSignal.h" #include "../JPetPhysSignal/JPetPhysSignal.h" #include "../JPetHit/JPetHit.h" #include "../JPetLOR/JPetLOR.h" #include "../JPetWriter/JPetWriter.h" #include "../JPetReader/JPetReader.h" // JPetWriter(const char *p_fileName); // virtual ~JPetWriter(void); // // template <class T> // bool Write(const T& obj); // //bool OpenFile(const char* filename); // void WriteHeader(TObject* header); // inline bool IsOpenFile() const {return fFile.IsOpen();} // void closeFile(); // // int WriteObject(const TObject* obj, const char* name){ return fFile.WriteObject(obj, name); } // BOOST_AUTO_TEST_SUITE(FirstSuite) BOOST_AUTO_TEST_CASE( my_test1 ) { JPetWriter writer("test.root"); BOOST_REQUIRE(writer.isOpen()); writer.closeFile(); BOOST_REQUIRE(!writer.isOpen()); } BOOST_AUTO_TEST_CASE( my_test2 ) { std::string fileName = "test2.root"; JPetWriter writer(fileName.c_str()); TNamed obj("TNamed", "Title of this testObj"); writer.write(obj); writer.closeFile(); JPetReader reader(fileName.c_str()); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 1); TNamed& objOut = (TNamed&)reader.getCurrentEvent(); BOOST_REQUIRE(std::string(objOut.GetName())=="TNamed"); BOOST_REQUIRE(std::string(objOut.GetTitle())=="Title of this testObj"); } /// a tree must have a name if not SetAutoSave makes it crash when when call Branch BOOST_AUTO_TEST_CASE( my_helperTest_for_test3 ) { std::string fileName = "test3_bis.root"; TFile file(fileName.c_str(), "RECREATE"); TTree tree("tree", "tree"); tree.SetAutoSave(1000); TNamed* filler = 0; tree.Branch("TNamed", "TNamed", &filler); const int kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; TNamed obj("TNamed", Form("Title of this testObj%d",i)); filler = &obj; tree.Fill(); tree.FlushBaskets(); } std::cout <<std::endl; file.Close(); } BOOST_AUTO_TEST_CASE( my_test3 ) { std::string fileName = "test3.root"; JPetWriter writer(fileName.c_str()); const int kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { TNamed obj("TNamed", Form("Title of this testObj%d",i)); if (i%1000==0) std::cout<<"*"<<std::flush; writer.write(obj); } std::cout <<std::endl; writer.closeFile(); JPetReader reader(fileName.c_str()); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), kHugeNumberOfObjects); for (int i = 0; i < kHugeNumberOfObjects; i++) { reader.nthEvent(i); TNamed& objOut = (TNamed&)reader.getCurrentEvent(); BOOST_REQUIRE(std::string(objOut.GetName())=="TNamed"); BOOST_REQUIRE(std::string(objOut.GetTitle())==Form("Title of this testObj%d",i)); } } BOOST_AUTO_TEST_CASE( saving_different_objects1 ) { //JPetSigCh testJPetSigCh; auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetSigCh testJPetSigCh; writer.write(testJPetSigCh); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects2 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetTimeWindow testJPetTimeWindow; writer.write(testJPetTimeWindow); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects3 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetBaseSignal testJPetBaseSignal; writer.write(testJPetBaseSignal); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects4 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetRawSignal testJPetRawSignal; writer.write(testJPetRawSignal); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects5 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetRecoSignal testJPetRecoSignal; writer.write(testJPetRecoSignal); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects6 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetPhysSignal testJPetPhysSignal; writer.write(testJPetPhysSignal); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects7 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetHit testJPetHit; writer.write(testJPetHit); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects8 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetLOR testJPetLOR; writer.write(testJPetLOR); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Added cppcheck comment to JPetWriterTest.cpp to suppress null pointer error<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetWriterTest #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> // for filesystem::remove #include <TNamed.h> #include "../JPetSigCh/JPetSigCh.h" #include "../JPetTimeWindow/JPetTimeWindow.h" #include "../JPetBaseSignal/JPetBaseSignal.h" #include "../JPetRawSignal/JPetRawSignal.h" #include "../JPetRecoSignal/JPetRecoSignal.h" #include "../JPetPhysSignal/JPetPhysSignal.h" #include "../JPetHit/JPetHit.h" #include "../JPetLOR/JPetLOR.h" #include "../JPetWriter/JPetWriter.h" #include "../JPetReader/JPetReader.h" // JPetWriter(const char *p_fileName); // virtual ~JPetWriter(void); // // template <class T> // bool Write(const T& obj); // //bool OpenFile(const char* filename); // void WriteHeader(TObject* header); // inline bool IsOpenFile() const {return fFile.IsOpen();} // void closeFile(); // // int WriteObject(const TObject* obj, const char* name){ return fFile.WriteObject(obj, name); } // BOOST_AUTO_TEST_SUITE(FirstSuite) BOOST_AUTO_TEST_CASE( my_test1 ) { JPetWriter writer("test.root"); BOOST_REQUIRE(writer.isOpen()); writer.closeFile(); BOOST_REQUIRE(!writer.isOpen()); } BOOST_AUTO_TEST_CASE( my_test2 ) { std::string fileName = "test2.root"; JPetWriter writer(fileName.c_str()); TNamed obj("TNamed", "Title of this testObj"); writer.write(obj); writer.closeFile(); JPetReader reader(fileName.c_str()); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 1); TNamed& objOut = (TNamed&)reader.getCurrentEvent(); BOOST_REQUIRE(std::string(objOut.GetName())=="TNamed"); BOOST_REQUIRE(std::string(objOut.GetTitle())=="Title of this testObj"); } /// a tree must have a name if not SetAutoSave makes it crash when when call Branch BOOST_AUTO_TEST_CASE( my_helperTest_for_test3 ) { std::string fileName = "test3_bis.root"; TFile file(fileName.c_str(), "RECREATE"); TTree tree("tree", "tree"); tree.SetAutoSave(1000); TNamed* filler = 0; // cppcheck-suppress nullPointer tree.Branch("TNamed", "TNamed", &filler); const int kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; TNamed obj("TNamed", Form("Title of this testObj%d",i)); filler = &obj; tree.Fill(); tree.FlushBaskets(); } std::cout <<std::endl; file.Close(); } BOOST_AUTO_TEST_CASE( my_test3 ) { std::string fileName = "test3.root"; JPetWriter writer(fileName.c_str()); const int kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { TNamed obj("TNamed", Form("Title of this testObj%d",i)); if (i%1000==0) std::cout<<"*"<<std::flush; writer.write(obj); } std::cout <<std::endl; writer.closeFile(); JPetReader reader(fileName.c_str()); BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), kHugeNumberOfObjects); for (int i = 0; i < kHugeNumberOfObjects; i++) { reader.nthEvent(i); TNamed& objOut = (TNamed&)reader.getCurrentEvent(); BOOST_REQUIRE(std::string(objOut.GetName())=="TNamed"); BOOST_REQUIRE(std::string(objOut.GetTitle())==Form("Title of this testObj%d",i)); } } BOOST_AUTO_TEST_CASE( saving_different_objects1 ) { //JPetSigCh testJPetSigCh; auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetSigCh testJPetSigCh; writer.write(testJPetSigCh); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects2 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetTimeWindow testJPetTimeWindow; writer.write(testJPetTimeWindow); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects3 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetBaseSignal testJPetBaseSignal; writer.write(testJPetBaseSignal); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects4 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetRawSignal testJPetRawSignal; writer.write(testJPetRawSignal); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects5 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetRecoSignal testJPetRecoSignal; writer.write(testJPetRecoSignal); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects6 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetPhysSignal testJPetPhysSignal; writer.write(testJPetPhysSignal); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects7 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetHit testJPetHit; writer.write(testJPetHit); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_CASE( saving_different_objects8 ) { auto fileTest = "saving_different_objectsTest.root"; JPetWriter writer(fileTest); const auto kHugeNumberOfObjects = 10000; for (int i = 0; i < kHugeNumberOfObjects; i++) { if (i%1000==0) std::cout<<"*"<<std::flush; JPetLOR testJPetLOR; writer.write(testJPetLOR); } if(boost::filesystem::exists(fileTest)) boost::filesystem::remove(fileTest); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file ir_function_inlining.cpp * * Replaces calls to functions with the body of the function. */ #include <inttypes.h> #include "ir.h" #include "ir_visitor.h" #include "ir_function_inlining.h" #include "ir_expression_flattening.h" #include "glsl_types.h" #include "program/hash_table.h" class ir_function_inlining_visitor : public ir_hierarchical_visitor { public: ir_function_inlining_visitor() { progress = false; } virtual ~ir_function_inlining_visitor() { /* empty */ } virtual ir_visitor_status visit_enter(ir_expression *); virtual ir_visitor_status visit_enter(ir_call *); virtual ir_visitor_status visit_enter(ir_assignment *); virtual ir_visitor_status visit_enter(ir_return *); virtual ir_visitor_status visit_enter(ir_texture *); virtual ir_visitor_status visit_enter(ir_swizzle *); bool progress; }; bool automatic_inlining_predicate(ir_instruction *ir) { ir_call *call = ir->as_call(); if (call && can_inline(call)) return true; return false; } bool do_function_inlining(exec_list *instructions) { ir_function_inlining_visitor v; do_expression_flattening(instructions, automatic_inlining_predicate); v.run(instructions); return v.progress; } static void replace_return_with_assignment(ir_instruction *ir, void *data) { void *ctx = talloc_parent(ir); ir_variable *retval = (ir_variable *)data; ir_return *ret = ir->as_return(); if (ret) { if (ret->value) { ir_rvalue *lhs = new(ctx) ir_dereference_variable(retval); ret->replace_with(new(ctx) ir_assignment(lhs, ret->value, NULL)); } else { /* un-valued return has to be the last return, or we shouldn't * have reached here. (see can_inline()). */ assert(!ret->next->is_tail_sentinel()); ret->remove(); } } } ir_rvalue * ir_call::generate_inline(ir_instruction *next_ir) { void *ctx = talloc_parent(this); ir_variable **parameters; int num_parameters; int i; ir_variable *retval = NULL; struct hash_table *ht; ht = hash_table_ctor(0, hash_table_pointer_hash, hash_table_pointer_compare); num_parameters = 0; foreach_iter(exec_list_iterator, iter_sig, this->callee->parameters) num_parameters++; parameters = new ir_variable *[num_parameters]; /* Generate storage for the return value. */ if (this->callee->return_type) { retval = new(ctx) ir_variable(this->callee->return_type, "__retval", ir_var_auto); next_ir->insert_before(retval); } /* Generate the declarations for the parameters to our inlined code, * and set up the mapping of real function body variables to ours. */ i = 0; exec_list_iterator sig_param_iter = this->callee->parameters.iterator(); exec_list_iterator param_iter = this->actual_parameters.iterator(); for (i = 0; i < num_parameters; i++) { ir_variable *sig_param = (ir_variable *) sig_param_iter.get(); ir_rvalue *param = (ir_rvalue *) param_iter.get(); /* Generate a new variable for the parameter. */ if (sig_param->type->base_type == GLSL_TYPE_SAMPLER) { /* For samplers, we want the inlined sampler references * referencing the passed in sampler variable, since that * will have the location information, which an assignment of * a sampler wouldn't. */ parameters[i] = NULL; hash_table_insert(ht, param->variable_referenced(), sig_param); } else { parameters[i] = sig_param->clone(ctx, ht); parameters[i]->mode = ir_var_auto; next_ir->insert_before(parameters[i]); } /* Move the actual param into our param variable if it's an 'in' type. */ if (parameters[i] && (sig_param->mode == ir_var_in || sig_param->mode == ir_var_inout)) { ir_assignment *assign; assign = new(ctx) ir_assignment(new(ctx) ir_dereference_variable(parameters[i]), param, NULL); next_ir->insert_before(assign); } sig_param_iter.next(); param_iter.next(); } /* Generate the inlined body of the function. */ foreach_iter(exec_list_iterator, iter, callee->body) { ir_instruction *ir = (ir_instruction *)iter.get(); ir_instruction *new_ir = ir->clone(ctx, ht); next_ir->insert_before(new_ir); visit_tree(new_ir, replace_return_with_assignment, retval); } /* Copy back the value of any 'out' parameters from the function body * variables to our own. */ i = 0; param_iter = this->actual_parameters.iterator(); sig_param_iter = this->callee->parameters.iterator(); for (i = 0; i < num_parameters; i++) { ir_instruction *const param = (ir_instruction *) param_iter.get(); const ir_variable *const sig_param = (ir_variable *) sig_param_iter.get(); /* Move our param variable into the actual param if it's an 'out' type. */ if (parameters[i] && (sig_param->mode == ir_var_out || sig_param->mode == ir_var_inout)) { ir_assignment *assign; assign = new(ctx) ir_assignment(param->clone(ctx, NULL)->as_rvalue(), new(ctx) ir_dereference_variable(parameters[i]), NULL); next_ir->insert_before(assign); } param_iter.next(); sig_param_iter.next(); } delete [] parameters; hash_table_dtor(ht); if (retval) return new(ctx) ir_dereference_variable(retval); else return NULL; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_expression *ir) { (void) ir; return visit_continue_with_parent; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_return *ir) { (void) ir; return visit_continue_with_parent; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_texture *ir) { (void) ir; return visit_continue_with_parent; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_swizzle *ir) { (void) ir; return visit_continue_with_parent; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_call *ir) { if (can_inline(ir)) { /* If the call was part of some tree, then it should have been * flattened out or we shouldn't have seen it because of a * visit_continue_with_parent in this visitor. */ assert(ir == base_ir); (void) ir->generate_inline(ir); ir->remove(); this->progress = true; } return visit_continue; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_assignment *ir) { ir_call *call = ir->rhs->as_call(); if (!call || !can_inline(call)) return visit_continue; /* generates the parameter setup, function body, and returns the return * value of the function */ ir_rvalue *rhs = call->generate_inline(ir); assert(rhs); ir->rhs = rhs; this->progress = true; return visit_continue; } <commit_msg>glsl2: Fix inlining with sampler array or struct dereferences as arguments.<commit_after>/* * Copyright © 2010 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /** * \file ir_function_inlining.cpp * * Replaces calls to functions with the body of the function. */ #include <inttypes.h> #include "ir.h" #include "ir_visitor.h" #include "ir_function_inlining.h" #include "ir_expression_flattening.h" #include "glsl_types.h" #include "program/hash_table.h" static void do_sampler_replacement(exec_list *instructions, ir_variable *sampler, ir_dereference *deref); class ir_function_inlining_visitor : public ir_hierarchical_visitor { public: ir_function_inlining_visitor() { progress = false; } virtual ~ir_function_inlining_visitor() { /* empty */ } virtual ir_visitor_status visit_enter(ir_expression *); virtual ir_visitor_status visit_enter(ir_call *); virtual ir_visitor_status visit_enter(ir_assignment *); virtual ir_visitor_status visit_enter(ir_return *); virtual ir_visitor_status visit_enter(ir_texture *); virtual ir_visitor_status visit_enter(ir_swizzle *); bool progress; }; bool automatic_inlining_predicate(ir_instruction *ir) { ir_call *call = ir->as_call(); if (call && can_inline(call)) return true; return false; } bool do_function_inlining(exec_list *instructions) { ir_function_inlining_visitor v; do_expression_flattening(instructions, automatic_inlining_predicate); v.run(instructions); return v.progress; } static void replace_return_with_assignment(ir_instruction *ir, void *data) { void *ctx = talloc_parent(ir); ir_variable *retval = (ir_variable *)data; ir_return *ret = ir->as_return(); if (ret) { if (ret->value) { ir_rvalue *lhs = new(ctx) ir_dereference_variable(retval); ret->replace_with(new(ctx) ir_assignment(lhs, ret->value, NULL)); } else { /* un-valued return has to be the last return, or we shouldn't * have reached here. (see can_inline()). */ assert(ret->next->is_tail_sentinel()); ret->remove(); } } } ir_rvalue * ir_call::generate_inline(ir_instruction *next_ir) { void *ctx = talloc_parent(this); ir_variable **parameters; int num_parameters; int i; ir_variable *retval = NULL; struct hash_table *ht; ht = hash_table_ctor(0, hash_table_pointer_hash, hash_table_pointer_compare); num_parameters = 0; foreach_iter(exec_list_iterator, iter_sig, this->callee->parameters) num_parameters++; parameters = new ir_variable *[num_parameters]; /* Generate storage for the return value. */ if (this->callee->return_type) { retval = new(ctx) ir_variable(this->callee->return_type, "__retval", ir_var_auto); next_ir->insert_before(retval); } /* Generate the declarations for the parameters to our inlined code, * and set up the mapping of real function body variables to ours. */ i = 0; exec_list_iterator sig_param_iter = this->callee->parameters.iterator(); exec_list_iterator param_iter = this->actual_parameters.iterator(); for (i = 0; i < num_parameters; i++) { ir_variable *sig_param = (ir_variable *) sig_param_iter.get(); ir_rvalue *param = (ir_rvalue *) param_iter.get(); /* Generate a new variable for the parameter. */ if (sig_param->type->base_type == GLSL_TYPE_SAMPLER) { /* For samplers, we want the inlined sampler references * referencing the passed in sampler variable, since that * will have the location information, which an assignment of * a sampler wouldn't. Fix it up below. */ parameters[i] = NULL; } else { parameters[i] = sig_param->clone(ctx, ht); parameters[i]->mode = ir_var_auto; next_ir->insert_before(parameters[i]); } /* Move the actual param into our param variable if it's an 'in' type. */ if (parameters[i] && (sig_param->mode == ir_var_in || sig_param->mode == ir_var_inout)) { ir_assignment *assign; assign = new(ctx) ir_assignment(new(ctx) ir_dereference_variable(parameters[i]), param, NULL); next_ir->insert_before(assign); } sig_param_iter.next(); param_iter.next(); } exec_list new_instructions; /* Generate the inlined body of the function to a new list */ foreach_iter(exec_list_iterator, iter, callee->body) { ir_instruction *ir = (ir_instruction *)iter.get(); ir_instruction *new_ir = ir->clone(ctx, ht); new_instructions.push_tail(new_ir); visit_tree(new_ir, replace_return_with_assignment, retval); } /* If any samplers were passed in, replace any deref of the sampler * with a deref of the sampler argument. */ param_iter = this->actual_parameters.iterator(); sig_param_iter = this->callee->parameters.iterator(); for (i = 0; i < num_parameters; i++) { ir_instruction *const param = (ir_instruction *) param_iter.get(); ir_variable *sig_param = (ir_variable *) sig_param_iter.get(); if (sig_param->type->base_type == GLSL_TYPE_SAMPLER) { ir_dereference *deref = param->as_dereference(); assert(deref); do_sampler_replacement(&new_instructions, sig_param, deref); } } /* Now push those new instructions in. */ foreach_iter(exec_list_iterator, iter, new_instructions) { ir_instruction *ir = (ir_instruction *)iter.get(); next_ir->insert_before(ir); } /* Copy back the value of any 'out' parameters from the function body * variables to our own. */ i = 0; param_iter = this->actual_parameters.iterator(); sig_param_iter = this->callee->parameters.iterator(); for (i = 0; i < num_parameters; i++) { ir_instruction *const param = (ir_instruction *) param_iter.get(); const ir_variable *const sig_param = (ir_variable *) sig_param_iter.get(); /* Move our param variable into the actual param if it's an 'out' type. */ if (parameters[i] && (sig_param->mode == ir_var_out || sig_param->mode == ir_var_inout)) { ir_assignment *assign; assign = new(ctx) ir_assignment(param->clone(ctx, NULL)->as_rvalue(), new(ctx) ir_dereference_variable(parameters[i]), NULL); next_ir->insert_before(assign); } param_iter.next(); sig_param_iter.next(); } delete [] parameters; hash_table_dtor(ht); if (retval) return new(ctx) ir_dereference_variable(retval); else return NULL; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_expression *ir) { (void) ir; return visit_continue_with_parent; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_return *ir) { (void) ir; return visit_continue_with_parent; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_texture *ir) { (void) ir; return visit_continue_with_parent; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_swizzle *ir) { (void) ir; return visit_continue_with_parent; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_call *ir) { if (can_inline(ir)) { /* If the call was part of some tree, then it should have been * flattened out or we shouldn't have seen it because of a * visit_continue_with_parent in this visitor. */ assert(ir == base_ir); (void) ir->generate_inline(ir); ir->remove(); this->progress = true; } return visit_continue; } ir_visitor_status ir_function_inlining_visitor::visit_enter(ir_assignment *ir) { ir_call *call = ir->rhs->as_call(); if (!call || !can_inline(call)) return visit_continue; /* generates the parameter setup, function body, and returns the return * value of the function */ ir_rvalue *rhs = call->generate_inline(ir); assert(rhs); ir->rhs = rhs; this->progress = true; return visit_continue; } /** * Replaces references to the "sampler" variable with a clone of "deref." * * From the spec, samplers can appear in the tree as function * (non-out) parameters and as the result of array indexing and * structure field selection. In our builtin implementation, they * also appear in the sampler field of an ir_tex instruction. */ class ir_sampler_replacement_visitor : public ir_hierarchical_visitor { public: ir_sampler_replacement_visitor(ir_variable *sampler, ir_dereference *deref) { this->sampler = sampler; this->deref = deref; } virtual ~ir_sampler_replacement_visitor() { } virtual ir_visitor_status visit_leave(ir_call *); virtual ir_visitor_status visit_leave(ir_dereference_array *); virtual ir_visitor_status visit_leave(ir_dereference_record *); virtual ir_visitor_status visit_leave(ir_texture *); void replace_deref(ir_dereference **deref); void replace_rvalue(ir_rvalue **rvalue); ir_variable *sampler; ir_dereference *deref; }; void ir_sampler_replacement_visitor::replace_deref(ir_dereference **deref) { ir_dereference_variable *deref_var = (*deref)->as_dereference_variable(); if (deref_var && deref_var->var == this->sampler) { *deref = this->deref->clone(talloc_parent(*deref), NULL); } } void ir_sampler_replacement_visitor::replace_rvalue(ir_rvalue **rvalue) { if (!*rvalue) return; ir_dereference *deref = (*rvalue)->as_dereference(); if (!deref) return; replace_deref(&deref); *rvalue = deref; } ir_visitor_status ir_sampler_replacement_visitor::visit_leave(ir_texture *ir) { replace_deref(&ir->sampler); return visit_continue; } ir_visitor_status ir_sampler_replacement_visitor::visit_leave(ir_dereference_array *ir) { replace_rvalue(&ir->array); return visit_continue; } ir_visitor_status ir_sampler_replacement_visitor::visit_leave(ir_dereference_record *ir) { replace_rvalue(&ir->record); return visit_continue; } ir_visitor_status ir_sampler_replacement_visitor::visit_leave(ir_call *ir) { foreach_iter(exec_list_iterator, iter, *ir) { ir_rvalue *param = (ir_rvalue *)iter.get(); ir_rvalue *new_param = param; replace_rvalue(&new_param); if (new_param != param) { param->replace_with(new_param); } } return visit_continue; } static void do_sampler_replacement(exec_list *instructions, ir_variable *sampler, ir_dereference *deref) { ir_sampler_replacement_visitor v(sampler, deref); visit_list_elements(&v, instructions); } <|endoftext|>
<commit_before>/* This file is part of VoltDB. * Copyright (C) 2008-2010 VoltDB L.L.C. * * VoltDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FATALEXCEPTION_HPP_ #define FATALEXCEPTION_HPP_ #include <string> #include <string.h> #include <execinfo.h> #include <cxxabi.h> #include <vector> #include "boost/scoped_array.hpp" #define throwFatalException(...) { char reallysuperbig_nonce_message[8192]; sprintf(reallysuperbig_nonce_message, __VA_ARGS__); throw voltdb::FatalException( reallysuperbig_nonce_message, __FILE__, __LINE__); } namespace voltdb { class FatalException { public: FatalException(std::string message, const char *filename, unsigned long lineno) : m_reason(message), m_filename(filename), m_lineno(lineno) { void *traces[128]; const int numTraces = backtrace( traces, 128); boost::scoped_array<char*> traceSymbols(backtrace_symbols( traces, 128)); for (int ii = 0; ii < numTraces; ii++) { std::size_t sz = 200; char *function = static_cast<char*>(malloc(sz)); char *begin = NULL, *end = NULL; //Find parens surrounding mangled name for (char *j = traceSymbols[ii]; *j; ++j) { if (*j == '(') { begin = j; } else if (*j == '+') { end = j; } } if (begin && end) { *begin++ = '\0'; *end = '\0'; int status; char *ret = abi::__cxa_demangle(begin, function, &sz, &status); if (ret) { //return value may be a realloc of input function = ret; } else { // demangle failed, treat it like a C function with no args strncpy(function, begin, sz); strncat(function, "()", sz); function[sz-1] = '\0'; } m_traces.push_back(std::string(function)); } else { //didn't find the mangled name in the trace m_traces.push_back(std::string(traceSymbols[ii])); } free(function); } } const std::string m_reason; const char *m_filename; const unsigned long m_lineno; std::vector<std::string> m_traces; }; } #endif /* FATALEXCEPTION_HPP_ */ <commit_msg>Add attribution to stack trace beautifying code.<commit_after>/* This file is part of VoltDB. * Copyright (C) 2008-2010 VoltDB L.L.C. * * VoltDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FATALEXCEPTION_HPP_ #define FATALEXCEPTION_HPP_ #include <string> #include <string.h> #include <execinfo.h> #include <cxxabi.h> #include <vector> #include "boost/scoped_array.hpp" #define throwFatalException(...) { char reallysuperbig_nonce_message[8192]; sprintf(reallysuperbig_nonce_message, __VA_ARGS__); throw voltdb::FatalException( reallysuperbig_nonce_message, __FILE__, __LINE__); } namespace voltdb { class FatalException { public: /** * Stack trace code from http://tombarta.wordpress.com/2008/08/01/c-stack-traces-with-gcc/ * */ FatalException(std::string message, const char *filename, unsigned long lineno) : m_reason(message), m_filename(filename), m_lineno(lineno) { void *traces[128]; const int numTraces = backtrace( traces, 128); boost::scoped_array<char*> traceSymbols(backtrace_symbols( traces, 128)); for (int ii = 0; ii < numTraces; ii++) { std::size_t sz = 200; char *function = static_cast<char*>(malloc(sz)); char *begin = NULL, *end = NULL; //Find parens surrounding mangled name for (char *j = traceSymbols[ii]; *j; ++j) { if (*j == '(') { begin = j; } else if (*j == '+') { end = j; } } if (begin && end) { *begin++ = '\0'; *end = '\0'; int status; char *ret = abi::__cxa_demangle(begin, function, &sz, &status); if (ret) { //return value may be a realloc of input function = ret; } else { // demangle failed, treat it like a C function with no args strncpy(function, begin, sz); strncat(function, "()", sz); function[sz-1] = '\0'; } m_traces.push_back(std::string(function)); } else { //didn't find the mangled name in the trace m_traces.push_back(std::string(traceSymbols[ii])); } free(function); } } const std::string m_reason; const char *m_filename; const unsigned long m_lineno; std::vector<std::string> m_traces; }; } #endif /* FATALEXCEPTION_HPP_ */ <|endoftext|>
<commit_before>#include "SkBlurDrawLooper.h" #include "SkBlurMaskFilter.h" #include "SkCanvas.h" #include "SkPaint.h" #include "SkMaskFilter.h" SkBlurDrawLooper::SkBlurDrawLooper(SkScalar radius, SkScalar dx, SkScalar dy, SkColor color) : fDx(dx), fDy(dy), fBlurColor(color) { if (radius > 0) fBlur = SkBlurMaskFilter::Create(radius, SkBlurMaskFilter::kNormal_BlurStyle); else fBlur = NULL; } SkBlurDrawLooper::SkBlurDrawLooper(SkFlattenableReadBuffer& buffer) { fDx = buffer.readScalar(); fDy = buffer.readScalar(); fBlurColor = buffer.readU32(); fBlur = static_cast<SkMaskFilter*>(buffer.readFlattenable()); } SkBlurDrawLooper::~SkBlurDrawLooper() { fBlur->safeUnref(); } void SkBlurDrawLooper::flatten(SkFlattenableWriteBuffer& buffer) { buffer.writeScalar(fDx); buffer.writeScalar(fDy); buffer.write32(fBlurColor); buffer.writeFlattenable(fBlur); } void SkBlurDrawLooper::init(SkCanvas* canvas, SkPaint* paint) { // we do nothing if a maskfilter is already installed if (paint->getMaskFilter() != NULL) fState = kDone; else { fState = kBeforeEdge; fPaint = paint; fCanvas = canvas; fSaveCount = canvas->getSaveCount(); } } bool SkBlurDrawLooper::next() { switch (fState) { case kBeforeEdge: fSavedColor = fPaint->getColor(); fPaint->setColor(fBlurColor); fPaint->setMaskFilter(fBlur); fCanvas->save(SkCanvas::kMatrix_SaveFlag); fCanvas->translate(fDx, fDy); fState = kAfterEdge; return true; case kAfterEdge: fPaint->setColor(fSavedColor); fPaint->setMaskFilter(NULL); fCanvas->restore(); // to remove the translate we did earlier fState = kDone; return true; default: SkASSERT(kDone == fState); return false; } } void SkBlurDrawLooper::restore() { if (kAfterEdge == fState) { fPaint->setColor(fSavedColor); fPaint->setMaskFilter(NULL); fCanvas->restore(); // to remove the translate we did earlier fState = kDone; } } /////////////////////////////////////////////////////////////////////////////// static SkFlattenable::Registrar gReg("SkBlurDrawLooper", SkBlurDrawLooper::CreateProc); <commit_msg>Applies the paint's alpha to drop shadows.<commit_after>#include "SkBlurDrawLooper.h" #include "SkBlurMaskFilter.h" #include "SkCanvas.h" #include "SkPaint.h" #include "SkMaskFilter.h" SkBlurDrawLooper::SkBlurDrawLooper(SkScalar radius, SkScalar dx, SkScalar dy, SkColor color) : fDx(dx), fDy(dy), fBlurColor(color) { if (radius > 0) fBlur = SkBlurMaskFilter::Create(radius, SkBlurMaskFilter::kNormal_BlurStyle); else fBlur = NULL; } SkBlurDrawLooper::SkBlurDrawLooper(SkFlattenableReadBuffer& buffer) { fDx = buffer.readScalar(); fDy = buffer.readScalar(); fBlurColor = buffer.readU32(); fBlur = static_cast<SkMaskFilter*>(buffer.readFlattenable()); } SkBlurDrawLooper::~SkBlurDrawLooper() { fBlur->safeUnref(); } void SkBlurDrawLooper::flatten(SkFlattenableWriteBuffer& buffer) { buffer.writeScalar(fDx); buffer.writeScalar(fDy); buffer.write32(fBlurColor); buffer.writeFlattenable(fBlur); } void SkBlurDrawLooper::init(SkCanvas* canvas, SkPaint* paint) { // we do nothing if a maskfilter is already installed if (paint->getMaskFilter() != NULL) fState = kDone; else { fState = kBeforeEdge; fPaint = paint; fCanvas = canvas; fSaveCount = canvas->getSaveCount(); } } bool SkBlurDrawLooper::next() { SkColor blurColor; SkAlpha alpha; switch (fState) { case kBeforeEdge: fSavedColor = fPaint->getColor(); blurColor = fBlurColor; alpha = SkColorGetA(blurColor); if (alpha == 255) { blurColor = SkColorSetA(blurColor, fPaint->getAlpha()); } fPaint->setColor(blurColor); fPaint->setMaskFilter(fBlur); fCanvas->save(SkCanvas::kMatrix_SaveFlag); fCanvas->translate(fDx, fDy); fState = kAfterEdge; return true; case kAfterEdge: fPaint->setColor(fSavedColor); fPaint->setMaskFilter(NULL); fCanvas->restore(); // to remove the translate we did earlier fState = kDone; return true; default: SkASSERT(kDone == fState); return false; } } void SkBlurDrawLooper::restore() { if (kAfterEdge == fState) { fPaint->setColor(fSavedColor); fPaint->setMaskFilter(NULL); fCanvas->restore(); // to remove the translate we did earlier fState = kDone; } } /////////////////////////////////////////////////////////////////////////////// static SkFlattenable::Registrar gReg("SkBlurDrawLooper", SkBlurDrawLooper::CreateProc); <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2011, 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. */ #include <serialize/binary-i-serializer.hh> #include <libport/finally.hh> #include <ast/nary.hh> #include <ast/stmt.hh> #include <libport/debug.hh> #include <urbi/object/lobby.hh> #include <urbi/object/object.hh> #include <urbi/object/tag.hh> #include <urbi/uvalue-serialize.hh> #include <object/system.hh> #include <ast/print.hh> #include <kernel/uconnection.hh> #include <kernel/uobject.hh> #include <kernel/userver.hh> #include <parser/transform.hh> #include <parser/uparser.hh> #include <runner/exception.hh> #include <runner/shell.hh> #include <sched/job.hh> #include <sched/scheduler.hh> namespace runner { GD_CATEGORY(Urbi.Shell); Shell::Shell(const rLobby& lobby, sched::Scheduler& scheduler, const std::string& name, std::istream& input) : Interpreter(lobby, scheduler, ast::rConstAst(), name) , executing_(false) , input_(input) , stop_(false) , binary_mode_(false) , parser_(new parser::UParser(input_)) { GD_FINFO_TRACE("new shell: %s %p", name_get(), this); } Shell::~Shell() { GD_FINFO_TRACE("dying shell: %s %p", name_get(), this); if (serializationJob_) serializationJob_->terminate_asap(); delete parser_; } void Shell::eval_print_(const ast::Exp* exp) { // Visual Studio on Windows does not rewind the stack before the // end of a "try/catch" block, "catch" included. It means that we // cannot display the exception in the "catch" block in case this // is a scheduling error due to stack exhaustion, as we may need // the stack. The following objects will be set if we have an // exception to show, and it will be printed after the "catch" // block, or if we have an exception to rethrow. boost::scoped_ptr<object::UrbiException> exception_to_show; try { object::rObject res = operator()(exp); // We need to keep checking for void here because it // cannot be passed to the << function. if (res && res != object::void_class) { // Display the value using the topLevel channel. If it is not // (yet) defined, do nothing, unless this environment variable // is set. static bool toplevel_debug = getenv("URBI_TOPLEVEL"); rSlot topLevel = lobby_get()->slot_locate(SYMBOL(topLevel), false).second; if (topLevel) topLevel->value()->call(SYMBOL(LT_LT), res); else if (toplevel_debug) { try { rObject result = res->call(SYMBOL(asToplevelPrintable)); std::ostringstream os; result->print(os); lobby_->connection_get().send(os.str()); lobby_->connection_get().endline(); } catch (object::UrbiException&) { // nothing } } } } // Catch and print unhandled exceptions catch (object::UrbiException& e) { exception_to_show.reset(new object::UrbiException(e.value_get(), e.backtrace_get())); } // When we receive the exception fired by "connectionTag.stop", // kill the jobs, not the shell. catch (const sched::StopException& e) { GD_FINFO_DUMP("StopException ignored: %s", e.what()); } catch (const sched::TerminateException&) { GD_INFO_DUMP("TerminateException"); throw; } // Stop invalid exceptions thrown by primitives catch (const std::exception& e) { Exception::warn(exp->location_get(), libport::format("invalid exception caught: %s", e.what())); } catch (...) { Exception::warn(exp->location_get(), "unknown exception caught"); } if (exception_to_show.get()) show_exception(*exception_to_show); } void Shell::handle_command_(ast::rConstExp exp, bool canYield) { LIBPORT_SCOPE_SET(executing_, true); const ast::Stmt* stmt = dynamic_cast<const ast::Stmt*>(exp.get()); if (stmt && stmt->flavor_get() == ast::flavor_comma) { GD_FPUSH_TRACE("%s: executing command in background.", name_get()); GD_FINFO_DUMP("%s: command: %s", name_get(), *exp); sched::rJob subrunner = new Interpreter(*this, stmt->expression_get().get(), libport::Symbol::fresh_string(name_get())); jobs_ << subrunner; subrunner->start_job(); if (canYield && !input_.eof()) yield(); } else { GD_FPUSH_TRACE("%s: executing command (%s).", name_get(), stmt); GD_FINFO_DUMP("%s: command: %s", name_get(), *exp); eval_print_(exp.get()); if (canYield && !input_.eof()) yield(); } if (non_interruptible_get()) { send_message("error", "the toplevel cannot be non-interruptible"); non_interruptible_set(false); } } static void collect_connection(kernel::UConnection* c) { GD_FPUSH_DUMP("closing connection %p", c); aver(c); kernel::server().connection_remove(*c); } void Shell::handle_command_end_() { if (input_.eof()) { stop(); } } void Shell::work() { while (!stop_) { try { work_(); } // Don't kill the shell when we receive the exception // fired by "connectionTag.stop". catch (const sched::StopException& e) { GD_FINFO_DUMP("StopException ignored: %s", e.what()); } } foreach (const sched::rJob& job, jobs_) job->terminate_now(); yield_until_terminated(jobs_); } void Shell::work_() { while (!stop_) { try { parser::parse_result_type res; { GD_FPUSH_TRACE("%s: reading command.", name_get()); // It once happened that parser_ was null here. The // scenario is that an remote UObject in binary mode sends a // message that is too big to fit into the stream buffer, // and as a result the message was incomplete. This caused // processSerializedMessages to end in an unexpected way, // and control returned here, with !stop_. So we returned // in the regular processing flow, although there is no // parser around. // // To work around this, the buffer size was increased (from // 1k to 8k on OS X). assert(parser_); res = parser_->parse(); } ast::rExp ast = parser::transform(ast::rConstExp(res)); handle_command_(ast); handle_command_end_(); } catch (const Exception& e) { GD_FINFO_TRACE("%s: command is invalid, printing errors.", name_get()); e.print(*this); } for (jobs_type::iterator it = jobs_.begin(); it != jobs_.end(); /* nothing */) if ((*it)->terminated()) it = jobs_.erase(it); else ++it; } } void Shell::processSerializedMessages() { GD_CATEGORY(Urbi.Shell.Serialize); GD_INFO_TRACE("Entering processSerializedMessages"); libport::serialize::BinaryISerializer deserializer(input_); while (binary_mode_ && !stop_) { try { GD_INFO_DEBUG("Reading new serialized message type"); char msgType; deserializer >> msgType; GD_FINFO_DEBUG("Processing serialized message of type %s", (int)msgType); std::string code = urbi::uobjects::processSerializedMessage(msgType, deserializer); GD_FINFO_DEBUG("Got value '%s'", code); if (!code.empty()) { // We must parse and execute synchronously, but honor ',': this is // toplevel code. yy::location loc; parser::UParser p(code, &loc); p.oneshot_set(false); ast::rConstExp e = p.parse(); ast::rConstExp ast = parser::transform(e); handle_command_(ast::rConstExp(ast), false); } handle_command_end_(); } // Catch and print unhandled exceptions catch (object::UrbiException& e) { show_exception(object::UrbiException(e.value_get(), e.backtrace_get())); } catch (const Exception& e) { GD_FINFO_TRACE("%s: command is invalid, printing errors.", name_get()); e.print(*this); } catch (const sched::StopException& e) { GD_FINFO_DUMP("StopException ignored: %s", e.what()); } catch (const std::runtime_error& re) { GD_FINFO_TRACE("Serialized message error: %s", re.what()); Exception e; e.err(ast::loc(), re.what()); e.print(*this); } catch (const std::exception& e) { GD_FWARN("Unexpected error '%s' caught in processSerializedMessages", e.what()); throw; } catch(...) { GD_WARN("Unknown error caught in processSerializedMessages"); throw; } for (jobs_type::iterator it = jobs_.begin(); it != jobs_.end(); /* nothing */) if ((*it)->terminated()) it = jobs_.erase(it); else ++it; } } void Shell::setSerializationMode(bool m, const std::string& tag) { GD_CATEGORY(Urbi.Shell.serialize); GD_FINFO_TRACE("setSerializationMode %s", m); if (m == binary_mode_) return; if (!m && binary_mode_) throw std::runtime_error("There is no turning back from serialized mode"); delete parser_; parser_ = 0; lobby_get()->send("1", tag); binary_mode_ = m; if (binary_mode_) processSerializedMessages(); } bool Shell::pending_command_get() const { return executing_ || !commands_.empty(); } void Shell::pending_commands_clear() { commands_.clear(); } void Shell::stop() { if (stop_) return; GD_FPUSH_TRACE("%s: end reached.", name_get()); if (&kernel::urbiserver->ghost_connection_get() != &lobby_get()->connection_get()) { // Asynchronous destruction of the connection is necessary // otherwise the connection destructor (which is stopping the // connection tag) will raise a Stop exception. In addition, the // UConnection is supposed to hold the last reference on this // Shell once the work function has ended, thus scheduling the // ansynchronous destruction will destroy the lobby and the shell. // The UConnection should be fetch before disconnecting the lobby, // because the lobby will lose it's reference on the connection. GD_FPUSH_DUMP("%s: schedule connection destruction.", name_get()); aver(&lobby_get()->connection_get()); kernel::server().schedule( SYMBOL(collect_connection), boost::bind(collect_connection, &lobby_get()->connection_get()) ); GD_FPUSH_DUMP("%s: disconnecting.", name_get()); lobby_get()->disconnect(); stop_ = true; } // Force interruption of work_ lobby_get()->tag_get()->stop(); } } // namespace runner <commit_msg>Shell: don't report TerminateException as unexpected.<commit_after>/* * Copyright (C) 2008-2011, 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. */ #include <serialize/binary-i-serializer.hh> #include <libport/finally.hh> #include <ast/nary.hh> #include <ast/stmt.hh> #include <libport/debug.hh> #include <urbi/object/lobby.hh> #include <urbi/object/object.hh> #include <urbi/object/tag.hh> #include <urbi/uvalue-serialize.hh> #include <object/system.hh> #include <ast/print.hh> #include <kernel/uconnection.hh> #include <kernel/uobject.hh> #include <kernel/userver.hh> #include <parser/transform.hh> #include <parser/uparser.hh> #include <runner/exception.hh> #include <runner/shell.hh> #include <sched/job.hh> #include <sched/scheduler.hh> namespace runner { GD_CATEGORY(Urbi.Shell); Shell::Shell(const rLobby& lobby, sched::Scheduler& scheduler, const std::string& name, std::istream& input) : Interpreter(lobby, scheduler, ast::rConstAst(), name) , executing_(false) , input_(input) , stop_(false) , binary_mode_(false) , parser_(new parser::UParser(input_)) { GD_FINFO_TRACE("new shell: %s %p", name_get(), this); } Shell::~Shell() { GD_FINFO_TRACE("dying shell: %s %p", name_get(), this); if (serializationJob_) serializationJob_->terminate_asap(); delete parser_; } void Shell::eval_print_(const ast::Exp* exp) { // Visual Studio on Windows does not rewind the stack before the // end of a "try/catch" block, "catch" included. It means that we // cannot display the exception in the "catch" block in case this // is a scheduling error due to stack exhaustion, as we may need // the stack. The following objects will be set if we have an // exception to show, and it will be printed after the "catch" // block, or if we have an exception to rethrow. boost::scoped_ptr<object::UrbiException> exception_to_show; try { object::rObject res = operator()(exp); // We need to keep checking for void here because it // cannot be passed to the << function. if (res && res != object::void_class) { // Display the value using the topLevel channel. If it is not // (yet) defined, do nothing, unless this environment variable // is set. static bool toplevel_debug = getenv("URBI_TOPLEVEL"); rSlot topLevel = lobby_get()->slot_locate(SYMBOL(topLevel), false).second; if (topLevel) topLevel->value()->call(SYMBOL(LT_LT), res); else if (toplevel_debug) { try { rObject result = res->call(SYMBOL(asToplevelPrintable)); std::ostringstream os; result->print(os); lobby_->connection_get().send(os.str()); lobby_->connection_get().endline(); } catch (object::UrbiException&) { // nothing } } } } // Catch and print unhandled exceptions catch (object::UrbiException& e) { exception_to_show.reset(new object::UrbiException(e.value_get(), e.backtrace_get())); } // When we receive the exception fired by "connectionTag.stop", // kill the jobs, not the shell. catch (const sched::StopException& e) { GD_FINFO_DUMP("StopException ignored: %s", e.what()); } catch (const sched::TerminateException&) { GD_INFO_DUMP("TerminateException"); throw; } // Stop invalid exceptions thrown by primitives catch (const std::exception& e) { Exception::warn(exp->location_get(), libport::format("invalid exception caught: %s", e.what())); } catch (...) { Exception::warn(exp->location_get(), "unknown exception caught"); } if (exception_to_show.get()) show_exception(*exception_to_show); } void Shell::handle_command_(ast::rConstExp exp, bool canYield) { LIBPORT_SCOPE_SET(executing_, true); const ast::Stmt* stmt = dynamic_cast<const ast::Stmt*>(exp.get()); if (stmt && stmt->flavor_get() == ast::flavor_comma) { GD_FPUSH_TRACE("%s: executing command in background.", name_get()); GD_FINFO_DUMP("%s: command: %s", name_get(), *exp); sched::rJob subrunner = new Interpreter(*this, stmt->expression_get().get(), libport::Symbol::fresh_string(name_get())); jobs_ << subrunner; subrunner->start_job(); if (canYield && !input_.eof()) yield(); } else { GD_FPUSH_TRACE("%s: executing command (%s).", name_get(), stmt); GD_FINFO_DUMP("%s: command: %s", name_get(), *exp); eval_print_(exp.get()); if (canYield && !input_.eof()) yield(); } if (non_interruptible_get()) { send_message("error", "the toplevel cannot be non-interruptible"); non_interruptible_set(false); } } static void collect_connection(kernel::UConnection* c) { GD_FPUSH_DUMP("closing connection %p", c); aver(c); kernel::server().connection_remove(*c); } void Shell::handle_command_end_() { if (input_.eof()) { stop(); } } void Shell::work() { while (!stop_) { try { work_(); } // Don't kill the shell when we receive the exception // fired by "connectionTag.stop". catch (const sched::StopException& e) { GD_FINFO_DUMP("StopException ignored: %s", e.what()); } } foreach (const sched::rJob& job, jobs_) job->terminate_now(); yield_until_terminated(jobs_); } void Shell::work_() { while (!stop_) { try { parser::parse_result_type res; { GD_FPUSH_TRACE("%s: reading command.", name_get()); // It once happened that parser_ was null here. The // scenario is that an remote UObject in binary mode sends a // message that is too big to fit into the stream buffer, // and as a result the message was incomplete. This caused // processSerializedMessages to end in an unexpected way, // and control returned here, with !stop_. So we returned // in the regular processing flow, although there is no // parser around. // // To work around this, the buffer size was increased (from // 1k to 8k on OS X). assert(parser_); res = parser_->parse(); } ast::rExp ast = parser::transform(ast::rConstExp(res)); handle_command_(ast); handle_command_end_(); } catch (const Exception& e) { GD_FINFO_TRACE("%s: command is invalid, printing errors.", name_get()); e.print(*this); } for (jobs_type::iterator it = jobs_.begin(); it != jobs_.end(); /* nothing */) if ((*it)->terminated()) it = jobs_.erase(it); else ++it; } } void Shell::processSerializedMessages() { GD_CATEGORY(Urbi.Shell.Serialize); GD_INFO_TRACE("Entering processSerializedMessages"); libport::serialize::BinaryISerializer deserializer(input_); while (binary_mode_ && !stop_) { try { GD_INFO_DEBUG("Reading new serialized message type"); char msgType; deserializer >> msgType; GD_FINFO_DEBUG("Processing serialized message of type %s", (int)msgType); std::string code = urbi::uobjects::processSerializedMessage(msgType, deserializer); GD_FINFO_DEBUG("Got value '%s'", code); if (!code.empty()) { // We must parse and execute synchronously, but honor ',': this is // toplevel code. yy::location loc; parser::UParser p(code, &loc); p.oneshot_set(false); ast::rConstExp e = p.parse(); ast::rConstExp ast = parser::transform(e); handle_command_(ast::rConstExp(ast), false); } handle_command_end_(); } // Catch and print unhandled exceptions catch (object::UrbiException& e) { show_exception(object::UrbiException(e.value_get(), e.backtrace_get())); } catch (const Exception& e) { GD_FINFO_TRACE("%s: command is invalid, printing errors.", name_get()); e.print(*this); } catch (const sched::StopException& e) { GD_FINFO_DUMP("StopException ignored: %s", e.what()); } catch (const sched::TerminateException&) { GD_INFO_DUMP("TerminateException"); throw; } catch (const std::runtime_error& re) { GD_FINFO_TRACE("Serialized message error: %s", re.what()); Exception e; e.err(ast::loc(), re.what()); e.print(*this); } catch (const std::exception& e) { GD_FWARN("Unexpected error '%s' caught in processSerializedMessages", e.what()); throw; } catch(...) { GD_WARN("Unknown error caught in processSerializedMessages"); throw; } for (jobs_type::iterator it = jobs_.begin(); it != jobs_.end(); /* nothing */) if ((*it)->terminated()) it = jobs_.erase(it); else ++it; } } void Shell::setSerializationMode(bool m, const std::string& tag) { GD_CATEGORY(Urbi.Shell.serialize); GD_FINFO_TRACE("setSerializationMode %s", m); if (m == binary_mode_) return; if (!m && binary_mode_) throw std::runtime_error("There is no turning back from serialized mode"); delete parser_; parser_ = 0; lobby_get()->send("1", tag); binary_mode_ = m; if (binary_mode_) processSerializedMessages(); } bool Shell::pending_command_get() const { return executing_ || !commands_.empty(); } void Shell::pending_commands_clear() { commands_.clear(); } void Shell::stop() { if (stop_) return; GD_FPUSH_TRACE("%s: end reached.", name_get()); if (&kernel::urbiserver->ghost_connection_get() != &lobby_get()->connection_get()) { // Asynchronous destruction of the connection is necessary // otherwise the connection destructor (which is stopping the // connection tag) will raise a Stop exception. In addition, the // UConnection is supposed to hold the last reference on this // Shell once the work function has ended, thus scheduling the // ansynchronous destruction will destroy the lobby and the shell. // The UConnection should be fetch before disconnecting the lobby, // because the lobby will lose it's reference on the connection. GD_FPUSH_DUMP("%s: schedule connection destruction.", name_get()); aver(&lobby_get()->connection_get()); kernel::server().schedule( SYMBOL(collect_connection), boost::bind(collect_connection, &lobby_get()->connection_get()) ); GD_FPUSH_DUMP("%s: disconnecting.", name_get()); lobby_get()->disconnect(); stop_ = true; } // Force interruption of work_ lobby_get()->tag_get()->stop(); } } // namespace runner <|endoftext|>
<commit_before>// Copyright 2014 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 <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ctime> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <utils.hpp> #include <SNR.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char *argv[]) { bool print = false; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int nrDMsPerBlock = 0; unsigned int nrPeriodsPerBlock = 0; unsigned int nrDMsPerThread = 0; unsigned int nrPeriodsPerThread = 0; long long unsigned int wrongSamples = 0; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); print = args.getSwitch("-print"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db"); nrPeriodsPerBlock = args.getSwitchArgument< unsigned int >("-pb"); nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt"); nrPeriodsPerThread = args.getSwitchArgument< unsigned int >("-pt"); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, 0.0); observation.setPeriodRange(args.getSwitchArgument< unsigned int >("-periods"), 0, 0); observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins")); } catch ( isa::utils::SwitchNotFound &err ) { std::cerr << err.what() << std::endl; return 1; }catch ( std::exception &err ) { std::cerr << "Usage: " << argv[0] << " [-print] -opencl_platform ... -opencl_device ... -padding ... -db ... -pb ... -dt ... -pt ... -dms ... -periods ... -bins ..." << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); // Allocate memory std::vector< dataType > foldedData = std::vector< dataType >(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs()); cl::Buffer foldedData_d; std::vector< dataType > snrs = std::vector< dataType >(observation.getNrPeriods() * observation.getNrPaddedDMs()); std::vector< dataType > snrs_c = std::vector< dataType >(observation.getNrPeriods() * observation.getNrPaddedDMs()); cl::Buffer snrs_d; try { foldedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, foldedData.size() * sizeof(dataType), NULL, NULL); snrs_d = cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, snrs.size() * sizeof(dataType), NULL, NULL); } catch ( cl::Error &err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } srand(time(NULL)); for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM] = static_cast< dataType >(rand() % 10); } } } std::fill(snrs.begin(), snrs.end(), static_cast< dataType >(0)); std::fill(snrs_c.begin(), snrs_c.end(), static_cast< dataType >(0)); // Copy data structures to device try { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(foldedData_d, CL_FALSE, 0, foldedData.size() * sizeof(dataType), reinterpret_cast< void * >(foldedData.data())); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(snrs_d, CL_FALSE, 0, snrs.size() * sizeof(dataType), reinterpret_cast< void * >(snrs.data())); } catch ( cl::Error &err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } // Generate kernel cl::Kernel * kernel; std::string * code = PulsarSearch::getSNROpenCL(nrDMsPerBlock, nrPeriodsPerBlock, nrDMsPerThread, nrPeriodsPerThread, typeName, observation); if ( print ) { std::cout << *code << std::endl; } try { kernel = isa::OpenCL::compile("snr", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError &err ) { std::cerr << err.what() << std::endl; return 1; } // Run OpenCL kernel and CPU control try { cl::NDRange global(observation.getNrPaddedDMs() / nrDMsPerThread, observation.getNrPeriods() / nrPeriodsPerThread); cl::NDRange local(nrDMsPerBlock, nrPeriodsPerBlock); kernel->setArg(0, foldedData_d); kernel->setArg(1, snrs_d); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, NULL, NULL); PulsarSearch::snrFoldedTS(observation, foldedData, snrs_c); clQueues->at(clDeviceID)[0].enqueueReadBuffer(snrs_d, CL_TRUE, 0, snrs.size() * sizeof(dataType), reinterpret_cast< void * >(snrs.data())); } catch ( cl::Error &err ) { std::cerr << "OpenCL error: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { if ( ! isa::utils::same(snrs_c[(period * observation.getNrPaddedDMs()) + dm], snrs[(period * observation.getNrPaddedDMs()) + dm]) ) { wrongSamples++; } } } if ( wrongSamples > 0 ) { std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << std::endl; } else { std::cout << "TEST PASSED." << std::endl; } return 0; } <commit_msg>Updated the tests.<commit_after>// Copyright 2014 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 <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ctime> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <utils.hpp> #include <SNR.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char *argv[]) { bool print = false; bool dSNR = false; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int nrDMsPerBlock = 0; unsigned int nrPeriodsPerBlock = 0; unsigned int nrDMsPerThread = 0; unsigned int nrPeriodsPerThread = 0; long long unsigned int wrongSamples = 0; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); print = args.getSwitch("-print"); dSNR = args.getSwitch("-dedispersed"); bool fSNR = args.getSwitch("-folded"); if ( (dSNR && fSNR) || (!dSNR && ! fSNR) ) { throw std::exception(); } clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db"); nrPeriodsPerBlock = args.getSwitchArgument< unsigned int >("-pb"); nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt"); if ( fSNR ) { nrPeriodsPerBlock = args.getSwitchArgument< unsigned int >("-pb"); nrPeriodsPerThread = args.getSwitchArgument< unsigned int >("-pt"); } else { observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); } observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, 0.0); if ( fSNR ) { observation.setPeriodRange(args.getSwitchArgument< unsigned int >("-periods"), 0, 0); observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins")); } } catch ( isa::utils::SwitchNotFound &err ) { std::cerr << err.what() << std::endl; return 1; } catch ( std::exception &err ) { std::cerr << "Usage: " << argv[0] << " [-dedispersed | -folded] [-print] -opencl_platform ... -opencl_device ... -padding ... -db ... -dt ... -dms ..." << std::endl; std::cerr << "\t -dedispersed -samples ..." << std::endl; std::cerr << "\t -folded -pb ... -pt ... -periods .... -bins ..." << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); // Allocate memory std::vector< dataType > foldedData, snrs, snrs_c; std::vector< dataType > transposedData, maxS, meanS, rmsS, maxS_c, meanS_c, rmsS_c; cl::Buffer foldedData_d, snrs_d; cl::Buffer tranposedData_d, maxS_d, meanS_d, rmsS_d; if ( dSNR ) { foldedData.resize(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedBins()); snrs.resize(observation.getNrPeriods() * observation.getNrPaddedDMs()); snrs_c.resize(observation.getNrPeriods() * observation.getNrPaddedDMs()); } else { tranposedData.resize(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs()); maxS.resize(observation.getNrPaddedDMs()); meanS.resize(observation.getNrPaddedDMs()); rmsS.resize(observation.getNrPaddedDMs()); maxS_c.resize(observation.getNrPaddedDMs()); meanS_c.resize(observation.getNrPaddedDMs()); rmsS_c.resize(observation.getNrPaddedDMs()); } try { if ( dSNR ) { transposedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, transposedData.size() * sizeof(dataType), 0, 0); maxS_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, maxS.size() * sizeof(dataType), 0, 0); meanS_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, meanS.size() * sizeof(dataType), 0, 0); rmsS_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, rmsS.size() * sizeof(dataType), 0, 0); } else { foldedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, foldedData.size() * sizeof(dataType), 0, 0); snrs_d = cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, snrs.size() * sizeof(dataType), 0, 0); } } catch ( cl::Error &err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } srand(time(0)); if ( dSNR ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { transposedData[(sample * observation.getNrPaddedDMs()) + dm] = static_cast< dataType >(rand() % 10); } } std::fill(maxS.begin(), maxS.end(), static_cast< dataType >(0)); std::fill(meanS.begin(), meanS.end(), static_cast< dataType >(0)); std::fill(rmsS.begin(), rmsS.end(), static_cast< dataType >(0)); std::fill(maxS_c.begin(), maxS_c.end(), static_cast< dataType >(0)); std::fill(meanS_c.begin(), meanS_c.end(), static_cast< dataType >(0)); std::fill(rmsS_c.begin(), rmsS_c.end(), static_cast< dataType >(0)); } else { for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) { foldedData[(bin * observation.getNrPeriods() * observation.getNrPaddedDMs()) + (period * observation.getNrPaddedDMs()) + DM] = static_cast< dataType >(rand() % 10); } } } std::fill(snrs.begin(), snrs.end(), static_cast< dataType >(0)); std::fill(snrs_c.begin(), snrs_c.end(), static_cast< dataType >(0)); } // Copy data structures to device try { if ( dSNR ) { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(transposedData_d, CL_FALSE, 0, transposedData.size() * sizeof(dataType), reinterpret_cast< void * >(transposedData.data())); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(maxS_d, CL_FALSE, 0, maxS.size() * sizeof(dataType), reinterpret_cast< void * >(maxS.data())); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(meanS_d, CL_FALSE, 0, meanS.size() * sizeof(dataType), reinterpret_cast< void * >(meanS.data())); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(rmsS_d, CL_FALSE, 0, rmsS.size() * sizeof(dataType), reinterpret_cast< void * >(rmsS.data())); } else { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(foldedData_d, CL_FALSE, 0, foldedData.size() * sizeof(dataType), reinterpret_cast< void * >(foldedData.data())); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(snrs_d, CL_FALSE, 0, snrs.size() * sizeof(dataType), reinterpret_cast< void * >(snrs.data())); } } catch ( cl::Error &err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } // Generate kernel cl::Kernel * kernel; std::string * code; if ( dSNR ) { code = PulsarSearch::getSNRDedispersedOpenCL(nrDMsPerBlock, nrDMsPerThread, typeName, observation); } else { code = PulsarSearch::getSNRFoldedOpenCL(nrDMsPerBlock, nrPeriodsPerBlock, nrDMsPerThread, nrPeriodsPerThread, typeName, observation); } if ( print ) { std::cout << *code << std::endl; } try { if ( dSNR ) { kernel = isa::OpenCL::compile("snrDedispersed", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } else { kernel = isa::OpenCL::compile("snrFolded", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } } catch ( isa::OpenCL::OpenCLError &err ) { std::cerr << err.what() << std::endl; return 1; } // Run OpenCL kernel and CPU control try { cl::NDRange global; cl::NDRange local; if ( dSNR ) { cl::NDRange global(observation.getNrPaddedDMs() / nrDMsPerThread); cl::NDRange local(nrDMsPerBlock); kernel->setArg(0, 0); kernel->setArg(1, transposedData_d); kernel->setArg(2, maxS_d); kernel->setArg(3, meanS_d); kernel->setArg(4, rmsS_d); } else { cl::NDRange global(observation.getNrPaddedDMs() / nrDMsPerThread, observation.getNrPeriods() / nrPeriodsPerThread); cl::NDRange local(nrDMsPerBlock, nrPeriodsPerBlock); kernel->setArg(0, foldedData_d); kernel->setArg(1, snrs_d); } clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, 0); if ( dSNR ) { PulsarSearch::snrDedispersedTS(0, observation, transposedData, maxS_c, meanS_c, rmsS_c); clQueues->at(clDeviceID)[0].enqueueReadBuffer(maxS_d, CL_TRUE, 0, maxS.size() * sizeof(dataType), reinterpret_cast< void * >(maxS.data())); clQueues->at(clDeviceID)[0].enqueueReadBuffer(meanS_d, CL_TRUE, 0, meanS.size() * sizeof(dataType), reinterpret_cast< void * >(meanS.data())); clQueues->at(clDeviceID)[0].enqueueReadBuffer(rmsS_d, CL_TRUE, 0, rmsS.size() * sizeof(dataType), reinterpret_cast< void * >(rmsS.data())); } else { PulsarSearch::snrFoldedTS(observation, foldedData, snrs_c); clQueues->at(clDeviceID)[0].enqueueReadBuffer(snrs_d, CL_TRUE, 0, snrs.size() * sizeof(dataType), reinterpret_cast< void * >(snrs.data())); } } catch ( cl::Error &err ) { std::cerr << "OpenCL error: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } if ( dSNR) { for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { dataType snr = (maxS[dm] - meanS[dm]) / std::sqrt(rmsS[dm]); dataType snr_c = (maxS_c[dm] - meanS_c[dm]) / std::sqrt(rmsS_c[dm]); if ( ! isa::utils::same(snr, snr_c) ) { wrongSamples++; } } } else { for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) { for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { if ( ! isa::utils::same(snrs_c[(period * observation.getNrPaddedDMs()) + dm], snrs[(period * observation.getNrPaddedDMs()) + dm]) ) { wrongSamples++; } } } } if ( wrongSamples > 0 ) { if ( dSNR ) { std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / static_cast< long long unsigned int >(observation.getNrDMs()) << "%)." << std::endl; } else { std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods()) << "%)." << std::endl; } } else { std::cout << "TEST PASSED." << std::endl; } return 0; } <|endoftext|>
<commit_before>#ifndef AST_HPP #define AST_HPP #include <string> #include <vector> #include <memory> #include <typeinfo> #include "utils/util.hpp" #include "utils/error.hpp" #include "utils/typeInfo.hpp" #include "token.hpp" namespace llvm { class BasicBlock; } class ASTVisitor; using ASTVisitorLink = PtrUtil<ASTVisitor>::Link; /** \brief A node in an AST This is the abstract superclass for all the nodes in an AST. */ class ASTNode: public std::enable_shared_from_this<ASTNode> { public: using Link = std::shared_ptr<ASTNode>; using WeakLink = std::weak_ptr<ASTNode>; using Children = std::vector<Link>; protected: WeakLink parent = WeakLink(); ///< Parent in the tree Children children {}; ///< Branches/Leaves in the tree Trace trace = defaultTrace; ///< Where in the source was this found static inline void printIndent(uint level) { for (uint i = 0; i < level; i++) print(" "); } public: ASTNode(); virtual ~ASTNode(); /** \brief Add a new child to this node. */ virtual void addChild(Link child); /// Get list of children Children getChildren() const; /** \brief Get child at position \param pos which child. Suports negative positions that count from the end of the children */ Link at(int64 pos) const; void setParent(WeakLink newParent); WeakLink getParent() const; void setTrace(Trace trace); Trace getTrace() const; /// Pretty printing for this node and all his children virtual void printTree(uint level) const; virtual bool operator==(const ASTNode& rhs) const; virtual bool operator!=(const ASTNode& rhs) const; virtual void visit(ASTVisitorLink visitor) = 0; }; /** \brief All the types a BlockNode can be. */ enum BlockType { ROOT_BLOCK, ///< Only the root of the AST is this. CODE_BLOCK, ///< Default. Normal block do...end FUNCTION_BLOCK, ///< Same as CODE_BLOCK, except it is only used for functions IF_BLOCK ///< Used for else clauses. Can be do...else }; /** \brief Represents a block of statements. Children are those statements. */ class BlockNode: public ASTNode { private: BlockType type; public: BlockNode(BlockType type); BlockType getType() const; void printTree(uint level) const override; bool operator==(const ASTNode& rhs) const override; bool operator!=(const ASTNode& rhs) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Represents a piece of an expression. The stored token only contains operators and terminals. If it has an operator, the children are the operands. If it has a terminal, it does not have children. */ class ExpressionNode: public ASTNode { private: Token tok = Token(UNPROCESSED, defaultTrace); public: ExpressionNode(Token token); /// Technically overrides ASTNode::at std::shared_ptr<ExpressionNode> at(int64 pos) const; /// Get stored Token Token getToken() const; void printTree(uint level) const override; bool operator==(const ASTNode& rhs) const override; bool operator!=(const ASTNode& rhs) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Utility class for managing smart pointers of ASTNode subclasses */ template<typename T, typename std::enable_if<std::is_base_of<ASTNode, T>::value>::type* = nullptr> struct Node: public PtrUtil<T> { typedef typename PtrUtil<T>::Link Link; typedef typename PtrUtil<T>::WeakLink WeakLink; /// Create a shared ptr that holds a node template<typename... Args> static Link make(Args... args) { return std::make_shared<T>(args...); } /// Technically overrides PtrUtil<T>::isSameType static inline bool isSameType(ASTNode::Link node) { return typeid(T) == typeid(*node); } /// Technically overrides PtrUtil<T>::dynPtrCast static inline Link dynPtrCast(ASTNode::Link node) { return std::dynamic_pointer_cast<T>(node); } }; /** \brief Stores an abstract syntax tree of a program. */ class AST { private: /// Root of AST Node<BlockNode>::Link root; public: AST(Node<BlockNode>::Link lk); /// Print the tree void print() const; /// Get root Node<BlockNode>::Link getRoot() const; bool operator==(const AST& rhs) const; bool operator!=(const AST& rhs) const; }; #define GET_SIG(linkType, nameOf) Node<linkType>::Link get##nameOf() const; #define SET_SIG(linkType, nameOf) void set##nameOf(std::shared_ptr<linkType> newNode); #define GET_SET_SIGS(linkType, nameOf) \ GET_SIG(linkType, nameOf) \ SET_SIG(linkType, nameOf) /** \brief ASTNode with fixed children count. */ class NoMoreChildrenNode: public ASTNode { public: /** \param childrenCount does not have more than this many children */ NoMoreChildrenNode(int childrenCount); /** \throws InternalError always throws, never use */ void addChild(Link child) override; /// Utility to check if the childIndex'th child is not nullptr bool inline notNull(uint childIndex) const { return children[childIndex] != nullptr; } }; /** \brief Stores metadata about a declaration. Can have one ExpressionNode child representing initialization. Check using hasInit. */ class DeclarationNode: public NoMoreChildrenNode { private: std::string identifier; DefiniteTypeInfo info; public: /** \param identifier name of declared variable \param typeList what types are allowed to be stored in this variable */ DeclarationNode(std::string identifier, TypeList typeList); GET_SET_SIGS(ExpressionNode, Init) /// Get string identifier std::string getIdentifier() const; /// Get DefiniteTypeInfo DefiniteTypeInfo getTypeInfo() const; /// Has dynamic type bool isDynamic() const; /// Has initialization bool hasInit() const; void printTree(uint level) const override; bool operator==(const ASTNode& rhs) const override; bool operator!=(const ASTNode& rhs) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief If statement in AST form. Has 3 children: - Condition - ExpressionNode - SuccessBlock - BlockNode - if Condition is true, run this - FailiureBlock - BlockNode or BranchNode - if Condition if false, run this */ class BranchNode: public NoMoreChildrenNode { public: BranchNode(); GET_SET_SIGS(ExpressionNode, Condition) GET_SET_SIGS(BlockNode, SuccessBlock) GET_SIG(ASTNode, FailiureBlock) SET_SIG(BlockNode, FailiureBlock) SET_SIG(BranchNode, FailiureBlock) void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Represents a loop. Has 4 children: - Init - DeclarationNode - Condition - ExpressionNode - Update - ExpressionNode - Code - BlockNode Example on a for loop: for (Init, Condition, Update) Code */ class LoopNode: public NoMoreChildrenNode { private: /// Used by the break statement llvm::BasicBlock* exitBlock; public: LoopNode(); GET_SET_SIGS(DeclarationNode, Init) GET_SET_SIGS(ExpressionNode, Condition) GET_SET_SIGS(ExpressionNode, Update) GET_SET_SIGS(BlockNode, Code) llvm::BasicBlock* getExitBlock() const; void setExitBlock(llvm::BasicBlock* bb); void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Return statement. Can have an ExpressionNode to be returned. */ class ReturnNode: public NoMoreChildrenNode { public: ReturnNode(); GET_SET_SIGS(ExpressionNode, Value) void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Break statement for exiting a loop. \todo maybe add loop labels so this can break a specific loop */ class BreakLoopNode: public NoMoreChildrenNode { public: BreakLoopNode(); void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Function definition. */ class FunctionNode: public NoMoreChildrenNode { private: std::string ident; FunctionSignature sig; public: FunctionNode(FunctionSignature sig); /// \param ident if empty, behaves just like FunctionNode(FunctionSignature) FunctionNode(std::string ident, FunctionSignature sig); GET_SET_SIGS(BlockNode, Code) std::string getIdentifier() const; const FunctionSignature& getSignature() const; bool isAnon() const; void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; #undef GET_SIG #undef SET_SIG #undef GET_SET_SIGS /** \see VISITOR_VISIT_IMPL_FOR */ #define PURE_VIRTUAL_VISIT(nodeName) virtual void visit##nodeName(Node<nodeName##Node>::Link node) = 0; /** \brief Abstract class for visiting nodes on an AST. */ class ASTVisitor { public: PURE_VIRTUAL_VISIT(Block) PURE_VIRTUAL_VISIT(Expression) PURE_VIRTUAL_VISIT(Declaration) PURE_VIRTUAL_VISIT(Branch) PURE_VIRTUAL_VISIT(Loop) PURE_VIRTUAL_VISIT(Return) PURE_VIRTUAL_VISIT(BreakLoop) PURE_VIRTUAL_VISIT(Function) }; #undef PURE_VIRTUAL_VISIT #endif <commit_msg>Reorder classes in header<commit_after>#ifndef AST_HPP #define AST_HPP #include <string> #include <vector> #include <memory> #include <typeinfo> #include "utils/util.hpp" #include "utils/error.hpp" #include "utils/typeInfo.hpp" #include "token.hpp" namespace llvm { class BasicBlock; } class ASTVisitor; using ASTVisitorLink = PtrUtil<ASTVisitor>::Link; /** \brief A node in an AST This is the abstract superclass for all the nodes in an AST. */ class ASTNode: public std::enable_shared_from_this<ASTNode> { public: using Link = std::shared_ptr<ASTNode>; using WeakLink = std::weak_ptr<ASTNode>; using Children = std::vector<Link>; protected: WeakLink parent = WeakLink(); ///< Parent in the tree Children children {}; ///< Branches/Leaves in the tree Trace trace = defaultTrace; ///< Where in the source was this found static inline void printIndent(uint level) { for (uint i = 0; i < level; i++) print(" "); } public: ASTNode(); virtual ~ASTNode(); /** \brief Add a new child to this node. */ virtual void addChild(Link child); /// Get list of children Children getChildren() const; /** \brief Get child at position \param pos which child. Suports negative positions that count from the end of the children */ Link at(int64 pos) const; void setParent(WeakLink newParent); WeakLink getParent() const; void setTrace(Trace trace); Trace getTrace() const; /// Pretty printing for this node and all his children virtual void printTree(uint level) const; virtual bool operator==(const ASTNode& rhs) const; virtual bool operator!=(const ASTNode& rhs) const; virtual void visit(ASTVisitorLink visitor) = 0; }; /** \brief Utility class for managing smart pointers of ASTNode subclasses */ template<typename T, typename std::enable_if<std::is_base_of<ASTNode, T>::value>::type* = nullptr> struct Node: public PtrUtil<T> { typedef typename PtrUtil<T>::Link Link; typedef typename PtrUtil<T>::WeakLink WeakLink; /// Create a shared ptr that holds a node template<typename... Args> static Link make(Args... args) { return std::make_shared<T>(args...); } /// Technically overrides PtrUtil<T>::isSameType static inline bool isSameType(ASTNode::Link node) { return typeid(T) == typeid(*node); } /// Technically overrides PtrUtil<T>::dynPtrCast static inline Link dynPtrCast(ASTNode::Link node) { return std::dynamic_pointer_cast<T>(node); } }; /** \brief All the types a BlockNode can be. */ enum BlockType { ROOT_BLOCK, ///< Only the root of the AST is this. CODE_BLOCK, ///< Default. Normal block do...end FUNCTION_BLOCK, ///< Same as CODE_BLOCK, except it is only used for functions IF_BLOCK ///< Used for else clauses. Can be do...else }; /** \brief Represents a block of statements. Children are those statements. */ class BlockNode: public ASTNode { private: BlockType type; public: BlockNode(BlockType type); BlockType getType() const; void printTree(uint level) const override; bool operator==(const ASTNode& rhs) const override; bool operator!=(const ASTNode& rhs) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Represents a piece of an expression. The stored token only contains operators and terminals. If it has an operator, the children are the operands. If it has a terminal, it does not have children. */ class ExpressionNode: public ASTNode { private: Token tok = Token(UNPROCESSED, defaultTrace); public: ExpressionNode(Token token); /// Technically overrides ASTNode::at std::shared_ptr<ExpressionNode> at(int64 pos) const; /// Get stored Token Token getToken() const; void printTree(uint level) const override; bool operator==(const ASTNode& rhs) const override; bool operator!=(const ASTNode& rhs) const override; void visit(ASTVisitorLink visitor) override; }; /// \see GET_FOR #define GET_SIG(linkType, nameOf) Node<linkType>::Link get##nameOf() const; /// \see SET_FOR #define SET_SIG(linkType, nameOf) void set##nameOf(std::shared_ptr<linkType> newNode); /// \see GET_SET_FOR #define GET_SET_SIGS(linkType, nameOf) \ GET_SIG(linkType, nameOf); \ SET_SIG(linkType, nameOf); /** \brief ASTNode with fixed children count. */ class NoMoreChildrenNode: public ASTNode { public: /** \param childrenCount does not have more than this many children */ NoMoreChildrenNode(int childrenCount); /** \throws InternalError always throws, never use */ void addChild(Link child) override; /// Utility to check if the childIndex'th child is not nullptr bool inline notNull(uint childIndex) const { return children[childIndex] != nullptr; } }; /** \brief Stores metadata about a declaration. Can have one ExpressionNode child representing initialization. Check using hasInit. */ class DeclarationNode: public NoMoreChildrenNode { private: std::string identifier; DefiniteTypeInfo info; public: /** \param identifier name of declared variable \param typeList what types are allowed to be stored in this variable */ DeclarationNode(std::string identifier, TypeList typeList); GET_SET_SIGS(ExpressionNode, Init) /// Get string identifier std::string getIdentifier() const; /// Get DefiniteTypeInfo DefiniteTypeInfo getTypeInfo() const; /// Has dynamic type bool isDynamic() const; /// Has initialization bool hasInit() const; void printTree(uint level) const override; bool operator==(const ASTNode& rhs) const override; bool operator!=(const ASTNode& rhs) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief If statement in AST form. Has 3 children: - Condition - ExpressionNode - SuccessBlock - BlockNode - if Condition is true, run this - FailiureBlock - BlockNode or BranchNode - if Condition if false, run this */ class BranchNode: public NoMoreChildrenNode { public: BranchNode(); GET_SET_SIGS(ExpressionNode, Condition) GET_SET_SIGS(BlockNode, SuccessBlock) GET_SIG(ASTNode, FailiureBlock) SET_SIG(BlockNode, FailiureBlock) SET_SIG(BranchNode, FailiureBlock) void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Represents a loop. Has 4 children: - Init - DeclarationNode - Condition - ExpressionNode - Update - ExpressionNode - Code - BlockNode Example on a for loop: for (Init, Condition, Update) Code */ class LoopNode: public NoMoreChildrenNode { private: /// Used by the break statement llvm::BasicBlock* exitBlock; public: LoopNode(); GET_SET_SIGS(DeclarationNode, Init) GET_SET_SIGS(ExpressionNode, Condition) GET_SET_SIGS(ExpressionNode, Update) GET_SET_SIGS(BlockNode, Code) llvm::BasicBlock* getExitBlock() const; void setExitBlock(llvm::BasicBlock* bb); void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Return statement. Can have an ExpressionNode to be returned. */ class ReturnNode: public NoMoreChildrenNode { public: ReturnNode(); GET_SET_SIGS(ExpressionNode, Value) void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Break statement for exiting a loop. \todo maybe add loop labels so this can break a specific loop */ class BreakLoopNode: public NoMoreChildrenNode { public: BreakLoopNode(); void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; /** \brief Function definition. */ class FunctionNode: public NoMoreChildrenNode { private: std::string ident; FunctionSignature sig; public: FunctionNode(FunctionSignature sig); /// \param ident if empty, behaves just like FunctionNode(FunctionSignature) FunctionNode(std::string ident, FunctionSignature sig); GET_SET_SIGS(BlockNode, Code) std::string getIdentifier() const; const FunctionSignature& getSignature() const; bool isAnon() const; void printTree(uint level) const override; void visit(ASTVisitorLink visitor) override; }; #undef GET_SIG #undef SET_SIG #undef GET_SET_SIGS /** \brief Stores an abstract syntax tree of a program. */ class AST { private: /// Root of AST Node<BlockNode>::Link root; public: AST(Node<BlockNode>::Link lk); /// Print the tree void print() const; /// Get root Node<BlockNode>::Link getRoot() const; bool operator==(const AST& rhs) const; bool operator!=(const AST& rhs) const; }; /** \see VISITOR_VISIT_IMPL_FOR */ #define PURE_VIRTUAL_VISIT(nodeName) virtual void visit##nodeName(Node<nodeName##Node>::Link node) = 0; /** \brief Abstract class for visiting nodes on an AST. */ class ASTVisitor { public: PURE_VIRTUAL_VISIT(Block) PURE_VIRTUAL_VISIT(Expression) PURE_VIRTUAL_VISIT(Declaration) PURE_VIRTUAL_VISIT(Branch) PURE_VIRTUAL_VISIT(Loop) PURE_VIRTUAL_VISIT(Return) PURE_VIRTUAL_VISIT(BreakLoop) PURE_VIRTUAL_VISIT(Function) }; #undef PURE_VIRTUAL_VISIT #endif <|endoftext|>
<commit_before>#include "TensorFlowEngine.hpp" //#define TF_CPP_MIN_LOG_LEVEL 5 //#define TF_CPP_MIN_VLOG_LEVEL 5 // Windows hack for removing need for protobuf #ifdef WIN32 #include <google/protobuf/stubs/logging.h> #undef GOOGLE_LOG_IF #define GOOGLE_LOG_IF(LEVEL, CONDITION) \ !(CONDITION) ? std::clog : std::cerr // end hack #endif //#include <tensorflow/core/framework/step_stats.pb.h> //#include <tensorflow/core/framework/tensor.h> //#include <tensorflow/core/framework/types.pb.h> //#include <tensorflow/core/lib/strings/stringprintf.h> //#include <tensorflow/core/platform/env.h> //#include <tensorflow/core/platform/mutex.h> //#include <tensorflow/core/platform/types.h> #include <tensorflow/core/public/session.h> //#include <tensorflow/core/graph/default_device.h> //#include <tensorflow/core/platform/init_main.h> //#include <tensorflow/cc/framework/ops.h> //#include <tensorflow/core/platform/logging.h> #include <FAST/Utility.hpp> #include <tensorflow/cc/saved_model/loader.h> #include <tensorflow/cc/saved_model/loader_util.h> #include <tensorflow/cc/saved_model/tag_constants.h> #include <tensorflow/cc/saved_model/reader.h> namespace fast { class TensorFlowTensorWrapper { public: explicit TensorFlowTensorWrapper(tensorflow::Tensor&& inTensor) : tensor(inTensor) {}; tensorflow::Tensor tensor; }; void TensorFlowTensor::create(TensorFlowTensorWrapper* wrapper) { m_tensorflowTensor = wrapper; auto shape = m_tensorflowTensor->tensor.shape(); TensorShape fastShape; for(int i = 0; i < shape.dims(); ++i) fastShape.addDimension(shape.dim_size(i)); m_shape = fastShape; m_spacing = VectorXf::Ones(m_shape.getDimensions()); mHostDataIsUpToDate = true; if(m_shape.getDimensions() >= 3) { const int width = m_shape[m_shape.getDimensions() - 2]; const int height = m_shape[m_shape.getDimensions() - 3]; mBoundingBox = DataBoundingBox(Vector3f(width, height, 1)); } /* // Unnecessary copy.. auto data = make_uninitialized_unique<float[]>(fastShape.getTotalSize()); std::memcpy(data.get(), tensorflowTensor.flat<float>().data(), fastShape.getTotalSize()*sizeof(float)); Tensor::create(std::move(data), fastShape); */ } bool TensorFlowTensor::hasAnyData() { return true; } TensorFlowTensor::~TensorFlowTensor() { delete m_tensorflowTensor; } float* TensorFlowTensor::getHostDataPointer() { return m_tensorflowTensor->tensor.flat<float>().data(); } static TensorShape getShape(const tensorflow::NodeDef& node) { TensorShape resultShape; if(node.attr().count("shape") > 0) { auto shape = node.attr().at("shape").shape(); for(int i = 0; i < shape.dim_size(); i++) { resultShape.addDimension(shape.dim(i).size()); } } return resultShape; } void TensorFlowEngine::run() { if(mInputNodes.empty()) throw Exception("At least one output node has to be given to the NeuralNetwork before execution"); if(mOutputNodes.empty()) throw Exception("At least one output node has to be given to the NeuralNetwork before execution"); // For each input, create a tensorflow tensor: std::vector <std::pair<std::string, tensorflow::Tensor>> input_tensors; for(auto inputNode : mInputNodes) { const std::string name = inputNode.first; if(!inputNode.second.data) throw Exception("Input node " + name + " has not received any data"); auto shape = inputNode.second.data->getShape(); if(shape.getUnknownDimensions() > 0) throw Exception("Input shape must be fully known when executing NN"); // Construct tensorflow tensor tensorflow::TensorShape tensorShape; for(auto i : shape.getAll()) { tensorShape.AddDim(i); } tensorflow::Tensor input_tensor( tensorflow::DT_FLOAT, tensorShape ); // Give tensor data to tensorflow // TODO is the data here actually moved? TensorAccess::pointer access = inputNode.second.data->getAccess(ACCESS_READ); switch(shape.getDimensions()) { case 2: input_tensor.tensor<float, 2>() = std::move(access->getData<2>()); break; case 3: input_tensor.tensor<float, 3>() = std::move(access->getData<3>()); break; case 4: input_tensor.tensor<float, 4>() = std::move(access->getData<4>()); break; case 5: input_tensor.tensor<float, 5>() = std::move(access->getData<5>()); break; case 6: input_tensor.tensor<float, 6>() = std::move(access->getData<6>()); break; default: throw Exception("Invalid tensor dimension size"); } // Add tensorflow tensor to list of input tensors input_tensors.push_back(std::make_pair(name, input_tensor)); } for(std::string name : mLearningPhaseTensors) { // Create a scalar tensor which tells the system we are NOT doing training tensorflow::Tensor input_tensor2( tensorflow::DT_BOOL, tensorflow::TensorShape() // Scalar ); auto input_tensor_mapped2 = input_tensor2.tensor<bool, 0>(); input_tensor_mapped2(0) = false; input_tensors.push_back(std::make_pair(name, input_tensor2)); } std::vector<tensorflow::Tensor> output_tensors; reportInfo() << "Running network" << reportEnd(); tensorflow::Status s; //mRuntimeManager->startRegularTimer("network_execution"); std::vector<std::string> outputNames; for(auto node : mOutputNodes) outputNames.push_back(node.first); s = mSession->Run(input_tensors, outputNames, {}, &output_tensors); //mRuntimeManager->stopRegularTimer("network_execution"); if (!s.ok()) { throw Exception("Error during inference: " + s.ToString()); } reportInfo() << "Finished executing network" << reportEnd(); // Collect all output data as FAST tensors for(int j = 0; j < outputNames.size(); ++j) { const std::string outputName = outputNames[j]; const NetworkNode node = mOutputNodes[outputName]; auto tensor = TensorFlowTensor::New(); tensor->create(new TensorFlowTensorWrapper(std::move(output_tensors[j]))); mOutputNodes[outputName].data = tensor; } reportInfo() << "Finished parsing output" << reportEnd(); } void TensorFlowEngine::load() { const auto networkFilename = getFilename(); tensorflow::SessionOptions options; tensorflow::ConfigProto &config = options.config; #ifndef WIN32 // These lines cause linking issues on windows config.mutable_gpu_options()->set_allow_growth(true); // Set this so that tensorflow will not use up all GPU memory if (m_deviceType == InferenceDeviceType::CPU) { config.mutable_gpu_options()->set_visible_device_list(""); } else if (m_deviceIndex >= 0) { config.mutable_gpu_options()->set_visible_device_list(std::to_string(m_deviceIndex)); } #endif /* tensorflow::GPUOptions* gpuOptions = config.mutable_gpu_options(); gpuOptions->set_allow_growth(true); //gpuOptions->set_per_process_gpu_memory_fraction(0.5); */ tensorflow::GraphDef tensorflow_graph; if(networkFilename.substr(networkFilename.size()-3) == ".pb" || tensorflow::MaybeSavedModelDirectory(networkFilename) == false) { // Load a frozen protobuf file (.pb) if(!fileExists(networkFilename)) throw Exception(networkFilename + " does not exist"); reportInfo() << "Loading network file: " << networkFilename << reportEnd(); tensorflow::Status s = ReadBinaryProto(tensorflow::Env::Default(), networkFilename, &tensorflow_graph); if (!s.ok()) { throw Exception("Could not read TensorFlow graph file " + networkFilename); } reportInfo() << "Creating session." << reportEnd(); mSession.reset(tensorflow::NewSession(options)); s = mSession->Create(tensorflow_graph); if (!s.ok()) { throw Exception("Could not create TensorFlow Graph: " + s.error_message()); } } else { // Load a model stored in the SavedModel format mSavedModelBundle = std::make_unique<tensorflow::SavedModelBundle>(); tensorflow::RunOptions runOptions; auto s = tensorflow::LoadSavedModel(options, runOptions, networkFilename, {tensorflow::kSavedModelTagServe}, mSavedModelBundle.get()); if(!s.ok()) { throw Exception("Could not read TensorFlow SavedModel from " + networkFilename); } tensorflow::MetaGraphDef metaGraphDef = mSavedModelBundle->meta_graph_def; mSession.reset(mSavedModelBundle->GetSession()); tensorflow_graph = metaGraphDef.graph_def(); } // Analyze nodes to find input node bool nodesSpecified = true; int inputCounter = 0; if(mInputNodes.size() == 0) { nodesSpecified = false; } for(int i = 0; i < tensorflow_graph.node_size(); ++i) { tensorflow::NodeDef node = tensorflow_graph.node(i); if(mInputNodes.count(node.name()) > 0) { } if(node.op() == "Placeholder") { if(node.name().find("keras_learning_phase") != std::string::npos) { //mLearningPhaseTensors.insert(node.name()); mLearningPhaseTensors.push_back(node.name()); } else { // Input node found: // Get its shape // Input nodes use the Op Placeholder reportInfo() << "Found input node: " << i << " with name " << node.name() << reportEnd(); auto shape = getShape(node); reportInfo() << "Node has shape " << shape.toString() << reportEnd(); if(mInputNodes.count(node.name()) == 0) { if(nodesSpecified) { throw Exception("Encountered unknown node " + node.name()); } reportInfo() << "Node was not specified by user" << reportEnd(); // If node has not been specified by user, we need to add it // and thus know its type (fast image or tensor) // It is assumed to be an image if input shape has at least 4 dimensions NodeType type = NodeType::TENSOR; if(shape.getDimensions() >= 4) { reportInfo() << "Assuming node is an image" << reportEnd(); type = NodeType::IMAGE; } else if(shape.getDimensions() > 0) { reportInfo() << "Assuming node is a tensor" << reportEnd(); } else { reportInfo() << "Node has dimension 0, skipping.." << reportEnd(); continue; } addInputNode(inputCounter, node.name(), type, shape); ++inputCounter; } } } } // If no output nodes, guess that last node is the output node if(mOutputNodes.empty()) { tensorflow::NodeDef node = tensorflow_graph.node(tensorflow_graph.node_size()-1); reportWarning() << "No output nodes were given to TensorFlow engine, FAST is guessing it is the last node with name " << node.name() << reportEnd(); addOutputNode(0, node.name()); } // Clear the proto to save memory space. tensorflow_graph.Clear(); reportInfo() << "TensorFlow graph loaded from: " << networkFilename << reportEnd(); setIsLoaded(true); } TensorFlowEngine::TensorFlowEngine() { } TensorFlowEngine::~TensorFlowEngine() { if(mSession) { mSession->Close(); } } ImageOrdering TensorFlowEngine::getPreferredImageOrdering() const { return ImageOrdering::ChannelLast; } std::string TensorFlowEngine::getName() const { return "TensorFlow"; } std::string TensorFlowEngine::getDefaultFileExtension() const { return "pb"; } std::vector<InferenceDeviceInfo> TensorFlowEngine::getDeviceList() { std::vector<InferenceDeviceInfo> result; InferenceDeviceInfo cpu; cpu.type = InferenceDeviceType::CPU; cpu.index = 0; result.push_back(cpu); #ifdef FAST_TENSORFLOW_BUILD_CUDA { // TODO how to query number of devices? InferenceDeviceInfo device; device.type = InferenceDeviceType::GPU; device.index = 0; result.push_back(device); } #endif #ifdef FAST_TENSORFLOW_BUILD_ROCM { // TODO ROCm how? InferenceDeviceInfo device; device.type = InferenceDeviceType::GPU; device.index = 0; result.push_back(device); } #endif return result; } } <commit_msg>Enabled allow_growth an other session options for Windows, which was excluded previously due to linking issues which have been resolved<commit_after>#include "TensorFlowEngine.hpp" //#define TF_CPP_MIN_LOG_LEVEL 5 //#define TF_CPP_MIN_VLOG_LEVEL 5 // Windows hack for removing need for protobuf #ifdef WIN32 #include <google/protobuf/stubs/logging.h> #undef GOOGLE_LOG_IF #define GOOGLE_LOG_IF(LEVEL, CONDITION) \ !(CONDITION) ? std::clog : std::cerr // end hack #endif //#include <tensorflow/core/framework/step_stats.pb.h> //#include <tensorflow/core/framework/tensor.h> //#include <tensorflow/core/framework/types.pb.h> //#include <tensorflow/core/lib/strings/stringprintf.h> //#include <tensorflow/core/platform/env.h> //#include <tensorflow/core/platform/mutex.h> //#include <tensorflow/core/platform/types.h> #include <tensorflow/core/public/session.h> //#include <tensorflow/core/graph/default_device.h> //#include <tensorflow/core/platform/init_main.h> //#include <tensorflow/cc/framework/ops.h> //#include <tensorflow/core/platform/logging.h> #include <FAST/Utility.hpp> #include <tensorflow/cc/saved_model/loader.h> #include <tensorflow/cc/saved_model/loader_util.h> #include <tensorflow/cc/saved_model/tag_constants.h> #include <tensorflow/cc/saved_model/reader.h> namespace fast { class TensorFlowTensorWrapper { public: explicit TensorFlowTensorWrapper(tensorflow::Tensor&& inTensor) : tensor(inTensor) {}; tensorflow::Tensor tensor; }; void TensorFlowTensor::create(TensorFlowTensorWrapper* wrapper) { m_tensorflowTensor = wrapper; auto shape = m_tensorflowTensor->tensor.shape(); TensorShape fastShape; for(int i = 0; i < shape.dims(); ++i) fastShape.addDimension(shape.dim_size(i)); m_shape = fastShape; m_spacing = VectorXf::Ones(m_shape.getDimensions()); mHostDataIsUpToDate = true; if(m_shape.getDimensions() >= 3) { const int width = m_shape[m_shape.getDimensions() - 2]; const int height = m_shape[m_shape.getDimensions() - 3]; mBoundingBox = DataBoundingBox(Vector3f(width, height, 1)); } /* // Unnecessary copy.. auto data = make_uninitialized_unique<float[]>(fastShape.getTotalSize()); std::memcpy(data.get(), tensorflowTensor.flat<float>().data(), fastShape.getTotalSize()*sizeof(float)); Tensor::create(std::move(data), fastShape); */ } bool TensorFlowTensor::hasAnyData() { return true; } TensorFlowTensor::~TensorFlowTensor() { delete m_tensorflowTensor; } float* TensorFlowTensor::getHostDataPointer() { return m_tensorflowTensor->tensor.flat<float>().data(); } static TensorShape getShape(const tensorflow::NodeDef& node) { TensorShape resultShape; if(node.attr().count("shape") > 0) { auto shape = node.attr().at("shape").shape(); for(int i = 0; i < shape.dim_size(); i++) { resultShape.addDimension(shape.dim(i).size()); } } return resultShape; } void TensorFlowEngine::run() { if(mInputNodes.empty()) throw Exception("At least one output node has to be given to the NeuralNetwork before execution"); if(mOutputNodes.empty()) throw Exception("At least one output node has to be given to the NeuralNetwork before execution"); // For each input, create a tensorflow tensor: std::vector <std::pair<std::string, tensorflow::Tensor>> input_tensors; for(auto inputNode : mInputNodes) { const std::string name = inputNode.first; if(!inputNode.second.data) throw Exception("Input node " + name + " has not received any data"); auto shape = inputNode.second.data->getShape(); if(shape.getUnknownDimensions() > 0) throw Exception("Input shape must be fully known when executing NN"); // Construct tensorflow tensor tensorflow::TensorShape tensorShape; for(auto i : shape.getAll()) { tensorShape.AddDim(i); } tensorflow::Tensor input_tensor( tensorflow::DT_FLOAT, tensorShape ); // Give tensor data to tensorflow // TODO is the data here actually moved? TensorAccess::pointer access = inputNode.second.data->getAccess(ACCESS_READ); switch(shape.getDimensions()) { case 2: input_tensor.tensor<float, 2>() = std::move(access->getData<2>()); break; case 3: input_tensor.tensor<float, 3>() = std::move(access->getData<3>()); break; case 4: input_tensor.tensor<float, 4>() = std::move(access->getData<4>()); break; case 5: input_tensor.tensor<float, 5>() = std::move(access->getData<5>()); break; case 6: input_tensor.tensor<float, 6>() = std::move(access->getData<6>()); break; default: throw Exception("Invalid tensor dimension size"); } // Add tensorflow tensor to list of input tensors input_tensors.push_back(std::make_pair(name, input_tensor)); } for(std::string name : mLearningPhaseTensors) { // Create a scalar tensor which tells the system we are NOT doing training tensorflow::Tensor input_tensor2( tensorflow::DT_BOOL, tensorflow::TensorShape() // Scalar ); auto input_tensor_mapped2 = input_tensor2.tensor<bool, 0>(); input_tensor_mapped2(0) = false; input_tensors.push_back(std::make_pair(name, input_tensor2)); } std::vector<tensorflow::Tensor> output_tensors; reportInfo() << "Running network" << reportEnd(); tensorflow::Status s; //mRuntimeManager->startRegularTimer("network_execution"); std::vector<std::string> outputNames; for(auto node : mOutputNodes) outputNames.push_back(node.first); s = mSession->Run(input_tensors, outputNames, {}, &output_tensors); //mRuntimeManager->stopRegularTimer("network_execution"); if (!s.ok()) { throw Exception("Error during inference: " + s.ToString()); } reportInfo() << "Finished executing network" << reportEnd(); // Collect all output data as FAST tensors for(int j = 0; j < outputNames.size(); ++j) { const std::string outputName = outputNames[j]; const NetworkNode node = mOutputNodes[outputName]; auto tensor = TensorFlowTensor::New(); tensor->create(new TensorFlowTensorWrapper(std::move(output_tensors[j]))); mOutputNodes[outputName].data = tensor; } reportInfo() << "Finished parsing output" << reportEnd(); } void TensorFlowEngine::load() { // Setup tensorflow session options tensorflow::SessionOptions options; tensorflow::ConfigProto &config = options.config; config.mutable_gpu_options()->set_allow_growth(true); // Set this so that tensorflow will not use up all GPU memory if (m_deviceType == InferenceDeviceType::CPU) { config.mutable_gpu_options()->set_visible_device_list(""); // Hide devices to force CPU execution } else if (m_deviceIndex >= 0) { config.mutable_gpu_options()->set_visible_device_list(std::to_string(m_deviceIndex)); // Use specific GPU } tensorflow::GraphDef tensorflow_graph; const auto networkFilename = getFilename(); if(networkFilename.substr(networkFilename.size()-3) == ".pb" || tensorflow::MaybeSavedModelDirectory(networkFilename) == false) { // Load a frozen protobuf file (.pb) if(!fileExists(networkFilename)) throw Exception(networkFilename + " does not exist"); reportInfo() << "Loading network file: " << networkFilename << reportEnd(); tensorflow::Status s = ReadBinaryProto(tensorflow::Env::Default(), networkFilename, &tensorflow_graph); if (!s.ok()) { throw Exception("Could not read TensorFlow graph file " + networkFilename); } reportInfo() << "Creating session." << reportEnd(); mSession.reset(tensorflow::NewSession(options)); s = mSession->Create(tensorflow_graph); if (!s.ok()) { throw Exception("Could not create TensorFlow Graph: " + s.error_message()); } } else { // Load a model stored in the SavedModel format mSavedModelBundle = std::make_unique<tensorflow::SavedModelBundle>(); tensorflow::RunOptions runOptions; auto s = tensorflow::LoadSavedModel(options, runOptions, networkFilename, {tensorflow::kSavedModelTagServe}, mSavedModelBundle.get()); if(!s.ok()) { throw Exception("Could not read TensorFlow SavedModel from " + networkFilename); } tensorflow::MetaGraphDef metaGraphDef = mSavedModelBundle->meta_graph_def; mSession.reset(mSavedModelBundle->GetSession()); tensorflow_graph = metaGraphDef.graph_def(); } // Analyze nodes to find input node bool nodesSpecified = true; int inputCounter = 0; if(mInputNodes.size() == 0) { nodesSpecified = false; } for(int i = 0; i < tensorflow_graph.node_size(); ++i) { tensorflow::NodeDef node = tensorflow_graph.node(i); if(mInputNodes.count(node.name()) > 0) { } if(node.op() == "Placeholder") { if(node.name().find("keras_learning_phase") != std::string::npos) { //mLearningPhaseTensors.insert(node.name()); mLearningPhaseTensors.push_back(node.name()); } else { // Input node found: // Get its shape // Input nodes use the Op Placeholder reportInfo() << "Found input node: " << i << " with name " << node.name() << reportEnd(); auto shape = getShape(node); reportInfo() << "Node has shape " << shape.toString() << reportEnd(); if(mInputNodes.count(node.name()) == 0) { if(nodesSpecified) { throw Exception("Encountered unknown node " + node.name()); } reportInfo() << "Node was not specified by user" << reportEnd(); // If node has not been specified by user, we need to add it // and thus know its type (fast image or tensor) // It is assumed to be an image if input shape has at least 4 dimensions NodeType type = NodeType::TENSOR; if(shape.getDimensions() >= 4) { reportInfo() << "Assuming node is an image" << reportEnd(); type = NodeType::IMAGE; } else if(shape.getDimensions() > 0) { reportInfo() << "Assuming node is a tensor" << reportEnd(); } else { reportInfo() << "Node has dimension 0, skipping.." << reportEnd(); continue; } addInputNode(inputCounter, node.name(), type, shape); ++inputCounter; } } } } // If no output nodes, guess that last node is the output node if(mOutputNodes.empty()) { tensorflow::NodeDef node = tensorflow_graph.node(tensorflow_graph.node_size()-1); reportWarning() << "No output nodes were given to TensorFlow engine, FAST is guessing it is the last node with name " << node.name() << reportEnd(); addOutputNode(0, node.name()); } // Clear the proto to save memory space. tensorflow_graph.Clear(); reportInfo() << "TensorFlow graph loaded from: " << networkFilename << reportEnd(); setIsLoaded(true); } TensorFlowEngine::TensorFlowEngine() { } TensorFlowEngine::~TensorFlowEngine() { if(mSession) { mSession->Close(); } } ImageOrdering TensorFlowEngine::getPreferredImageOrdering() const { return ImageOrdering::ChannelLast; } std::string TensorFlowEngine::getName() const { return "TensorFlow"; } std::string TensorFlowEngine::getDefaultFileExtension() const { return "pb"; } std::vector<InferenceDeviceInfo> TensorFlowEngine::getDeviceList() { std::vector<InferenceDeviceInfo> result; InferenceDeviceInfo cpu; cpu.type = InferenceDeviceType::CPU; cpu.index = 0; result.push_back(cpu); #ifdef FAST_TENSORFLOW_BUILD_CUDA { // TODO how to query number of devices? InferenceDeviceInfo device; device.type = InferenceDeviceType::GPU; device.index = 0; result.push_back(device); } #endif #ifdef FAST_TENSORFLOW_BUILD_ROCM { // TODO ROCm how? InferenceDeviceInfo device; device.type = InferenceDeviceType::GPU; device.index = 0; result.push_back(device); } #endif return result; } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/nest/p10_chiplet_fabric_scominit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2019,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_chiplet_fabric_scominit.C /// @brief Apply fabric scom inits to prepare for xlink enablement /// /// *HWP HW Maintainer: Jenny Huynh <jhuynh@us.ibm.com> /// *HWP FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com> /// *HWP Consumed by: HB /// //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p10_chiplet_fabric_scominit.H> #include <p10_smp_link_firs.H> #include <p10_fbc_utils.H> #include <p10_fbc_no_hp_scom.H> #include <p10_fbc_ptl_scom.H> #include <p10_fbc_dlp_scom.H> #include <p10_scom_proc.H> //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ fapi2::ReturnCode p10_chiplet_fabric_scominit( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const bool i_config_intranode, const bool i_config_internode) { FAPI_DBG("Start"); FAPI_DBG(" i_config_intranode: %d", i_config_intranode); FAPI_DBG(" i_config_internode: %d", i_config_internode); fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; auto l_iohs_targets = i_target.getChildren<fapi2::TARGET_TYPE_IOHS>(); char l_tgt_str[fapi2::MAX_ECMD_STRING_LEN]; fapi2::ReturnCode l_rc; if (i_config_intranode) { // apply FBC non-hotplug scom initfile fapi2::toString(i_target, l_tgt_str, sizeof(l_tgt_str)); FAPI_DBG("Invoking p10.fbc.no_hp.scom.initfile on target %s...", l_tgt_str); FAPI_EXEC_HWP(l_rc, p10_fbc_no_hp_scom, i_target, FAPI_SYSTEM); FAPI_TRY(l_rc, "Error from p10_fbc_no_hp_scom"); // mask FIRs on proc/pauc scope if there are no valid links if(!l_iohs_targets.size()) { auto l_iohs_present = i_target.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_PRESENT); for(auto l_iohs : l_iohs_present) { FAPI_TRY(p10_smp_link_firs(l_iohs, sublink_t::BOTH, action_t::INACTIVE), "Error from p10_smp_link_firs when masking firs for all links"); } } } for (auto l_iohs : l_iohs_targets) { fapi2::ATTR_PROC_FABRIC_LINK_ACTIVE_Type l_fabric_link_active; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_LINK_ACTIVE, l_iohs, l_fabric_link_active), "Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_LINK_ACTIVE)"); if(l_fabric_link_active == fapi2::ENUM_ATTR_PROC_FABRIC_LINK_ACTIVE_TRUE) { fapi2::ATTR_IOHS_DRAWER_INTERCONNECT_Type l_drawer_interconnect; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IOHS_DRAWER_INTERCONNECT, l_iohs, l_drawer_interconnect), "Error from FAPI_ATTR_GET (ATTR_IOHS_DRAWER_INTERCONNECT)"); if((i_config_intranode && (l_drawer_interconnect == fapi2::ENUM_ATTR_IOHS_DRAWER_INTERCONNECT_FALSE)) || (i_config_internode && (l_drawer_interconnect == fapi2::ENUM_ATTR_IOHS_DRAWER_INTERCONNECT_TRUE))) { auto l_pauc = l_iohs.getParent<fapi2::TARGET_TYPE_PAUC>(); fapi2::ATTR_IOHS_LINK_TRAIN_Type l_link_train; sublink_t sublink_opt; // apply FBC TL scom initfile fapi2::toString(l_pauc, l_tgt_str, sizeof(l_tgt_str)); FAPI_DBG("Invoking p10.fbc.ptl.scom.initfile on target %s...", l_tgt_str); FAPI_EXEC_HWP(l_rc, p10_fbc_ptl_scom, l_pauc, i_target, FAPI_SYSTEM); FAPI_TRY(l_rc, "Error from p10_fbc_ptl_scom"); // apply FBC DL scom initfile fapi2::toString(l_iohs, l_tgt_str, sizeof(l_tgt_str)); FAPI_DBG("Invoking p10.fbc.dlp.scom.initfile on target %s...", l_tgt_str); FAPI_EXEC_HWP(l_rc, p10_fbc_dlp_scom, l_iohs, i_target, FAPI_SYSTEM); FAPI_TRY(l_rc, "Error from p10_fbc_dlp_scom"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IOHS_LINK_TRAIN, l_iohs, l_link_train), "Error from FAPI_ATTR_GET (ATTR_IOHS_LINK_TRAIN)"); switch(l_link_train) { case fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_BOTH: sublink_opt = sublink_t::BOTH; break; case fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_EVEN_ONLY: sublink_opt = sublink_t::EVEN; break; case fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_ODD_ONLY: sublink_opt = sublink_t::ODD; break; default: sublink_opt = sublink_t::NONE; break; } // setup and unmask TL/DL FIRs FAPI_TRY(p10_smp_link_firs(l_iohs, sublink_opt, action_t::RUNTIME), "Error from p10_smp_link_firs when configuring for runtime operations"); } } else { // mask TL/DL FIRs for links that are not configured for smp operations if (i_config_intranode) { FAPI_TRY(p10_smp_link_firs(l_iohs, sublink_t::BOTH, action_t::INACTIVE), "Error from p10_smp_link_firs when configuring both sublinks for inactive operations"); } } } fapi_try_exit: FAPI_DBG("End"); return fapi2::current_err; } <commit_msg>Mask all link firs before configuring link settings<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/nest/p10_chiplet_fabric_scominit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2019,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_chiplet_fabric_scominit.C /// @brief Apply fabric scom inits to prepare for xlink enablement /// /// *HWP HW Maintainer: Jenny Huynh <jhuynh@us.ibm.com> /// *HWP FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com> /// *HWP Consumed by: HB /// //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p10_chiplet_fabric_scominit.H> #include <p10_smp_link_firs.H> #include <p10_fbc_utils.H> #include <p10_fbc_no_hp_scom.H> #include <p10_fbc_ptl_scom.H> #include <p10_fbc_dlp_scom.H> #include <p10_scom_proc.H> //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ fapi2::ReturnCode p10_chiplet_fabric_scominit( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const bool i_config_intranode, const bool i_config_internode) { FAPI_DBG("Start"); FAPI_DBG(" i_config_intranode: %d", i_config_intranode); FAPI_DBG(" i_config_internode: %d", i_config_internode); fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM; auto l_iohs_targets = i_target.getChildren<fapi2::TARGET_TYPE_IOHS>(); char l_tgt_str[fapi2::MAX_ECMD_STRING_LEN]; fapi2::ReturnCode l_rc; if (i_config_intranode) { // apply FBC non-hotplug scom initfile fapi2::toString(i_target, l_tgt_str, sizeof(l_tgt_str)); FAPI_DBG("Invoking p10.fbc.no_hp.scom.initfile on target %s...", l_tgt_str); FAPI_EXEC_HWP(l_rc, p10_fbc_no_hp_scom, i_target, FAPI_SYSTEM); FAPI_TRY(l_rc, "Error from p10_fbc_no_hp_scom"); // init all FIRs as inactive before applying configuration for(auto l_iohs : i_target.getChildren<fapi2::TARGET_TYPE_IOHS>(fapi2::TARGET_STATE_PRESENT)) { FAPI_TRY(p10_smp_link_firs(l_iohs, sublink_t::BOTH, action_t::INACTIVE), "Error from p10_smp_link_firs when masking firs for all links"); } } for (auto l_iohs : l_iohs_targets) { fapi2::ATTR_PROC_FABRIC_LINK_ACTIVE_Type l_fabric_link_active; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_LINK_ACTIVE, l_iohs, l_fabric_link_active), "Error from FAPI_ATTR_GET (ATTR_PROC_FABRIC_LINK_ACTIVE)"); if(l_fabric_link_active == fapi2::ENUM_ATTR_PROC_FABRIC_LINK_ACTIVE_TRUE) { fapi2::ATTR_IOHS_DRAWER_INTERCONNECT_Type l_drawer_interconnect; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IOHS_DRAWER_INTERCONNECT, l_iohs, l_drawer_interconnect), "Error from FAPI_ATTR_GET (ATTR_IOHS_DRAWER_INTERCONNECT)"); if((i_config_intranode && (l_drawer_interconnect == fapi2::ENUM_ATTR_IOHS_DRAWER_INTERCONNECT_FALSE)) || (i_config_internode && (l_drawer_interconnect == fapi2::ENUM_ATTR_IOHS_DRAWER_INTERCONNECT_TRUE))) { auto l_pauc = l_iohs.getParent<fapi2::TARGET_TYPE_PAUC>(); fapi2::ATTR_IOHS_LINK_TRAIN_Type l_link_train; sublink_t sublink_opt; // apply FBC TL scom initfile fapi2::toString(l_pauc, l_tgt_str, sizeof(l_tgt_str)); FAPI_DBG("Invoking p10.fbc.ptl.scom.initfile on target %s...", l_tgt_str); FAPI_EXEC_HWP(l_rc, p10_fbc_ptl_scom, l_pauc, i_target, FAPI_SYSTEM); FAPI_TRY(l_rc, "Error from p10_fbc_ptl_scom"); // apply FBC DL scom initfile fapi2::toString(l_iohs, l_tgt_str, sizeof(l_tgt_str)); FAPI_DBG("Invoking p10.fbc.dlp.scom.initfile on target %s...", l_tgt_str); FAPI_EXEC_HWP(l_rc, p10_fbc_dlp_scom, l_iohs, i_target, FAPI_SYSTEM); FAPI_TRY(l_rc, "Error from p10_fbc_dlp_scom"); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IOHS_LINK_TRAIN, l_iohs, l_link_train), "Error from FAPI_ATTR_GET (ATTR_IOHS_LINK_TRAIN)"); switch(l_link_train) { case fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_BOTH: sublink_opt = sublink_t::BOTH; break; case fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_EVEN_ONLY: sublink_opt = sublink_t::EVEN; break; case fapi2::ENUM_ATTR_IOHS_LINK_TRAIN_ODD_ONLY: sublink_opt = sublink_t::ODD; break; default: sublink_opt = sublink_t::NONE; break; } // setup and unmask TL/DL FIRs FAPI_TRY(p10_smp_link_firs(l_iohs, sublink_opt, action_t::RUNTIME), "Error from p10_smp_link_firs when configuring for runtime operations"); } } else { // mask TL/DL FIRs for links that are not configured for smp operations if (i_config_intranode) { FAPI_TRY(p10_smp_link_firs(l_iohs, sublink_t::BOTH, action_t::INACTIVE), "Error from p10_smp_link_firs when configuring both sublinks for inactive operations"); } } } fapi_try_exit: FAPI_DBG("End"); return fapi2::current_err; } <|endoftext|>
<commit_before>/* * Copyright 2012 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "temperatureFormats.h" #include <string.h> #include <Arduino.h> // uses constrain function from Arduino.h #include <limits.h> #include "TempControl.h" // result can have maximum length of : sign + 3 digits integer part + point + 3 digits fraction part + '\0' = 9 bytes; // only 1, 2 or 3 decimals allowed. // returns pointer to the string // fixed7_23 is used to prevent overflow char * tempToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(rawValue == INT_MIN){ strcpy_P(s, PSTR("null")); return s; } if(tempControl.cc.tempFormat == 'F'){ rawValue = (rawValue * 9) / 5 + (32 << 9); // convert to Fahrenheit first } return fixedPointToString(s, rawValue, numDecimals, maxLength); } char * fixedPointToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(rawValue < 0l){ s[0] = '-'; rawValue = -rawValue; } else{ s[0] = ' '; } int intPart = rawValue >> 9; uint16_t fracPart; if(numDecimals == 1){ fracPart = ((rawValue & 0x01FF) * 10 + 256) >> 9; // add 256 for rounding if(fracPart >= 10){ intPart++; fracPart = 0; // has already overflowed into integer part. } snprintf_P(&s[1], maxLength-1, PSTR("%d.%01d"), intPart, fracPart); } else if(numDecimals == 2){ fracPart = ((rawValue & 0x01FF) * 100 + 256) >> 9; if(fracPart >= 100){ intPart++; fracPart = 0; // has already overflowed into integer part. } snprintf_P(&s[1], maxLength-1, PSTR("%d.%02d"), intPart, fracPart); } else{ fracPart = ((rawValue & 0x01FF) * 1000 + 256) >> 9; if(fracPart>=1000){ intPart++; fracPart = 0; // has already overflowed into integer part. } snprintf_P(&s[1], maxLength-1, PSTR("%d.%03d"), intPart, fracPart); } return s; } fixed7_9 stringToTemp(char * numberString){ fixed23_9 rawTemp = stringToFixedPoint(numberString); if(tempControl.cc.tempFormat == 'F'){ rawTemp = ((rawTemp - (32 << 9)) * 5) / 9; // convert to store as Celsius } return constrain(rawTemp, INT_MIN, INT_MAX); } fixed23_9 stringToFixedPoint(char * numberString){ // receive new temperature as null terminated string: "19.20" fixed23_9 intPart = 0; fixed23_9 fracPart = 0; char * fractPtr = 0; //pointer to the point in the string char sign = 1; if(numberString[0] == '-'){ numberString++; sign = -1; // by processing the sign here, we don't have to include strtol } // find the point in the string to split in the integer part and the fraction part fractPtr = strchrnul(numberString, '.'); // returns pointer to the point. intPart = strtoul(numberString, NULL, 10); if(fractPtr != 0){ // decimal point was found char * fractEndPtr; fractPtr++; // add 1 to pointer to skip point fracPart = strtoul(fractPtr,&fractEndPtr, 10); uint8_t numDecimals = fractEndPtr - fractPtr; fracPart = fracPart << 9; // 9 bits for fraction part while(numDecimals > 0){ fracPart = (fracPart + 5) / 10; // divide by 10 rounded numDecimals--; } } return sign * ((intPart<<9) +fracPart); } char * tempDiffToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(tempControl.cc.tempFormat == 'F'){ rawValue = (rawValue * 9) / 5; // convert to Fahrenheit first } return fixedPointToString(s, rawValue, numDecimals, maxLength); } fixed7_9 stringToTempDiff(char * numberString){ fixed23_9 rawTempDiff = stringToFixedPoint(numberString); if(tempControl.cc.tempFormat == 'F'){ rawTempDiff = (rawTempDiff * 5) / 9; // convert to store as Celsius } return constrain(rawTempDiff, INT_MIN, INT_MAX); } int fixedToTenths(fixed23_9 temperature){ if(tempControl.cc.tempFormat == 'F'){ temperature = temperature*9/5 + 32*512; // Convert to Fahrenheit fixed point first } return (int) ((10 * temperature + 256) / 512); // return rounded result in tenth of degrees } fixed7_9 tenthsToFixed(int temperature){ if(tempControl.cc.tempFormat == 'F'){ return (( ( (fixed23_9) temperature - 320) * 512 * 5) / 9 + 5) / 10; // convert to Celsius and return rounded result in fixed point } else{ return ((fixed23_9) temperature * 512 + 5) / 10; // return rounded result in fixed point } }<commit_msg>Fix: negative temperatures where not processed correctly.<commit_after>/* * Copyright 2012 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "temperatureFormats.h" #include <string.h> #include <Arduino.h> // uses constrain function from Arduino.h #include <limits.h> #include "TempControl.h" // result can have maximum length of : sign + 3 digits integer part + point + 3 digits fraction part + '\0' = 9 bytes; // only 1, 2 or 3 decimals allowed. // returns pointer to the string // fixed7_23 is used to prevent overflow char * tempToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(rawValue == INT_MIN){ strcpy_P(s, PSTR("null")); return s; } if(tempControl.cc.tempFormat == 'F'){ rawValue = (rawValue * 9) / 5 + (32 << 9); // convert to Fahrenheit first } return fixedPointToString(s, rawValue, numDecimals, maxLength); } char * fixedPointToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(rawValue < 0l){ s[0] = '-'; rawValue = -rawValue; } else{ s[0] = ' '; } int intPart = rawValue >> 9; uint16_t fracPart; if(numDecimals == 1){ fracPart = ((rawValue & 0x01FF) * 10 + 256) >> 9; // add 256 for rounding if(fracPart >= 10){ intPart++; fracPart = 0; // has already overflowed into integer part. } snprintf_P(&s[1], maxLength-1, PSTR("%d.%01d"), intPart, fracPart); } else if(numDecimals == 2){ fracPart = ((rawValue & 0x01FF) * 100 + 256) >> 9; if(fracPart >= 100){ intPart++; fracPart = 0; // has already overflowed into integer part. } snprintf_P(&s[1], maxLength-1, PSTR("%d.%02d"), intPart, fracPart); } else{ fracPart = ((rawValue & 0x01FF) * 1000 + 256) >> 9; if(fracPart>=1000){ intPart++; fracPart = 0; // has already overflowed into integer part. } snprintf_P(&s[1], maxLength-1, PSTR("%d.%03d"), intPart, fracPart); } return s; } fixed7_9 stringToTemp(char * numberString){ fixed23_9 rawTemp = stringToFixedPoint(numberString); if(tempControl.cc.tempFormat == 'F'){ rawTemp = ((rawTemp - (32 << 9)) * 5) / 9; // convert to store as Celsius } return constrain(rawTemp, INT_MIN, INT_MAX); } fixed23_9 stringToFixedPoint(char * numberString){ // receive new temperature as null terminated string: "19.20" fixed23_9 intPart = 0; fixed23_9 fracPart = 0; char * fractPtr = 0; //pointer to the point in the string bool negative = 0; if(numberString[0] == '-'){ numberString++; negative = true; // by processing the sign here, we don't have to include strtol } // find the point in the string to split in the integer part and the fraction part fractPtr = strchrnul(numberString, '.'); // returns pointer to the point. intPart = strtoul(numberString, NULL, 10); if(fractPtr != 0){ // decimal point was found char * fractEndPtr; fractPtr++; // add 1 to pointer to skip point fracPart = strtoul(fractPtr,&fractEndPtr, 10); uint8_t numDecimals = fractEndPtr - fractPtr; fracPart = fracPart << 9; // 9 bits for fraction part while(numDecimals > 0){ fracPart = (fracPart + 5) / 10; // divide by 10 rounded numDecimals--; } } fixed23_9 absVal = ((intPart<<9) +fracPart); return negative ? -absVal:absVal; } char * tempDiffToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(tempControl.cc.tempFormat == 'F'){ rawValue = (rawValue * 9) / 5; // convert to Fahrenheit first } return fixedPointToString(s, rawValue, numDecimals, maxLength); } fixed7_9 stringToTempDiff(char * numberString){ fixed23_9 rawTempDiff = stringToFixedPoint(numberString); if(tempControl.cc.tempFormat == 'F'){ rawTempDiff = (rawTempDiff * 5) / 9; // convert to store as Celsius } return constrain(rawTempDiff, INT_MIN, INT_MAX); } int fixedToTenths(fixed23_9 temperature){ if(tempControl.cc.tempFormat == 'F'){ temperature = temperature*9/5 + 32*512; // Convert to Fahrenheit fixed point first } return (int) ((10 * temperature + 256) / 512); // return rounded result in tenth of degrees } fixed7_9 tenthsToFixed(int temperature){ if(tempControl.cc.tempFormat == 'F'){ return (( ( (fixed23_9) temperature - 320) * 512 * 5) / 9 + 5) / 10; // convert to Celsius and return rounded result in fixed point } else{ return ((fixed23_9) temperature * 512 + 5) / 10; // return rounded result in fixed point } }<|endoftext|>
<commit_before>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Dialect/HAL/Target/ROCM/ROCMTarget.h" #include <mutex> #include "iree/compiler/Codegen/Dialect/IREECodegenDialect.h" #include "iree/compiler/Codegen/Passes.h" #include "iree/compiler/Dialect/HAL/Target/TargetRegistry.h" #include "iree/compiler/Utils/FlatbufferUtils.h" #include "iree/schemas/rocm_executable_def_builder.h" #include "llvm/IR/Constants.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/MC/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Target/TargetMachine.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Pass/PassManager.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" #include "mlir/Target/LLVMIR/Dialect/ROCDL/ROCDLToLLVMIRTranslation.h" #include "mlir/Target/LLVMIR/Export.h" static llvm::cl::opt<std::string> clROCMTargetChip( "iree-rocm-target-chip", llvm::cl::desc("ROCm target Chip"), llvm::cl::init("gfx908")); static llvm::cl::opt<bool> clROCMLinkBC( "iree-rocm-link-bc", llvm::cl::desc("Whether to try Linking to AMD Bitcodes"), llvm::cl::init(false)); static llvm::cl::opt<std::string> clROCMBitcodeDir( "iree-rocm-bc-dir", llvm::cl::desc("Directory of ROCM Bitcode"), llvm::cl::init("/opt/rocm/amdgcn/bitcode")); namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { static std::string translateModuleToISA(llvm::Module &module, llvm::TargetMachine &targetMachine) { std::string targetISA; { llvm::raw_string_ostream stream(targetISA); llvm::buffer_ostream pstream(stream); llvm::legacy::PassManager codegenPasses; targetMachine.addPassesToEmitFile(codegenPasses, pstream, nullptr, llvm::CGFT_ObjectFile); codegenPasses.run(module); } return targetISA; } class ROCMTargetBackend final : public TargetBackend { public: std::string name() const override { return "rocm"; } void getDependentDialects(DialectRegistry &registry) const override { mlir::registerLLVMDialectTranslation(registry); mlir::registerROCDLDialectTranslation(registry); registry.insert<IREE::Codegen::IREECodegenDialect>(); } IREE::HAL::DeviceTargetAttr getDefaultDeviceTarget( MLIRContext *context) const override { Builder b(context); SmallVector<NamedAttribute> configItems; configItems.emplace_back(b.getStringAttr("executable_targets"), getExecutableTargets(context)); auto configAttr = b.getDictionaryAttr(configItems); return IREE::HAL::DeviceTargetAttr::get( context, b.getStringAttr(deviceID()), configAttr); } void buildTranslationPassPipeline(OpPassManager &passManager) override { buildLLVMGPUTransformPassPipeline(passManager, true); } LogicalResult serializeExecutable(const SerializationOptions &options, IREE::HAL::ExecutableVariantOp variantOp, OpBuilder &executableBuilder) override { // Perform the translation in a separate context to avoid any // multi-threading issues. llvm::LLVMContext context; // We name our files after the executable name so that they are easy to // track both during compilation (logs/artifacts/etc), as outputs (final // intermediate code/binary files), and at runtime (loaded // libraries/symbols/etc). auto libraryName = variantOp->getParentOfType<IREE::HAL::ExecutableOp>().getName().str(); ModuleOp innerModuleOp = variantOp.getInnerModule(); // Remove all the functions that are not part of the ROCM kernel. // TODO: Find a better solution to handle this. auto illegalFuncOps = llvm::to_vector<4>(innerModuleOp.getOps<func::FuncOp>()); for (auto funcOp : illegalFuncOps) { funcOp.erase(); } auto llvmModule = mlir::translateModuleToLLVMIR(innerModuleOp, context, libraryName); if (!llvmModule) { return variantOp.emitError() << "failed to translate the MLIR LLVM " "dialect to the native llvm::Module"; } // Collect all the entry point names. llvm::StringMap<IREE::HAL::ExecutableEntryPointOp> entryPointOps; for (auto op : variantOp.getOps<IREE::HAL::ExecutableEntryPointOp>()) { entryPointOps[op.sym_name()] = op; } std::vector<std::array<int32_t, 3>> workgroupSizes; for (auto func : innerModuleOp.getOps<LLVM::LLVMFuncOp>()) { int32_t flatWgSize = 1; auto *llvmFunc = llvmModule->getFunction(func.getName()); if (llvmFunc->isDeclaration()) continue; std::array<int32_t, 3> workgroup_size; auto entryPointOp = entryPointOps[func.getName()]; if (Optional<ArrayAttr> workgroupSizeAttr = entryPointOp.workgroup_size()) { for (auto it : llvm::enumerate(workgroupSizeAttr.getValue())) { workgroup_size[it.index()] = it.value().cast<IntegerAttr>().getInt(); flatWgSize *= it.value().cast<IntegerAttr>().getInt(); } } else { workgroup_size = {1, 1, 1}; } workgroupSizes.push_back(workgroup_size); // For GPU kernels, // 1. Insert AMDGPU_KERNEL calling convention. // 2. Insert amdgpu-flat-workgroup-size(1, 256) attribute. // 3. Insert amdgpu-implicitarg-num-bytes=56 (which must be set on OpenCL // and HIP kernels per Clang) llvmFunc->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL); std::string wgSizeRange = std::string("1, ") + std::to_string(flatWgSize); llvmFunc->addFnAttr("amdgpu-flat-work-group-size", wgSizeRange); } std::unique_ptr<llvm::TargetMachine> targetMachine; { llvm::Triple triple("amdgcn--amdhsa-amdgiz"); std::string targetChip = clROCMTargetChip; std::string error; const llvm::Target *target = llvm::TargetRegistry::lookupTarget("", triple, error); if (target == nullptr) { return variantOp.emitError() << "cannot initialize target triple"; } targetMachine.reset( target->createTargetMachine(triple.str(), targetChip, {}, {}, {})); if (targetMachine == nullptr) { return variantOp.emitError() << "cannot initialize target machine"; } } llvmModule->setDataLayout(targetMachine->createDataLayout()); iree_compiler::FlatbufferBuilder builder; iree_ROCMExecutableDef_start_as_root(builder); // Link module to Device Library if (clROCMLinkBC) { LinkROCDLIfNecessary(llvmModule.get(), clROCMTargetChip, clROCMBitcodeDir); } // Serialize hsaco kernel into the binary that we will embed in the // final flatbuffer. std::string targetISA = translateModuleToISA(*llvmModule, *targetMachine); std::string targetHSACO = createHsaco(targetISA, libraryName); if (!options.dumpBinariesPath.empty()) { dumpDataToPath(options.dumpBinariesPath, options.dumpBaseName, variantOp.getName(), ".hsaco", targetHSACO); } auto hsacoRef = flatbuffers_uint8_vec_create( builder, reinterpret_cast<const uint8_t *>(targetHSACO.c_str()), targetHSACO.size()); auto entryPointNames = llvm::to_vector<8>(llvm::map_range( variantOp.getBlock() .getOps<iree_compiler::IREE::HAL::ExecutableEntryPointOp>(), [&](auto op) { return op.getName(); })); auto entryPointsRef = builder.createStringVec(entryPointNames); iree_ROCMBlockSizeDef_vec_start(builder); auto blockSizes = workgroupSizes.begin(); for (int i = 0, e = entryPointNames.size(); i < e; ++i) { iree_ROCMBlockSizeDef_vec_push_create(builder, (*blockSizes)[0], (*blockSizes)[1], (*blockSizes)[2]); ++blockSizes; } auto blockSizesRef = iree_ROCMBlockSizeDef_vec_end(builder); iree_ROCMExecutableDef_entry_points_add(builder, entryPointsRef); iree_ROCMExecutableDef_block_sizes_add(builder, blockSizesRef); iree_ROCMExecutableDef_hsaco_image_add(builder, hsacoRef); iree_ROCMExecutableDef_end_as_root(builder); // Add the binary data to the target executable. executableBuilder.create<iree_compiler::IREE::HAL::ExecutableBinaryOp>( variantOp.getLoc(), variantOp.sym_name(), variantOp.target().getFormat(), builder.getBufferAttr(executableBuilder.getContext())); return success(); } private: ArrayAttr getExecutableTargets(MLIRContext *context) const { SmallVector<Attribute> targetAttrs; // If we had multiple target environments we would generate one target attr // per environment, with each setting its own environment attribute. targetAttrs.push_back(getExecutableTarget(context)); return ArrayAttr::get(context, targetAttrs); } IREE::HAL::ExecutableTargetAttr getExecutableTarget( MLIRContext *context) const { Builder b(context); SmallVector<NamedAttribute> configItems; auto configAttr = b.getDictionaryAttr(configItems); return IREE::HAL::ExecutableTargetAttr::get( context, b.getStringAttr("rocm"), b.getStringAttr("rocm-hsaco-fb"), configAttr); } }; void registerROCMTargetBackends() { // #hal.device.target<"rocm", ... // #hal.executable.target<"rocm", ... static iree_compiler::IREE::HAL::TargetBackendRegistration registration( "rocm", [=]() { LLVMInitializeAMDGPUTarget(); LLVMInitializeAMDGPUTargetMC(); LLVMInitializeAMDGPUTargetInfo(); LLVMInitializeAMDGPUAsmPrinter(); return std::make_shared<ROCMTargetBackend>(); }); } } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir <commit_msg>[ROCM] Add iree-hal-rocm-dump-isa flag (#9141)<commit_after>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Dialect/HAL/Target/ROCM/ROCMTarget.h" #include <mutex> #include "iree/compiler/Codegen/Dialect/IREECodegenDialect.h" #include "iree/compiler/Codegen/Passes.h" #include "iree/compiler/Dialect/HAL/Target/TargetRegistry.h" #include "iree/compiler/Utils/FlatbufferUtils.h" #include "iree/schemas/rocm_executable_def_builder.h" #include "llvm/IR/Constants.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/MC/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Target/TargetMachine.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Pass/PassManager.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" #include "mlir/Target/LLVMIR/Dialect/ROCDL/ROCDLToLLVMIRTranslation.h" #include "mlir/Target/LLVMIR/Export.h" static llvm::cl::opt<std::string> clROCMTargetChip( "iree-rocm-target-chip", llvm::cl::desc("ROCm target Chip"), llvm::cl::init("gfx908")); static llvm::cl::opt<bool> clROCMLinkBC( "iree-rocm-link-bc", llvm::cl::desc("Whether to try Linking to AMD Bitcodes"), llvm::cl::init(false)); static llvm::cl::opt<std::string> clROCMBitcodeDir( "iree-rocm-bc-dir", llvm::cl::desc("Directory of ROCM Bitcode"), llvm::cl::init("/opt/rocm/amdgcn/bitcode")); namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { static std::string translateModuleToObj(llvm::Module &module, llvm::TargetMachine &targetMachine) { std::string targetObj; { llvm::raw_string_ostream stream(targetObj); llvm::buffer_ostream pstream(stream); llvm::legacy::PassManager codegenPasses; targetMachine.addPassesToEmitFile(codegenPasses, pstream, nullptr, llvm::CGFT_ObjectFile); codegenPasses.run(module); } return targetObj; } static std::string translateModuleToISA(llvm::Module &module, llvm::TargetMachine &targetMachine) { std::string targetISA; { llvm::raw_string_ostream stream(targetISA); llvm::buffer_ostream pstream(stream); llvm::legacy::PassManager codegenPasses; targetMachine.addPassesToEmitFile(codegenPasses, pstream, nullptr, llvm::CGFT_AssemblyFile); codegenPasses.run(module); } return targetISA; } class ROCMTargetBackend final : public TargetBackend { public: std::string name() const override { return "rocm"; } void getDependentDialects(DialectRegistry &registry) const override { mlir::registerLLVMDialectTranslation(registry); mlir::registerROCDLDialectTranslation(registry); registry.insert<IREE::Codegen::IREECodegenDialect>(); } IREE::HAL::DeviceTargetAttr getDefaultDeviceTarget( MLIRContext *context) const override { Builder b(context); SmallVector<NamedAttribute> configItems; configItems.emplace_back(b.getStringAttr("executable_targets"), getExecutableTargets(context)); auto configAttr = b.getDictionaryAttr(configItems); return IREE::HAL::DeviceTargetAttr::get( context, b.getStringAttr(deviceID()), configAttr); } void buildTranslationPassPipeline(OpPassManager &passManager) override { buildLLVMGPUTransformPassPipeline(passManager, true); } LogicalResult serializeExecutable(const SerializationOptions &options, IREE::HAL::ExecutableVariantOp variantOp, OpBuilder &executableBuilder) override { // Perform the translation in a separate context to avoid any // multi-threading issues. llvm::LLVMContext context; // We name our files after the executable name so that they are easy to // track both during compilation (logs/artifacts/etc), as outputs (final // intermediate code/binary files), and at runtime (loaded // libraries/symbols/etc). auto libraryName = variantOp->getParentOfType<IREE::HAL::ExecutableOp>().getName().str(); ModuleOp innerModuleOp = variantOp.getInnerModule(); // Remove all the functions that are not part of the ROCM kernel. // TODO: Find a better solution to handle this. auto illegalFuncOps = llvm::to_vector<4>(innerModuleOp.getOps<func::FuncOp>()); for (auto funcOp : illegalFuncOps) { funcOp.erase(); } auto llvmModule = mlir::translateModuleToLLVMIR(innerModuleOp, context, libraryName); if (!llvmModule) { return variantOp.emitError() << "failed to translate the MLIR LLVM " "dialect to the native llvm::Module"; } // Collect all the entry point names. llvm::StringMap<IREE::HAL::ExecutableEntryPointOp> entryPointOps; for (auto op : variantOp.getOps<IREE::HAL::ExecutableEntryPointOp>()) { entryPointOps[op.sym_name()] = op; } std::vector<std::array<int32_t, 3>> workgroupSizes; for (auto func : innerModuleOp.getOps<LLVM::LLVMFuncOp>()) { int32_t flatWgSize = 1; auto *llvmFunc = llvmModule->getFunction(func.getName()); if (llvmFunc->isDeclaration()) continue; std::array<int32_t, 3> workgroup_size; auto entryPointOp = entryPointOps[func.getName()]; if (Optional<ArrayAttr> workgroupSizeAttr = entryPointOp.workgroup_size()) { for (auto it : llvm::enumerate(workgroupSizeAttr.getValue())) { workgroup_size[it.index()] = it.value().cast<IntegerAttr>().getInt(); flatWgSize *= it.value().cast<IntegerAttr>().getInt(); } } else { workgroup_size = {1, 1, 1}; } workgroupSizes.push_back(workgroup_size); // For GPU kernels, // 1. Insert AMDGPU_KERNEL calling convention. // 2. Insert amdgpu-flat-workgroup-size(1, 256) attribute. // 3. Insert amdgpu-implicitarg-num-bytes=56 (which must be set on OpenCL // and HIP kernels per Clang) llvmFunc->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL); std::string wgSizeRange = std::string("1, ") + std::to_string(flatWgSize); llvmFunc->addFnAttr("amdgpu-flat-work-group-size", wgSizeRange); } std::unique_ptr<llvm::TargetMachine> targetMachine; { llvm::Triple triple("amdgcn--amdhsa-amdgiz"); std::string targetChip = clROCMTargetChip; std::string error; const llvm::Target *target = llvm::TargetRegistry::lookupTarget("", triple, error); if (target == nullptr) { return variantOp.emitError() << "cannot initialize target triple"; } targetMachine.reset( target->createTargetMachine(triple.str(), targetChip, {}, {}, {})); if (targetMachine == nullptr) { return variantOp.emitError() << "cannot initialize target machine"; } } llvmModule->setDataLayout(targetMachine->createDataLayout()); iree_compiler::FlatbufferBuilder builder; iree_ROCMExecutableDef_start_as_root(builder); // Link module to Device Library if (clROCMLinkBC) { LinkROCDLIfNecessary(llvmModule.get(), clROCMTargetChip, clROCMBitcodeDir); } // Serialize hsaco kernel into the binary that we will embed in the // final flatbuffer. std::string targetObj = translateModuleToObj(*llvmModule, *targetMachine); std::string targetHSACO = createHsaco(targetObj, libraryName); if (!options.dumpBinariesPath.empty()) { dumpDataToPath(options.dumpBinariesPath, options.dumpBaseName, variantOp.getName(), ".hsaco", targetHSACO); } auto hsacoRef = flatbuffers_uint8_vec_create( builder, reinterpret_cast<const uint8_t *>(targetHSACO.c_str()), targetHSACO.size()); auto entryPointNames = llvm::to_vector<8>(llvm::map_range( variantOp.getBlock() .getOps<iree_compiler::IREE::HAL::ExecutableEntryPointOp>(), [&](auto op) { return op.getName(); })); auto entryPointsRef = builder.createStringVec(entryPointNames); iree_ROCMBlockSizeDef_vec_start(builder); auto blockSizes = workgroupSizes.begin(); for (int i = 0, e = entryPointNames.size(); i < e; ++i) { iree_ROCMBlockSizeDef_vec_push_create(builder, (*blockSizes)[0], (*blockSizes)[1], (*blockSizes)[2]); ++blockSizes; } auto blockSizesRef = iree_ROCMBlockSizeDef_vec_end(builder); iree_ROCMExecutableDef_entry_points_add(builder, entryPointsRef); iree_ROCMExecutableDef_block_sizes_add(builder, blockSizesRef); iree_ROCMExecutableDef_hsaco_image_add(builder, hsacoRef); iree_ROCMExecutableDef_end_as_root(builder); // Add the binary data to the target executable. executableBuilder.create<iree_compiler::IREE::HAL::ExecutableBinaryOp>( variantOp.getLoc(), variantOp.sym_name(), variantOp.target().getFormat(), builder.getBufferAttr(executableBuilder.getContext())); if (!options.dumpIntermediatesPath.empty()) { std::string targetISA = translateModuleToISA(*llvmModule, *targetMachine); dumpDataToPath(options.dumpIntermediatesPath, options.dumpBaseName, variantOp.getName(), ".rocmasm", targetISA); } return success(); } private: ArrayAttr getExecutableTargets(MLIRContext *context) const { SmallVector<Attribute> targetAttrs; // If we had multiple target environments we would generate one target attr // per environment, with each setting its own environment attribute. targetAttrs.push_back(getExecutableTarget(context)); return ArrayAttr::get(context, targetAttrs); } IREE::HAL::ExecutableTargetAttr getExecutableTarget( MLIRContext *context) const { Builder b(context); SmallVector<NamedAttribute> configItems; auto configAttr = b.getDictionaryAttr(configItems); return IREE::HAL::ExecutableTargetAttr::get( context, b.getStringAttr("rocm"), b.getStringAttr("rocm-hsaco-fb"), configAttr); } }; void registerROCMTargetBackends() { // #hal.device.target<"rocm", ... // #hal.executable.target<"rocm", ... static iree_compiler::IREE::HAL::TargetBackendRegistration registration( "rocm", [=]() { LLVMInitializeAMDGPUTarget(); LLVMInitializeAMDGPUTargetMC(); LLVMInitializeAMDGPUTargetInfo(); LLVMInitializeAMDGPUAsmPrinter(); return std::make_shared<ROCMTargetBackend>(); }); } } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before> #ifndef OMP_OMP_HPP #define OMP_OMP_HPP #include <cstdint> #include <functional> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <cassert> #include <iterator> #include <algorithm> namespace omp { struct iteration_context { std::size_t thread_index; std::size_t index; }; namespace internal { extern std::mutex global_mutex; extern const unsigned default_num_threads; inline std::uint64_t ceil_divide(std::uint64_t x, std::uint64_t y) { return (x + y - 1) / y; } class thread_pool { public: thread_pool(const std::function<void(std::size_t thread_idx)>& fn, unsigned num_threads = 0) : num_threads_(num_threads ? num_threads : default_num_threads) { threads_.reserve(num_threads - 1); for (unsigned i = 0; i < (num_threads_ - 1); ++i) threads_.emplace_back(fn, i); fn(num_threads_ - 1); for (auto it = threads_.begin(); it != threads_.end(); ++it) it->join(); } private: const std::size_t num_threads_; std::vector<std::thread> threads_; }; class thread_pool2 { private: enum class state { shutdown = 0, run, running, sleep }; std::vector<std::thread> threads_; std::vector<state> states_; std::mutex mtx_; std::condition_variable cv_; std::function<void(std::size_t)> fn_; std::size_t sleeping_counter_; public: thread_pool2(std::size_t num_threads = 0) : states_(num_threads ? num_threads - 1 : default_num_threads - 1, state::sleep), sleeping_counter_(states_.size()) { threads_.reserve(states_.size()); for (std::size_t i = 0; i < states_.size(); ++i) { threads_.emplace_back(std::bind(&thread_pool2::routine, this, i)); } } ~thread_pool2() { //std::cerr << "Destroying thread pool ..." << std::endl; { std::unique_lock<std::mutex> lk(mtx_); std::fill(states_.begin(), states_.end(), state::shutdown); } cv_.notify_all(); for (auto& t : threads_) t.join(); //std::cerr << "Done destroying thread pool ..." << std::endl; } std::size_t thread_count() const { return threads_.size() + 1; } void routine(std::size_t thread_idx) { while (true) { { std::unique_lock<std::mutex> lk(mtx_); if (states_[thread_idx] == state::shutdown) break; if (states_[thread_idx] == state::running) { states_[thread_idx] = state::sleep; ++sleeping_counter_; cv_.notify_all(); } cv_.wait(lk, [this, thread_idx] { return states_[thread_idx] != state::sleep; }); if (states_[thread_idx] == state::shutdown) break; states_[thread_idx] = state::running; } if (fn_) { fn_(thread_idx); } } } //template <typename Fn> void operator()(std::function<void(std::size_t)>&& fn) { fn_ = std::move(fn); { std::unique_lock<std::mutex> lk(mtx_); std::fill(states_.begin(), states_.end(), state::run); sleeping_counter_ = 0; } cv_.notify_all(); if (fn_) { fn_(states_.size()); } { // Wait for child threads to complete. std::unique_lock<std::mutex> lk(mtx_); cv_.wait(lk, [this] { return sleeping_counter_ == states_.size(); }); // std::count(states_.begin(), states_.end(), state::sleep) == states_.size(); }); } fn_ = nullptr; } }; template<typename Iter> class dynamic_iterator_thread_pool { public: dynamic_iterator_thread_pool(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference, const iteration_context&)>& fn, unsigned num_threads) : fn_(fn), cur_(begin), end_(end), index_(0), chunk_size_(chunk_size ? chunk_size : 1), num_threads_(num_threads ? num_threads : default_num_threads) { threads_.reserve(num_threads_ - 1); for (unsigned i = 0; i < (num_threads_ - 1); ++i) threads_.emplace_back(std::bind(&dynamic_iterator_thread_pool::routine, this, i)); this->routine(num_threads_ - 1); for (auto it = threads_.begin(); it != threads_.end(); ++it) it->join(); } private: std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_; std::vector<std::thread> threads_; Iter cur_; const Iter end_; std::size_t index_; std::mutex mtx_; const std::size_t chunk_size_; const std::size_t num_threads_; void routine(std::size_t thread_index) { bool done = false; while (!done) { std::vector<Iter> chunk(chunk_size_); std::unique_lock<std::mutex> lk(mtx_); std::size_t index = index_; for (std::size_t chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset) { ++index_; chunk[chunk_offset] = cur_; if (cur_ != end_) ++cur_; } lk.unlock(); for (std::size_t chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset) { if (chunk[chunk_offset] == end_) { done = true; } else { fn_(*chunk[chunk_offset], {thread_index, index + chunk_offset}); //fn_ ? fn_(*it, i) : void(); } } } } }; template<typename Iter> class static_iterator_thread_pool { public: static_iterator_thread_pool(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference,const iteration_context&)>& fn, unsigned num_threads = 0) : fn_(fn), num_threads_(num_threads ? num_threads : default_num_threads), beg_(begin), end_(end), total_elements_(std::distance(beg_, end_)), chunk_size_(chunk_size ? chunk_size : static_cast<std::size_t>(total_elements_) / num_threads_) { threads_.reserve(num_threads_ - 1); for (unsigned i = 0; i < (num_threads_ - 1); ++i) threads_.emplace_back(std::bind(&static_iterator_thread_pool::routine, this, i)); this->routine(num_threads_ - 1); for (auto it = threads_.begin(); it != threads_.end(); ++it) it->join(); } private: std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_; const std::size_t num_threads_; std::vector<std::thread> threads_; const Iter beg_; const Iter end_; long total_elements_; const std::size_t chunk_size_; public: void routine(std::size_t thread_index) { auto cur = beg_; std::advance(cur, thread_index * chunk_size_); for (std::size_t index = (thread_index * chunk_size_); index < total_elements_; index += (chunk_size_ * num_threads_ - chunk_size_), std::advance(cur, chunk_size_ * num_threads_ - chunk_size_)) { for (std::size_t chunk_offset = 0; chunk_offset < chunk_size_ && index < total_elements_; ++chunk_offset) { assert(cur != end_); fn_(*cur, {thread_index,index}); //fn_ ? fn_(*it, i) : void(); ++cur; ++index; } } } }; template<typename Iter> class static_iterator_functor { public: static_iterator_functor(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference,const iteration_context&)>& fn, unsigned num_threads) : fn_(fn), num_threads_(num_threads ? num_threads : default_num_threads), beg_(begin), end_(end), total_elements_(std::distance(beg_, end_)), chunk_size_(chunk_size ? chunk_size : ceil_divide(total_elements_, num_threads_)) { //assert(chunk_size_ > 0); // threads_.reserve(num_threads_ - 1); // for (unsigned i = 0; i < (num_threads_ - 1); ++i) // threads_.emplace_back(std::bind(&static_iterator_thread_pool::routine, this, i)); // this->routine(num_threads_ - 1); // // for (auto it = threads_.begin(); it != threads_.end(); ++it) // it->join(); } private: std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_; const std::size_t num_threads_; const Iter beg_; const Iter end_; std::int64_t total_elements_; const std::int64_t chunk_size_; public: void operator()(std::size_t thread_index) { if (total_elements_ > 0) { auto cur = beg_; std::advance(cur, thread_index * chunk_size_); for (std::size_t index = (thread_index * chunk_size_); index < total_elements_; index += (chunk_size_ * num_threads_ - chunk_size_), std::advance(cur, chunk_size_ * num_threads_ - chunk_size_)) { std::size_t end_off = index + chunk_size_; for (; index < end_off && index < total_elements_; ++index,++cur) { assert(cur != end_); fn_(*cur, {thread_index, index}); //fn_ ? fn_(*it, i) : void(); } } } } }; } class sequence_iterator { public: typedef sequence_iterator self_type; typedef int difference_type; typedef int value_type; typedef value_type& reference; typedef value_type* pointer; typedef std::random_access_iterator_tag iterator_category; sequence_iterator() : val_(0) {} sequence_iterator(value_type val) : val_(val) { } //reference operator [] (difference_type); bool operator < (const self_type& other) { return val_ < other.val_; } bool operator > (const self_type& other) { return val_ > other.val_; } bool operator <= (const self_type& other) { return val_ <= other.val_; } bool operator >= (const self_type& other) { return val_ >= other.val_; } self_type operator++() { self_type ret = *this; ++val_; return ret; } self_type operator--() { self_type ret = *this; --val_; return ret; } self_type& operator += (difference_type i) { val_ += i; return *this; } self_type& operator -= (difference_type i) { val_ -= i; return *this; } self_type operator + (difference_type i) { return self_type(val_ + i); } self_type operator - (difference_type i) { return self_type(val_ - i); } difference_type operator - (const self_type& other) { return val_ - other.val_; } void operator++(int) { ++val_; } void operator--(int) { --val_; } reference operator*() { return val_; } pointer operator->() { return &val_; } bool operator==(const self_type& rhs) const { return (val_ == rhs.val_); } bool operator!=(const self_type& rhs) const { return (val_ != rhs.val_); } private: value_type val_; }; class schedule { public: schedule(std::size_t chunk_size); std::size_t chunk_size() const; protected: std::size_t chunk_size_; }; class dynamic_schedule : public schedule { public: dynamic_schedule(std::size_t chunk_size = 0); }; class static_schedule : public schedule { public: static_schedule(std::size_t chunk_size = 0); }; void parallel(const std::function<void(std::size_t)>& operation, unsigned thread_cnt = 0); template <typename Iterator> void parallel_for(const dynamic_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0) { internal::dynamic_iterator_thread_pool<Iterator> pool(sched.chunk_size(), begin, end, operation, thread_cnt); } template <typename Iterator> void parallel_for(const static_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0) { internal::static_iterator_thread_pool<Iterator> pool(sched.chunk_size(), begin, end, operation, thread_cnt); } template <typename Iterator> void parallel_for_exp(const static_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, internal::thread_pool2& tp) { tp(internal::static_iterator_functor<Iterator>(sched.chunk_size(), begin, end, operation, tp.thread_count())); //std::bind(&internal::static_iterator_functor<Iterator>::routine, &static_fn, std::placeholders::_1)); } template <typename Iterator> void parallel_for(Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0) { parallel_for(static_schedule(), begin, end, operation, thread_cnt); } template <typename Handler> void critical(std::mutex& mtx, Handler fn) { std::lock_guard<std::mutex> lk(mtx); fn(); } template <typename Handler> void critical(Handler fn) { std::lock_guard<std::mutex> lk(internal::global_mutex); fn(); } } #endif //OMP_OMP_HPP <commit_msg>Fixes advancing iterator beyond end.<commit_after> #ifndef OMP_OMP_HPP #define OMP_OMP_HPP #include <cstdint> #include <functional> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <cassert> #include <iterator> #include <algorithm> namespace omp { struct iteration_context { std::size_t thread_index; std::size_t index; }; namespace internal { extern std::mutex global_mutex; extern const unsigned default_num_threads; inline std::uint64_t ceil_divide(std::uint64_t x, std::uint64_t y) { return (x + y - 1) / y; } class thread_pool { public: thread_pool(const std::function<void(std::size_t thread_idx)>& fn, unsigned num_threads = 0) : num_threads_(num_threads ? num_threads : default_num_threads) { threads_.reserve(num_threads - 1); for (unsigned i = 0; i < (num_threads_ - 1); ++i) threads_.emplace_back(fn, i); fn(num_threads_ - 1); for (auto it = threads_.begin(); it != threads_.end(); ++it) it->join(); } private: const std::size_t num_threads_; std::vector<std::thread> threads_; }; class thread_pool2 { private: enum class state { shutdown = 0, run, running, sleep }; std::vector<std::thread> threads_; std::vector<state> states_; std::mutex mtx_; std::condition_variable cv_; std::function<void(std::size_t)> fn_; std::size_t sleeping_counter_; public: thread_pool2(std::size_t num_threads = 0) : states_(num_threads ? num_threads - 1 : default_num_threads - 1, state::sleep), sleeping_counter_(states_.size()) { threads_.reserve(states_.size()); for (std::size_t i = 0; i < states_.size(); ++i) { threads_.emplace_back(std::bind(&thread_pool2::routine, this, i)); } } ~thread_pool2() { std::cerr << "Destroying thread pool ..." << std::endl; { std::unique_lock<std::mutex> lk(mtx_); std::fill(states_.begin(), states_.end(), state::shutdown); } cv_.notify_all(); for (auto& t : threads_) t.join(); std::cerr << "Done destroying thread pool ..." << std::endl; } std::size_t thread_count() const { return threads_.size() + 1; } void routine(std::size_t thread_idx) { while (true) { { std::unique_lock<std::mutex> lk(mtx_); if (states_[thread_idx] == state::shutdown) break; if (states_[thread_idx] == state::running) { states_[thread_idx] = state::sleep; ++sleeping_counter_; cv_.notify_all(); } cv_.wait(lk, [this, thread_idx] { return states_[thread_idx] != state::sleep; }); if (states_[thread_idx] == state::shutdown) break; states_[thread_idx] = state::running; } if (fn_) { fn_(thread_idx); } } } //template <typename Fn> void operator()(std::function<void(std::size_t)>&& fn) { fn_ = std::move(fn); { std::unique_lock<std::mutex> lk(mtx_); std::fill(states_.begin(), states_.end(), state::run); sleeping_counter_ = 0; } cv_.notify_all(); if (fn_) { fn_(states_.size()); } { // Wait for child threads to complete. std::unique_lock<std::mutex> lk(mtx_); cv_.wait(lk, [this] { return sleeping_counter_ == states_.size(); }); // std::count(states_.begin(), states_.end(), state::sleep) == states_.size(); }); } fn_ = nullptr; } }; template<typename Iter> class dynamic_iterator_thread_pool { public: dynamic_iterator_thread_pool(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference, const iteration_context&)>& fn, unsigned num_threads) : fn_(fn), cur_(begin), end_(end), index_(0), chunk_size_(chunk_size ? chunk_size : 1), num_threads_(num_threads ? num_threads : default_num_threads) { threads_.reserve(num_threads_ - 1); for (unsigned i = 0; i < (num_threads_ - 1); ++i) threads_.emplace_back(std::bind(&dynamic_iterator_thread_pool::routine, this, i)); this->routine(num_threads_ - 1); for (auto it = threads_.begin(); it != threads_.end(); ++it) it->join(); } private: std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_; std::vector<std::thread> threads_; Iter cur_; const Iter end_; std::size_t index_; std::mutex mtx_; const std::size_t chunk_size_; const std::size_t num_threads_; void routine(std::size_t thread_index) { bool done = false; while (!done) { std::vector<Iter> chunk(chunk_size_); std::unique_lock<std::mutex> lk(mtx_); std::size_t index = index_; for (std::size_t chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset) { ++index_; chunk[chunk_offset] = cur_; if (cur_ != end_) ++cur_; } lk.unlock(); for (std::size_t chunk_offset = 0; chunk_offset < chunk.size(); ++chunk_offset) { if (chunk[chunk_offset] == end_) { done = true; } else { fn_(*chunk[chunk_offset], {thread_index, index + chunk_offset}); //fn_ ? fn_(*it, i) : void(); } } } } }; template<typename Iter> class static_iterator_thread_pool { public: static_iterator_thread_pool(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference,const iteration_context&)>& fn, unsigned num_threads = 0) : fn_(fn), num_threads_(num_threads ? num_threads : default_num_threads), beg_(begin), end_(end), total_elements_(std::distance(beg_, end_)), chunk_size_(chunk_size ? chunk_size : static_cast<std::size_t>(total_elements_) / num_threads_) { threads_.reserve(num_threads_ - 1); for (unsigned i = 0; i < (num_threads_ - 1); ++i) threads_.emplace_back(std::bind(&static_iterator_thread_pool::routine, this, i)); this->routine(num_threads_ - 1); for (auto it = threads_.begin(); it != threads_.end(); ++it) it->join(); } private: std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_; const std::size_t num_threads_; std::vector<std::thread> threads_; const Iter beg_; const Iter end_; long total_elements_; const std::size_t chunk_size_; public: void routine(std::size_t thread_index) { auto cur = beg_; std::advance(cur, thread_index * chunk_size_); for (std::size_t index = (thread_index * chunk_size_); index < total_elements_; index += (chunk_size_ * num_threads_ - chunk_size_), std::advance(cur, chunk_size_ * num_threads_ - chunk_size_)) { for (std::size_t chunk_offset = 0; chunk_offset < chunk_size_ && index < total_elements_; ++chunk_offset) { assert(cur != end_); fn_(*cur, {thread_index,index}); //fn_ ? fn_(*it, i) : void(); ++cur; ++index; } } } }; template<typename Iter> class static_iterator_functor { public: static_iterator_functor(std::size_t chunk_size, Iter begin, Iter end, const std::function<void(typename Iter::reference,const iteration_context&)>& fn, unsigned num_threads) : fn_(fn), num_threads_(num_threads ? num_threads : default_num_threads), beg_(begin), end_(end), total_elements_(std::distance(beg_, end_)), chunk_size_(chunk_size ? chunk_size : ceil_divide(total_elements_, num_threads_)) { //assert(chunk_size_ > 0); // threads_.reserve(num_threads_ - 1); // for (unsigned i = 0; i < (num_threads_ - 1); ++i) // threads_.emplace_back(std::bind(&static_iterator_thread_pool::routine, this, i)); // this->routine(num_threads_ - 1); // // for (auto it = threads_.begin(); it != threads_.end(); ++it) // it->join(); } private: std::function<void(typename Iter::reference, const omp::iteration_context&)> fn_; const std::size_t num_threads_; const Iter beg_; const Iter end_; std::int64_t total_elements_; const std::int64_t chunk_size_; public: void operator()(std::size_t thread_index) { if (total_elements_ > 0) { auto cur = beg_; std::size_t index = (thread_index * chunk_size_); if (index >= total_elements_) return; std::advance(cur, thread_index * chunk_size_); for ( ; index < total_elements_; ) { std::size_t end_off = index + chunk_size_; for (; index < end_off && index < total_elements_; ++index,++cur) { assert(cur != end_); fn_(*cur, {thread_index, index}); //fn_ ? fn_(*it, i) : void(); } index += (chunk_size_ * num_threads_ - chunk_size_); if (index >= total_elements_) break; std::advance(cur, chunk_size_ * num_threads_ - chunk_size_); } } } }; } class sequence_iterator { public: typedef sequence_iterator self_type; typedef int difference_type; typedef int value_type; typedef value_type& reference; typedef value_type* pointer; typedef std::random_access_iterator_tag iterator_category; sequence_iterator() : val_(0) {} sequence_iterator(value_type val) : val_(val) { } //reference operator [] (difference_type); bool operator < (const self_type& other) { return val_ < other.val_; } bool operator > (const self_type& other) { return val_ > other.val_; } bool operator <= (const self_type& other) { return val_ <= other.val_; } bool operator >= (const self_type& other) { return val_ >= other.val_; } self_type operator++() { self_type ret = *this; ++val_; return ret; } self_type operator--() { self_type ret = *this; --val_; return ret; } self_type& operator += (difference_type i) { val_ += i; return *this; } self_type& operator -= (difference_type i) { val_ -= i; return *this; } self_type operator + (difference_type i) { return self_type(val_ + i); } self_type operator - (difference_type i) { return self_type(val_ - i); } difference_type operator - (const self_type& other) { return val_ - other.val_; } void operator++(int) { ++val_; } void operator--(int) { --val_; } reference operator*() { return val_; } pointer operator->() { return &val_; } bool operator==(const self_type& rhs) const { return (val_ == rhs.val_); } bool operator!=(const self_type& rhs) const { return (val_ != rhs.val_); } private: value_type val_; }; class schedule { public: schedule(std::size_t chunk_size); std::size_t chunk_size() const; protected: std::size_t chunk_size_; }; class dynamic_schedule : public schedule { public: dynamic_schedule(std::size_t chunk_size = 0); }; class static_schedule : public schedule { public: static_schedule(std::size_t chunk_size = 0); }; void parallel(const std::function<void(std::size_t)>& operation, unsigned thread_cnt = 0); template <typename Iterator> void parallel_for(const dynamic_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0) { internal::dynamic_iterator_thread_pool<Iterator> pool(sched.chunk_size(), begin, end, operation, thread_cnt); } template <typename Iterator> void parallel_for(const static_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0) { internal::static_iterator_thread_pool<Iterator> pool(sched.chunk_size(), begin, end, operation, thread_cnt); } template <typename Iterator> void parallel_for_exp(const static_schedule& sched, Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, internal::thread_pool2& tp) { tp(internal::static_iterator_functor<Iterator>(sched.chunk_size(), begin, end, operation, tp.thread_count())); //std::bind(&internal::static_iterator_functor<Iterator>::routine, &static_fn, std::placeholders::_1)); } template <typename Iterator> void parallel_for(Iterator begin, Iterator end, const std::function<void(typename Iterator::reference, const iteration_context&)>& operation, unsigned thread_cnt = 0) { parallel_for(static_schedule(), begin, end, operation, thread_cnt); } template <typename Handler> void critical(std::mutex& mtx, Handler fn) { std::lock_guard<std::mutex> lk(mtx); fn(); } template <typename Handler> void critical(Handler fn) { std::lock_guard<std::mutex> lk(internal::global_mutex); fn(); } } #endif //OMP_OMP_HPP <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2005-2006 by the FIFE Team * * fife-public@lists.sourceforge.net * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes // 3rd party library includes #include <guichan/sdl.hpp> #include <guichan.hpp> #include <SDL.h> // FIFE includes #include "video/gui/guimanager.h" #include "exception.h" #include "renderbackendsdl.h" #include "sdlscreen.h" #include "sdlimage.h" namespace FIFE { RenderBackendSDL::RenderBackendSDL() : RenderBackend("SDL"), m_screen(0) { } RenderBackendSDL::~RenderBackendSDL() { } void RenderBackendSDL::init() { if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) throw SDLException(SDL_GetError()); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); // temporary hack } void RenderBackendSDL::deinit() { delete m_screen; m_screen = 0; SDL_QuitSubSystem(SDL_INIT_VIDEO); } Screen* RenderBackendSDL::createMainScreen(unsigned int width, unsigned int height, unsigned char bitsPerPixel, bool fs) { Uint32 flags = 0; if (fs) { flags |= SDL_FULLSCREEN; } SDL_Surface* screen = NULL; if( 0 == bitsPerPixel ) { /// autodetect best mode unsigned char possibleBitsPerPixel[] = {32, 24, 16, 0}; int i = 0; while( true ) { bitsPerPixel = possibleBitsPerPixel[i]; if( !bitsPerPixel ) { throw SDLException("Videomode not available"); } if ( SDL_VideoModeOK(width, height, bitsPerPixel, flags) ) { screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); if( screen ) { break; } } ++i; } } else { if ( !SDL_VideoModeOK(width, height, bitsPerPixel, flags) ) { throw SDLException("Videomode not available"); } screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); } SDL_WM_SetCaption("FIFE", NULL); if (!screen) { throw SDLException(SDL_GetError()); } m_screen = new SDLScreen(screen); GUIManager* guimanager = GUIManager::instance(); guimanager->init(); return m_screen; } void RenderBackendSDL::startFrame() { SDL_FillRect(m_screen->getSurface(), 0, 0x00); } void RenderBackendSDL::endFrame() { SDL_Flip(m_screen->getSurface()); } Image* RenderBackendSDL::createStaticImageFromRGBA(const uint8_t* data, unsigned int width, unsigned int height) { SDL_Surface* surface = SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_SRCALPHA, width, height, 32, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff); SDL_LockSurface(surface); unsigned int size = width * height * 4; uint8_t* pixeldata = static_cast<uint8_t*>(surface->pixels); std::copy(data, data + size, pixeldata); SDL_UnlockSurface(surface); return new SDLImage(surface); } Screen* RenderBackendSDL::getMainScreen() const { return m_screen; } void RenderBackendSDL::captureScreen(const std::string& filename) { if( m_screen && m_screen->getSurface() ) { SDL_SaveBMP(m_screen->getSurface(),filename.c_str()); } } } <commit_msg>More robust selection of bpp, works better for me =)<commit_after>/*************************************************************************** * Copyright (C) 2005-2006 by the FIFE Team * * fife-public@lists.sourceforge.net * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes // 3rd party library includes #include <guichan/sdl.hpp> #include <guichan.hpp> #include <SDL.h> // FIFE includes #include "video/gui/guimanager.h" #include "exception.h" #include "log.h" #include "renderbackendsdl.h" #include "sdlscreen.h" #include "sdlimage.h" namespace FIFE { RenderBackendSDL::RenderBackendSDL() : RenderBackend("SDL"), m_screen(0) { } RenderBackendSDL::~RenderBackendSDL() { } void RenderBackendSDL::init() { if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) throw SDLException(SDL_GetError()); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); // temporary hack } void RenderBackendSDL::deinit() { delete m_screen; m_screen = 0; SDL_QuitSubSystem(SDL_INIT_VIDEO); } Screen* RenderBackendSDL::createMainScreen(unsigned int width, unsigned int height, unsigned char bitsPerPixel, bool fs) { Uint32 flags = 0; if (fs) { flags |= SDL_FULLSCREEN; } SDL_Surface* screen = NULL; if( 0 == bitsPerPixel ) { /// autodetect best mode unsigned char possibleBitsPerPixel[] = {16, 24, 32, 0}; int i = 0; while( true ) { bitsPerPixel = possibleBitsPerPixel[i]; if( !bitsPerPixel ) { // Last try, sometimes VideoModeOK seems to lie. // Try bpp=0 screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); if( !screen ) { throw SDLException("Videomode not available"); } break; } bitsPerPixel = SDL_VideoModeOK(width, height, bitsPerPixel, flags); if ( bitsPerPixel ) { screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); if( screen ) { break; } } ++i; } } else { if ( !SDL_VideoModeOK(width, height, bitsPerPixel, flags) ) { throw SDLException("Videomode not available"); } screen = SDL_SetVideoMode(width, height, bitsPerPixel, flags); } Log("RenderBackendSDL") << "Videomode " << width << "x" << height << " at " << int(screen->format->BitsPerPixel) << " bpp"; SDL_WM_SetCaption("FIFE", NULL); if (!screen) { throw SDLException(SDL_GetError()); } m_screen = new SDLScreen(screen); GUIManager* guimanager = GUIManager::instance(); guimanager->init(); return m_screen; } void RenderBackendSDL::startFrame() { SDL_FillRect(m_screen->getSurface(), 0, 0x00); } void RenderBackendSDL::endFrame() { SDL_Flip(m_screen->getSurface()); } Image* RenderBackendSDL::createStaticImageFromRGBA(const uint8_t* data, unsigned int width, unsigned int height) { SDL_Surface* surface = SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_SRCALPHA, width, height, 32, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff); SDL_LockSurface(surface); unsigned int size = width * height * 4; uint8_t* pixeldata = static_cast<uint8_t*>(surface->pixels); std::copy(data, data + size, pixeldata); SDL_UnlockSurface(surface); return new SDLImage(surface); } Screen* RenderBackendSDL::getMainScreen() const { return m_screen; } void RenderBackendSDL::captureScreen(const std::string& filename) { if( m_screen && m_screen->getSurface() ) { SDL_SaveBMP(m_screen->getSurface(),filename.c_str()); } } } <|endoftext|>
<commit_before>#ifndef ENTT_ENTITY_RUNTIME_VIEW_HPP #define ENTT_ENTITY_RUNTIME_VIEW_HPP #include <algorithm> #include <iterator> #include <type_traits> #include <utility> #include <vector> #include "entity.hpp" #include "fwd.hpp" #include "sparse_set.hpp" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename Set> class runtime_view_iterator final { using iterator_type = typename Set::iterator; [[nodiscard]] bool valid() const { return (!tombstone_check || *it != tombstone) && std::all_of(++pools->begin(), pools->end(), [entt = *it](const auto *curr) { return curr->contains(entt); }) && std::none_of(filter->cbegin(), filter->cend(), [entt = *it](const auto *curr) { return curr && curr->contains(entt); }); } public: using difference_type = typename iterator_type::difference_type; using value_type = typename iterator_type::value_type; using pointer = typename iterator_type::pointer; using reference = typename iterator_type::reference; using iterator_category = std::bidirectional_iterator_tag; constexpr runtime_view_iterator() noexcept : pools{}, filter{}, it{}, tombstone_check{} {} runtime_view_iterator(const std::vector<const Set *> &cpools, const std::vector<const Set *> &ignore, iterator_type curr) noexcept : pools{&cpools}, filter{&ignore}, it{curr}, tombstone_check{pools->size() == 1u && (*pools)[0u]->policy() == deletion_policy::in_place} { if(it != (*pools)[0]->end() && !valid()) { ++(*this); } } runtime_view_iterator &operator++() { while(++it != (*pools)[0]->end() && !valid()) {} return *this; } runtime_view_iterator operator++(int) { runtime_view_iterator orig = *this; return ++(*this), orig; } runtime_view_iterator &operator--() { while(--it != (*pools)[0]->begin() && !valid()) {} return *this; } runtime_view_iterator operator--(int) { runtime_view_iterator orig = *this; return operator--(), orig; } [[nodiscard]] pointer operator->() const noexcept { return it.operator->(); } [[nodiscard]] reference operator*() const noexcept { return *operator->(); } [[nodiscard]] constexpr bool operator==(const runtime_view_iterator &other) const noexcept { return it == other.it; } [[nodiscard]] constexpr bool operator!=(const runtime_view_iterator &other) const noexcept { return !(*this == other); } private: const std::vector<const Set *> *pools; const std::vector<const Set *> *filter; iterator_type it; bool tombstone_check; }; } // namespace internal /** * Internal details not to be documented. * @endcond */ /** * @brief Runtime view implementation. * * Primary template isn't defined on purpose. All the specializations give a * compile-time error, but for a few reasonable cases. */ template<typename> struct basic_runtime_view; /** * @brief Generic runtime view. * * Runtime views iterate over those entities that have at least all the given * components in their bags. During initialization, a runtime view looks at the * number of entities available for each component and picks up a reference to * the smallest set of candidate entities in order to get a performance boost * when iterate.<br/> * Order of elements during iterations are highly dependent on the order of the * underlying data structures. See sparse_set and its specializations for more * details. * * @b Important * * Iterators aren't invalidated if: * * * New instances of the given components are created and assigned to entities. * * The entity currently pointed is modified (as an example, if one of the * given components is removed from the entity to which the iterator points). * * The entity currently pointed is destroyed. * * In all the other cases, modifying the pools of the given components in any * way invalidates all the iterators and using them results in undefined * behavior. * * @note * Views share references to the underlying data structures of the registry that * generated them. Therefore any change to the entities and to the components * made by means of the registry are immediately reflected by the views, unless * a pool was missing when the view was built (in this case, the view won't * have a valid reference and won't be updated accordingly). * * @warning * Lifetime of a view must not overcome that of the registry that generated it. * In any other case, attempting to use a view results in undefined behavior. * * @tparam Entity A valid entity type (see entt_traits for more details). * @tparam Allocator Type of allocator used to manage memory and elements. */ template<typename Entity, typename Allocator> struct basic_runtime_view<basic_sparse_set<Entity, Allocator>> { /*! @brief Underlying entity identifier. */ using entity_type = Entity; /*! @brief Unsigned integer type. */ using size_type = std::size_t; /*! @brief Common type among all storage types. */ using base_type = basic_sparse_set<Entity, Allocator>; /*! @brief Bidirectional iterator type. */ using iterator = internal::runtime_view_iterator<base_type>; /*! @brief Default constructor to use to create empty, invalid views. */ basic_runtime_view() noexcept : pools{}, filter{} {} /** * @brief Appends an opaque storage object to a runtime view. * @param base An opaque reference to a storage object. * @return This runtime view. */ basic_runtime_view &iterate(const base_type &base) { if(pools.empty() || !(base.size() < pools[0u]->size())) { pools.push_back(&base); } else { pools.push_back(std::exchange(pools[0u], &base)); } return *this; } /** * @brief Adds an opaque storage object as a filter of a runtime view. * @param base An opaque reference to a storage object. * @return This runtime view. */ basic_runtime_view &exclude(const base_type &base) { filter.push_back(&base); return *this; } /** * @brief Estimates the number of entities iterated by the view. * @return Estimated number of entities iterated by the view. */ [[nodiscard]] size_type size_hint() const { return pools.empty() ? size_type{} : pools.front()->size(); } /** * @brief Returns an iterator to the first entity that has the given * components. * * The returned iterator points to the first entity that has the given * components. If the view is empty, the returned iterator will be equal to * `end()`. * * @return An iterator to the first entity that has the given components. */ [[nodiscard]] iterator begin() const { return pools.empty() ? iterator{} : iterator{pools, filter, pools[0]->begin()}; } /** * @brief Returns an iterator that is past the last entity that has the * given components. * * The returned iterator points to the entity following the last entity that * has the given components. Attempting to dereference the returned iterator * results in undefined behavior. * * @return An iterator to the entity following the last entity that has the * given components. */ [[nodiscard]] iterator end() const { return pools.empty() ? iterator{} : iterator{pools, filter, pools[0]->end()}; } /** * @brief Checks if a view contains an entity. * @param entt A valid identifier. * @return True if the view contains the given entity, false otherwise. */ [[nodiscard]] bool contains(const entity_type entt) const { return !pools.empty() && std::all_of(pools.cbegin(), pools.cend(), [entt](const auto *curr) { return curr->contains(entt); }) && std::none_of(filter.cbegin(), filter.cend(), [entt](const auto *curr) { return curr && curr->contains(entt); }); } /** * @brief Iterates entities and applies the given function object to them. * * The function object is invoked for each entity. It is provided only with * the entity itself. To get the components, users can use the registry with * which the view was built.<br/> * The signature of the function should be equivalent to the following: * * @code{.cpp} * void(const entity_type); * @endcode * * @tparam Func Type of the function object to invoke. * @param func A valid function object. */ template<typename Func> void each(Func func) const { for(const auto entity: *this) { func(entity); } } private: std::vector<const base_type *> pools; std::vector<const base_type *> filter; }; } // namespace entt #endif <commit_msg>runtime_view: remove the dependency on the sparse set class<commit_after>#ifndef ENTT_ENTITY_RUNTIME_VIEW_HPP #define ENTT_ENTITY_RUNTIME_VIEW_HPP #include <algorithm> #include <cstddef> #include <iterator> #include <utility> #include <vector> #include "entity.hpp" #include "fwd.hpp" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename Set> class runtime_view_iterator final { using iterator_type = typename Set::iterator; [[nodiscard]] bool valid() const { return (!tombstone_check || *it != tombstone) && std::all_of(++pools->begin(), pools->end(), [entt = *it](const auto *curr) { return curr->contains(entt); }) && std::none_of(filter->cbegin(), filter->cend(), [entt = *it](const auto *curr) { return curr && curr->contains(entt); }); } public: using difference_type = typename iterator_type::difference_type; using value_type = typename iterator_type::value_type; using pointer = typename iterator_type::pointer; using reference = typename iterator_type::reference; using iterator_category = std::bidirectional_iterator_tag; constexpr runtime_view_iterator() noexcept : pools{}, filter{}, it{}, tombstone_check{} {} runtime_view_iterator(const std::vector<const Set *> &cpools, const std::vector<const Set *> &ignore, iterator_type curr) noexcept : pools{&cpools}, filter{&ignore}, it{curr}, tombstone_check{pools->size() == 1u && (*pools)[0u]->policy() == deletion_policy::in_place} { if(it != (*pools)[0]->end() && !valid()) { ++(*this); } } runtime_view_iterator &operator++() { while(++it != (*pools)[0]->end() && !valid()) {} return *this; } runtime_view_iterator operator++(int) { runtime_view_iterator orig = *this; return ++(*this), orig; } runtime_view_iterator &operator--() { while(--it != (*pools)[0]->begin() && !valid()) {} return *this; } runtime_view_iterator operator--(int) { runtime_view_iterator orig = *this; return operator--(), orig; } [[nodiscard]] pointer operator->() const noexcept { return it.operator->(); } [[nodiscard]] reference operator*() const noexcept { return *operator->(); } [[nodiscard]] constexpr bool operator==(const runtime_view_iterator &other) const noexcept { return it == other.it; } [[nodiscard]] constexpr bool operator!=(const runtime_view_iterator &other) const noexcept { return !(*this == other); } private: const std::vector<const Set *> *pools; const std::vector<const Set *> *filter; iterator_type it; bool tombstone_check; }; } // namespace internal /** * Internal details not to be documented. * @endcond */ /** * @brief Generic runtime view. * * Runtime views iterate over those entities that have at least all the given * components in their bags. During initialization, a runtime view looks at the * number of entities available for each component and picks up a reference to * the smallest set of candidate entities in order to get a performance boost * when iterate.<br/> * Order of elements during iterations are highly dependent on the order of the * underlying data structures. See sparse_set and its specializations for more * details. * * @b Important * * Iterators aren't invalidated if: * * * New instances of the given components are created and assigned to entities. * * The entity currently pointed is modified (as an example, if one of the * given components is removed from the entity to which the iterator points). * * The entity currently pointed is destroyed. * * In all the other cases, modifying the pools of the given components in any * way invalidates all the iterators and using them results in undefined * behavior. * * @note * Views share references to the underlying data structures of the registry that * generated them. Therefore any change to the entities and to the components * made by means of the registry are immediately reflected by the views, unless * a pool was missing when the view was built (in this case, the view won't * have a valid reference and won't be updated accordingly). * * @warning * Lifetime of a view must not overcome that of the registry that generated it. * In any other case, attempting to use a view results in undefined behavior. * * @tparam Type Common base type. */ template<typename Type> struct basic_runtime_view { /*! @brief Underlying entity identifier. */ using entity_type = typename Type::entity_type; /*! @brief Unsigned integer type. */ using size_type = std::size_t; /*! @brief Common type among all storage types. */ using base_type = Type; /*! @brief Bidirectional iterator type. */ using iterator = internal::runtime_view_iterator<base_type>; /*! @brief Default constructor to use to create empty, invalid views. */ basic_runtime_view() noexcept : pools{}, filter{} {} /** * @brief Appends an opaque storage object to a runtime view. * @param base An opaque reference to a storage object. * @return This runtime view. */ basic_runtime_view &iterate(const base_type &base) { if(pools.empty() || !(base.size() < pools[0u]->size())) { pools.push_back(&base); } else { pools.push_back(std::exchange(pools[0u], &base)); } return *this; } /** * @brief Adds an opaque storage object as a filter of a runtime view. * @param base An opaque reference to a storage object. * @return This runtime view. */ basic_runtime_view &exclude(const base_type &base) { filter.push_back(&base); return *this; } /** * @brief Estimates the number of entities iterated by the view. * @return Estimated number of entities iterated by the view. */ [[nodiscard]] size_type size_hint() const { return pools.empty() ? size_type{} : pools.front()->size(); } /** * @brief Returns an iterator to the first entity that has the given * components. * * The returned iterator points to the first entity that has the given * components. If the view is empty, the returned iterator will be equal to * `end()`. * * @return An iterator to the first entity that has the given components. */ [[nodiscard]] iterator begin() const { return pools.empty() ? iterator{} : iterator{pools, filter, pools[0]->begin()}; } /** * @brief Returns an iterator that is past the last entity that has the * given components. * * The returned iterator points to the entity following the last entity that * has the given components. Attempting to dereference the returned iterator * results in undefined behavior. * * @return An iterator to the entity following the last entity that has the * given components. */ [[nodiscard]] iterator end() const { return pools.empty() ? iterator{} : iterator{pools, filter, pools[0]->end()}; } /** * @brief Checks if a view contains an entity. * @param entt A valid identifier. * @return True if the view contains the given entity, false otherwise. */ [[nodiscard]] bool contains(const entity_type entt) const { return !pools.empty() && std::all_of(pools.cbegin(), pools.cend(), [entt](const auto *curr) { return curr->contains(entt); }) && std::none_of(filter.cbegin(), filter.cend(), [entt](const auto *curr) { return curr && curr->contains(entt); }); } /** * @brief Iterates entities and applies the given function object to them. * * The function object is invoked for each entity. It is provided only with * the entity itself. To get the components, users can use the registry with * which the view was built.<br/> * The signature of the function should be equivalent to the following: * * @code{.cpp} * void(const entity_type); * @endcode * * @tparam Func Type of the function object to invoke. * @param func A valid function object. */ template<typename Func> void each(Func func) const { for(const auto entity: *this) { func(entity); } } private: std::vector<const base_type *> pools; std::vector<const base_type *> filter; }; } // namespace entt #endif <|endoftext|>
<commit_before>/** * A class which represents the properties and actions of a technology. * * @date Jul 3, 2014 * @author Joeri HERMANS * @version 0.1 * * Copyright 2013 Joeri HERMANS * * 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. */ // BEGIN Includes. /////////////////////////////////////////////////// // System dependencies. #include <cassert> // Application dependencies. #include <ias/technology/technology.h> // END Includes. ///////////////////////////////////////////////////// inline void Technology::initialize( void ) { mId = 0; } void Technology::setId( const std::size_t id ) { // Checking the precondition. assert( id > 0 ); mId = id; } Technology::Technology( const std::size_t id, const std::string & identifier, const std::string & name, const std::string & description, const std::vector<Member *> & members, const std::vector<Feature *> & features ) { initialize(); setId(id); setIdentifier(identifier); setName(name); setDescription(description); mMembers = members; mFeatures = features; } Technology::~Technology( void ) { // Nothing to do here. } std::size_t Technology::getId( void ) const { return ( mId ); } const std::string & Technology::getIdentifier( void ) const { return ( mIdentifier ); } void Technology::setIdentifier( const std::string & identifier ) { // Checking the precondition. assert( !identifier.empty() ); mMutexIdentifier.lock(); mIdentifier = identifier; mMutexIdentifier.unlock(); } const std::string & Technology::getName( void ) const { return ( mName ); } void Technology::setName( const std::string & name ) { // Checking the precondition. assert( !name.empty() ); mMutexName.lock(); mName = name; mMutexName.unlock(); } const std::string & Technology::getDescription( void ) const { return ( mDescription ); } bool Technology::hasDescription( void ) const { return ( mDescription.empty() ); } void Technology::setDescription( const std::string & description ) { mMutexDescription.lock(); mDescription = description; mMutexDescription.unlock(); } const std::vector<Member *> & Technology::getMembers( void ) const { return ( mMembers ); } std::size_t Technology::numMembers( void ) const { return ( mMembers.size() ); } const std::vector<Feature *> & Technology::getFeatures( void ) const { return ( mFeatures ); } const Feature * Technology::getFeature( const std::string & identifier ) const { const Feature * f; Feature * feature; f = nullptr; for( auto it = mFeatures.begin() ; it != mFeatures.end() ; ++it ) { feature = (*it); if( feature->getIdentifier() == identifier ) { f = feature; break; } } return ( f ); } bool Technology::containsFeature( const std::string & identifier ) const { Feature * feature; bool contains; contains = false; for( auto it = mFeatures.begin() ; it != mFeatures.end() ; ++it ) { feature = (*it); if( feature->getIdentifier() == identifier ) { contains = true; break; } } return ( contains ); } std::size_t Technology::numFeatures( void ) const { return ( mFeatures.size() ); } <commit_msg>Remove unnessecary spaces.<commit_after>/** * A class which represents the properties and actions of a technology. * * @date Jul 3, 2014 * @author Joeri HERMANS * @version 0.1 * * Copyright 2013 Joeri HERMANS * * 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. */ // BEGIN Includes. /////////////////////////////////////////////////// // System dependencies. #include <cassert> // Application dependencies. #include <ias/technology/technology.h> // END Includes. ///////////////////////////////////////////////////// inline void Technology::initialize( void ) { mId = 0; } void Technology::setId( const std::size_t id ) { // Checking the precondition. assert( id > 0 ); mId = id; } Technology::Technology( const std::size_t id, const std::string & identifier, const std::string & name, const std::string & description, const std::vector<Member *> & members, const std::vector<Feature *> & features ) { initialize(); setId(id); setIdentifier(identifier); setName(name); setDescription(description); mMembers = members; mFeatures = features; } Technology::~Technology( void ) { // Nothing to do here. } std::size_t Technology::getId( void ) const { return ( mId ); } const std::string & Technology::getIdentifier( void ) const { return ( mIdentifier ); } void Technology::setIdentifier( const std::string & identifier ) { // Checking the precondition. assert( !identifier.empty() ); mMutexIdentifier.lock(); mIdentifier = identifier; mMutexIdentifier.unlock(); } const std::string & Technology::getName( void ) const { return ( mName ); } void Technology::setName( const std::string & name ) { // Checking the precondition. assert( !name.empty() ); mMutexName.lock(); mName = name; mMutexName.unlock(); } const std::string & Technology::getDescription( void ) const { return ( mDescription ); } bool Technology::hasDescription( void ) const { return ( mDescription.empty() ); } void Technology::setDescription( const std::string & description ) { mMutexDescription.lock(); mDescription = description; mMutexDescription.unlock(); } const std::vector<Member *> & Technology::getMembers( void ) const { return ( mMembers ); } std::size_t Technology::numMembers( void ) const { return ( mMembers.size() ); } const std::vector<Feature *> & Technology::getFeatures( void ) const { return ( mFeatures ); } const Feature * Technology::getFeature( const std::string & identifier ) const { const Feature * f; Feature * feature; f = nullptr; for( auto it = mFeatures.begin() ; it != mFeatures.end() ; ++it ) { feature = (*it); if( feature->getIdentifier() == identifier ) { f = feature; break; } } return ( f ); } bool Technology::containsFeature( const std::string & identifier ) const { Feature * feature; bool contains; contains = false; for( auto it = mFeatures.begin() ; it != mFeatures.end() ; ++it ) { feature = (*it); if( feature->getIdentifier() == identifier ) { contains = true; break; } } return ( contains ); } std::size_t Technology::numFeatures( void ) const { return ( mFeatures.size() ); } <|endoftext|>
<commit_before>#include "maExtrude.h" #include "maCrawler.h" #include <apfMDS.h> #include <cassert> #include <sstream> //DEBUG #include <iostream> namespace ma { namespace { typedef std::set<Model*> ModelSet; typedef std::vector<Crawler::Layer> Layers; typedef std::vector<double> LayerFieldData; typedef std::vector<LayerFieldData> FieldData; typedef std::vector<apf::Field*> Fields; struct AllFieldsData { std::vector<FieldData> flat_data; FieldData flat_z_data; }; void gatherExtrudedFields(Mesh* m, Fields* fields_out) { Fields& fields = *fields_out; fields.clear(); for (int i = 0; i < m->countFields(); ++i) { apf::Field* f = m->getField(i); if (apf::getShape(f) == m->getShape()) fields.push_back(f); } } struct DataGetter { virtual void get(Entity* e, double* data_out) const = 0; virtual int ncomps() const = 0; }; struct FieldDataGetter : public DataGetter { apf::Field* field; FieldDataGetter(apf::Field* f):field(f) {} virtual void get(Entity* e, double* data_out) const { apf::getComponents(field, e, 0, data_out); } virtual int ncomps() const { return apf::countComponents(field); } }; struct ZDataGetter : public DataGetter { apf::Mesh* mesh; ZDataGetter(apf::Mesh* m):mesh(m) {} virtual void get(Entity* v, double* data_out) const { Vector x; mesh->getPoint(v, 0, x); *data_out = x[2]; } virtual int ncomps() const { return 1; } }; void gatherFieldData(DataGetter const& getter, Layers const& layers, FieldData* data_out) { int ncomps = getter.ncomps(); FieldData& data = *data_out; data.clear(); for (size_t l = 0; l < layers.size(); ++l) { Crawler::Layer const& layer = layers[l]; data.push_back(LayerFieldData()); LayerFieldData& layer_data = data.back(); layer_data.resize(layer.size() * ncomps); for (size_t i = 0; i < layer.size(); ++i) { Entity* e = layer[i]; getter.get(e, &layer_data[i * ncomps]); } } } void gatherAllFieldsData(Mesh* m, Layers const& layers, Fields const& extruded_fields, AllFieldsData* all_data_out) { AllFieldsData& all_data = *all_data_out; for (size_t i = 0; i < extruded_fields.size(); ++i) { FieldDataGetter getter(extruded_fields[i]); all_data.flat_data.resize(all_data.flat_data.size() + 1); FieldData field_data = all_data.flat_data.back(); gatherFieldData(getter, layers, &field_data); } ZDataGetter getter(m); gatherFieldData(getter, layers, &all_data.flat_z_data); } void getBottomModels(ModelExtrusions const& model_extrusions, ModelSet* bottoms_out) { ModelSet& bottoms = *bottoms_out; APF_CONST_ITERATE(ModelExtrusions, model_extrusions, it) bottoms.insert(it->bottom); } void getBase(Mesh* m, ModelSet const& bottoms, int d, Crawler::Layer* base_out) { std::cerr << "bottoms:\n"; APF_CONST_ITERATE(ModelSet, bottoms, it) { std::cerr << "(" << m->getModelType(*it) << ", " << m->getModelTag(*it) << ")\n"; } Crawler::Layer& base = *base_out; Iterator* it = m->begin(d); Entity* e; while ((e = m->iterate(it))) if (bottoms.count(m->toModel(e))) base.push_back(e); m->end(it); std::cerr << "bottom layer has " << base.size() << " verts\n"; } void getVertLayers(Mesh* m, Crawler::Layer const& base_layer, Layers* layers_out) { Layers& layers = *layers_out; apf::MeshTag* visited = m->createIntTag("visited", 0); HasTag pred(m, visited); Crawler::Layer current_layer = base_layer; do { layers.push_back(current_layer); Crawler::Layer next_layer; for (size_t i = 0; i < current_layer.size(); ++i) { m->setIntTag(current_layer[i], visited, 0); } std::cerr << "crawling a layer...\n"; for (size_t i = 0; i < current_layer.size(); ++i) { Entity* v = current_layer[i]; Entity* ov = getOtherVert(m, v, pred); if (ov) next_layer.push_back(ov); } if (!next_layer.empty()) assert(next_layer.size() == current_layer.size()); current_layer = next_layer; } while (!current_layer.empty()); m->destroyTag(visited); } void remove3DPortion(Mesh* m, ModelSet const& bottoms) { for (int d = 3; d >= 0; --d) { Iterator* it = m->begin(d); Entity* e; while ((e = m->iterate(it))) { if (!bottoms.count(m->toModel(e))) m->destroy(e); } m->end(it); } assert(m->count(3) == 0); apf::changeMdsDimension(m, 2); m->acceptChanges(); // needed ? not needed ? who knows... } void defrag(Mesh* m) { /* we need to use reordering to remove all holes in * the data structure leftover from removing the 3D portion, * but at the same time we don't want to change the vertex * order because it lines up with temporary field data * vectors, so we explicitly specify an identity ordering. */ Tag* tag = m->createIntTag("reorder", 1); Iterator* it = m->begin(0); Entity* v; int i = 0; while ((v = m->iterate(it))) { m->setIntTag(v, tag, &i); ++i; } m->end(it); reorderMdsMesh(m, tag); } void applyFlatField(Mesh* m, std::string const& extruded_name, int ncomps, FieldData const& field_data) { for (size_t j = 0; j < field_data.size(); ++j) { std::stringstream ss; ss << 'L' << j << '_'; ss << extruded_name; std::string name = ss.str(); apf::Field* flat_field = apf::createPackedField( m, name.c_str(), ncomps); LayerFieldData const& layer_data = field_data[j]; Iterator* it = m->begin(0); Entity* v; size_t k = 0; while ((v = m->iterate(it))) { apf::setComponents(flat_field, v, 0, &layer_data[k * ncomps]); ++k; } m->end(it); } } void applyFlatFields(Mesh* m, Fields const& extruded_fields, AllFieldsData const& all_data) { for (size_t i = 0; i < extruded_fields.size(); ++i) { apf::Field* extruded_field = extruded_fields[i]; std::string extruded_name = apf::getName(extruded_field); int ncomps = apf::countComponents(extruded_field); apf::destroyField(extruded_field); FieldData const& field_data = all_data.flat_data[i]; applyFlatField(m, extruded_name, ncomps, field_data); } applyFlatField(m, "z", 1, all_data.flat_z_data); } void zeroOutZCoords(Mesh* m) { Iterator* it = m->begin(0); Entity* v; while ((v = m->iterate(it))) { Vector x; m->getPoint(v, 0, x); x[2] = 0; m->setPoint(v, 0, x); } m->end(it); } } // end anonymous namespace void intrude(Mesh* m, ModelExtrusions const& model_extrusions, size_t* num_layers_out) { ModelSet bottoms; getBottomModels(model_extrusions, &bottoms); Crawler::Layer base; getBase(m, bottoms, 0, &base); Layers layers; getVertLayers(m, base, &layers); *num_layers_out = layers.size(); Fields extruded_fields; gatherExtrudedFields(m, &extruded_fields); AllFieldsData all_data; gatherAllFieldsData(m, layers, extruded_fields, &all_data); remove3DPortion(m, bottoms); defrag(m); applyFlatFields(m, extruded_fields, all_data); zeroOutZCoords(m); } } // end namespac ma <commit_msg>fix remaining bugs with prisms to triangles<commit_after>#include "maExtrude.h" #include "maCrawler.h" #include <apfMDS.h> #include <cassert> #include <sstream> //DEBUG #include <iostream> namespace ma { namespace { typedef std::set<Model*> ModelSet; typedef std::vector<Crawler::Layer> Layers; typedef std::vector<double> LayerFieldData; typedef std::vector<LayerFieldData> FieldData; typedef std::vector<apf::Field*> Fields; struct AllFieldsData { std::vector<FieldData> flat_data; FieldData flat_z_data; }; void gatherExtrudedFields(Mesh* m, Fields* fields_out) { std::cerr << "gathering extruded fields...\n"; Fields& fields = *fields_out; fields.clear(); for (int i = 0; i < m->countFields(); ++i) { apf::Field* f = m->getField(i); std::cerr << "field " << apf::getName(f) << " exists\n"; if (apf::getShape(f) == m->getShape()) { std::cerr << "field " << apf::getName(f) << " accepted\n"; fields.push_back(f); } } } struct DataGetter { virtual void get(Entity* e, double* data_out) const = 0; virtual int ncomps() const = 0; }; struct FieldDataGetter : public DataGetter { apf::Field* field; FieldDataGetter(apf::Field* f):field(f) {} virtual void get(Entity* e, double* data_out) const { apf::getComponents(field, e, 0, data_out); } virtual int ncomps() const { return apf::countComponents(field); } }; struct ZDataGetter : public DataGetter { apf::Mesh* mesh; ZDataGetter(apf::Mesh* m):mesh(m) {} virtual void get(Entity* v, double* data_out) const { Vector x; mesh->getPoint(v, 0, x); *data_out = x[2]; } virtual int ncomps() const { return 1; } }; void gatherFieldData(DataGetter const& getter, Layers const& layers, FieldData* data_out) { int ncomps = getter.ncomps(); FieldData& data = *data_out; data.clear(); for (size_t l = 0; l < layers.size(); ++l) { Crawler::Layer const& layer = layers[l]; data.push_back(LayerFieldData()); LayerFieldData& layer_data = data.back(); layer_data.resize(layer.size() * ncomps); for (size_t i = 0; i < layer.size(); ++i) { Entity* e = layer[i]; getter.get(e, &layer_data[i * ncomps]); } } } void gatherAllFieldsData(Mesh* m, Layers const& layers, Fields const& extruded_fields, AllFieldsData* all_data_out) { AllFieldsData& all_data = *all_data_out; for (size_t i = 0; i < extruded_fields.size(); ++i) { FieldDataGetter getter(extruded_fields[i]); all_data.flat_data.resize(all_data.flat_data.size() + 1); FieldData& field_data = all_data.flat_data.back(); gatherFieldData(getter, layers, &field_data); } ZDataGetter getter(m); gatherFieldData(getter, layers, &all_data.flat_z_data); } void getBottomModels(ModelExtrusions const& model_extrusions, ModelSet* bottoms_out) { ModelSet& bottoms = *bottoms_out; APF_CONST_ITERATE(ModelExtrusions, model_extrusions, it) bottoms.insert(it->bottom); } void getBase(Mesh* m, ModelSet const& bottoms, int d, Crawler::Layer* base_out) { std::cerr << "bottoms:\n"; APF_CONST_ITERATE(ModelSet, bottoms, it) { std::cerr << "(" << m->getModelType(*it) << ", " << m->getModelTag(*it) << ")\n"; } Crawler::Layer& base = *base_out; Iterator* it = m->begin(d); Entity* e; while ((e = m->iterate(it))) if (bottoms.count(m->toModel(e))) base.push_back(e); m->end(it); std::cerr << "bottom layer has " << base.size() << " verts\n"; } void getVertLayers(Mesh* m, Crawler::Layer const& base_layer, Layers* layers_out) { Layers& layers = *layers_out; apf::MeshTag* visited = m->createIntTag("visited", 0); HasTag pred(m, visited); Crawler::Layer current_layer = base_layer; do { layers.push_back(current_layer); Crawler::Layer next_layer; for (size_t i = 0; i < current_layer.size(); ++i) { m->setIntTag(current_layer[i], visited, 0); } std::cerr << "crawling a layer...\n"; for (size_t i = 0; i < current_layer.size(); ++i) { Entity* v = current_layer[i]; Entity* ov = getOtherVert(m, v, pred); if (ov) next_layer.push_back(ov); } if (!next_layer.empty()) assert(next_layer.size() == current_layer.size()); current_layer = next_layer; } while (!current_layer.empty()); m->destroyTag(visited); } void remove3DPortion(Mesh* m, ModelSet const& bottoms) { for (int d = 3; d >= 0; --d) { Iterator* it = m->begin(d); Entity* e; while ((e = m->iterate(it))) { if (!bottoms.count(m->toModel(e))) m->destroy(e); } m->end(it); } assert(m->count(3) == 0); apf::changeMdsDimension(m, 2); m->acceptChanges(); // needed ? not needed ? who knows... } void defrag(Mesh* m) { /* we need to use reordering to remove all holes in * the data structure leftover from removing the 3D portion, * but at the same time we don't want to change the vertex * order because it lines up with temporary field data * vectors, so we explicitly specify an identity ordering. */ Tag* tag = m->createIntTag("reorder", 1); Iterator* it = m->begin(0); Entity* v; int i = 0; while ((v = m->iterate(it))) { m->setIntTag(v, tag, &i); ++i; } m->end(it); reorderMdsMesh(m, tag); } void applyFlatField(Mesh* m, std::string const& extruded_name, int ncomps, FieldData const& field_data) { std::cerr << "flat field " << extruded_name << " will have " << field_data.size() << " layers\n"; for (size_t j = 0; j < field_data.size(); ++j) { std::stringstream ss; ss << 'L' << j << '_'; ss << extruded_name; std::string name = ss.str(); apf::Field* flat_field = apf::createPackedField( m, name.c_str(), ncomps); LayerFieldData const& layer_data = field_data[j]; Iterator* it = m->begin(0); Entity* v; size_t k = 0; while ((v = m->iterate(it))) { apf::setComponents(flat_field, v, 0, &layer_data[k * ncomps]); ++k; } m->end(it); } } void applyFlatFields(Mesh* m, Fields const& extruded_fields, AllFieldsData const& all_data) { std::cerr << "applying flat fields...\n"; for (size_t i = 0; i < extruded_fields.size(); ++i) { apf::Field* extruded_field = extruded_fields[i]; std::string extruded_name = apf::getName(extruded_field); int ncomps = apf::countComponents(extruded_field); apf::destroyField(extruded_field); FieldData const& field_data = all_data.flat_data[i]; std::cerr << "applying flat field " << extruded_name << '\n'; applyFlatField(m, extruded_name, ncomps, field_data); } applyFlatField(m, "z", 1, all_data.flat_z_data); } void zeroOutZCoords(Mesh* m) { Iterator* it = m->begin(0); Entity* v; while ((v = m->iterate(it))) { Vector x; m->getPoint(v, 0, x); x[2] = 0; m->setPoint(v, 0, x); } m->end(it); } } // end anonymous namespace void intrude(Mesh* m, ModelExtrusions const& model_extrusions, size_t* num_layers_out) { ModelSet bottoms; getBottomModels(model_extrusions, &bottoms); Crawler::Layer base; getBase(m, bottoms, 0, &base); Layers layers; getVertLayers(m, base, &layers); *num_layers_out = layers.size(); Fields extruded_fields; gatherExtrudedFields(m, &extruded_fields); AllFieldsData all_data; gatherAllFieldsData(m, layers, extruded_fields, &all_data); remove3DPortion(m, bottoms); defrag(m); applyFlatFields(m, extruded_fields, all_data); zeroOutZCoords(m); } } // end namespac ma <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <gmock/gmock.h> #include <iostream> #include <fstream> #include <type_traits> #define BOOST_FILESYSTEM_NO_DEPRECATED #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> using namespace boost::filesystem; #include "../src/job/job.h" #include "../src/job/job_exception.h" #include "../src/fileman/cache_manager.h" #include "../src/helpers/config.h" TEST(job_test, bad_parameters) { std::shared_ptr<job_metadata> job_meta = std::make_shared<job_metadata>(); std::shared_ptr<worker_config> worker_conf = std::make_shared<worker_config>(); // job_config not given EXPECT_THROW(job(nullptr, nullptr, "", nullptr), job_exception); // worker_config not given EXPECT_THROW(job(job_meta, nullptr, "", nullptr), job_exception); // source path not exists EXPECT_THROW(job(job_meta, worker_conf, "", nullptr), job_exception); // fileman not given EXPECT_THROW(job(job_meta, worker_conf, temp_directory_path(), nullptr), job_exception); } TEST(job_test, bad_paths) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_meta = std::make_shared<job_metadata>(); auto worker_conf = std::make_shared<worker_config>(); auto fileman = std::make_shared<cache_manager>(); // non-existing source code folder EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // source code path with no source codes in it create_directories(dir); EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // source code directory is not a directory dir = dir / "hello"; std::ofstream hello(dir.string()); hello << "hello" << std::endl; hello.close(); EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // cleanup after yourself remove_all(dir_root); } TEST(job_test, empty_submission_details) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_meta = std::make_shared<job_metadata>(); auto worker_conf = std::make_shared<worker_config>(); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); // job-id is empty EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // language is empty job_meta->job_id = "hello-job"; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // file-server-url is empty job_meta->language = "cpp"; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // cleanup after yourself remove_all(dir_root); } TEST(job_test, empty_tasks_details) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_meta = std::make_shared<job_metadata>(); auto worker_conf = std::make_shared<worker_config>(); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); job_meta->job_id = "hello-job"; job_meta->language = "cpp"; job_meta->file_server_url = "localhost"; auto task = std::make_shared<task_metadata>(); job_meta->tasks.push_back(task); // empty task-id EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // empty task priority task->task_id = "hello-task"; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // empty task binary task->priority = 1; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // empty sandbox name task->binary = "hello"; auto sandbox = std::make_shared<sandbox_config>(); task->sandbox = sandbox; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // non-defined hwgroup name sandbox->name = "fake"; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // cleanup after yourself remove_all(dir_root); } TEST(job_test, non_empty_details) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_yaml = YAML::Load( "---\n" "submission:\n" " job-id: 5\n" " language: cpp\n" " file-collector: localhost\n" "tasks:\n" " - task-id: eval\n" " priority: 4\n" " fatal-failure: false\n" " cmd:\n" " bin: recodex\n" " args:\n" " - -v\n" " - \"-f 01.in\"\n" " stdin: 01.in\n" " stdout: 01.out\n" " stderr: 01.err\n" " sandbox:\n" " name: fake\n" " limits:\n" " - hw-group-id: group1\n" " time: 5\n" " wall-time: 6\n" " extra-time: 7\n" " stack-size: 50000\n" " memory: 60000\n" " parallel: 1\n" " disk-blocks: 50\n" " disk-inodes: 10\n" " chdir: /eval\n" " environ-variable:\n" " ISOLATE_BOX: /box\n" " ISOLATE_TMP: /tmp\n" " bound-directories:\n" " /tmp/recodex: /recodex/tmp\n" " - hw-group-id: group2\n" "...\n" ); auto job_meta = helpers::build_job_metadata(job_yaml); auto default_yaml = YAML::Load( "worker-id: 8\n" "broker-uri: localhost\n" "headers:\n" " hwgroup: group1\n" "file-managers:\n" " - hostname: http://localhost:80\n" " username: 654321\n" " password: 123456\n" ); auto worker_conf = std::make_shared<worker_config>(default_yaml); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); // given correct (non empty) job/tasks details EXPECT_NO_THROW(job(job_meta, worker_conf, dir, fileman)); // cleanup after yourself remove_all(dir_root); } TEST(job_test, load_of_worker_defaults) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_yaml = YAML::Load( "---\n" "submission:\n" " job-id: 5\n" " language: cpp\n" " file-collector: localhost\n" "tasks:\n" " - task-id: eval\n" " priority: 4\n" " fatal-failure: false\n" " cmd:\n" " bin: recodex\n" " sandbox:\n" " name: fake\n" " limits:\n" " - hw-group-id: group1\n" "...\n" ); auto job_meta = helpers::build_job_metadata(job_yaml); auto default_yaml = YAML::Load( "worker-id: 8\n" "broker-uri: localhost\n" "headers:\n" " hwgroup: group1\n" "file-managers:\n" " - hostname: http://localhost:80\n" " username: 654321\n" " password: 123456\n" "limits:\n" " time: 5\n" " wall-time: 6\n" " extra-time: 2\n" " stack-size: 50000\n" " memory: 60000\n" " parallel: 1\n" " disk-blocks: 50\n" " disk-inodes: 7\n" ); auto worker_conf = std::make_shared<worker_config>(default_yaml); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); // construct and check job result(job_meta, worker_conf, dir, fileman); ASSERT_EQ(result.get_task_queue().size(), 2); // 2 because of fake_task as root auto task = result.get_task_queue().at(1); auto ext_task = std::dynamic_pointer_cast<external_task>(task); sandbox_limits limits = ext_task->get_limits(); ASSERT_EQ(limits.cpu_time, 5); ASSERT_EQ(limits.wall_time, 6); ASSERT_EQ(limits.extra_time, 2); ASSERT_EQ(limits.stack_size, 50000); ASSERT_EQ(limits.memory_usage, 60000); ASSERT_EQ(limits.processes, 1); ASSERT_EQ(limits.disk_blocks, 50); ASSERT_EQ(limits.disk_inodes, 7); // cleanup after yourself remove_all(dir_root); } TEST(job_test, correct_build) // TODO { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_meta = std::make_shared<job_metadata>(); auto worker_conf = std::make_shared<worker_config>(); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); job_meta->job_id = "hello-job"; job_meta->language = "cpp"; job_meta->file_server_url = "localhost"; // non-existing source code folder EXPECT_NO_THROW(job(job_meta, worker_conf, dir, fileman)); // cleanup after yourself remove_all(dir_root); } <commit_msg>Final test finished<commit_after>#include <gtest/gtest.h> #include <gmock/gmock.h> #include <iostream> #include <fstream> #include <type_traits> #define BOOST_FILESYSTEM_NO_DEPRECATED #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> using namespace boost::filesystem; #include "../src/job/job.h" #include "../src/job/job_exception.h" #include "../src/fileman/cache_manager.h" #include "../src/helpers/config.h" TEST(job_test, bad_parameters) { std::shared_ptr<job_metadata> job_meta = std::make_shared<job_metadata>(); std::shared_ptr<worker_config> worker_conf = std::make_shared<worker_config>(); // job_config not given EXPECT_THROW(job(nullptr, nullptr, "", nullptr), job_exception); // worker_config not given EXPECT_THROW(job(job_meta, nullptr, "", nullptr), job_exception); // source path not exists EXPECT_THROW(job(job_meta, worker_conf, "", nullptr), job_exception); // fileman not given EXPECT_THROW(job(job_meta, worker_conf, temp_directory_path(), nullptr), job_exception); } TEST(job_test, bad_paths) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_meta = std::make_shared<job_metadata>(); auto worker_conf = std::make_shared<worker_config>(); auto fileman = std::make_shared<cache_manager>(); // non-existing source code folder EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // source code path with no source codes in it create_directories(dir); EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // source code directory is not a directory dir = dir / "hello"; std::ofstream hello(dir.string()); hello << "hello" << std::endl; hello.close(); EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // cleanup after yourself remove_all(dir_root); } TEST(job_test, empty_submission_details) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_meta = std::make_shared<job_metadata>(); auto worker_conf = std::make_shared<worker_config>(); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); // job-id is empty EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // language is empty job_meta->job_id = "hello-job"; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // file-server-url is empty job_meta->language = "cpp"; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // cleanup after yourself remove_all(dir_root); } TEST(job_test, empty_tasks_details) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_meta = std::make_shared<job_metadata>(); auto worker_conf = std::make_shared<worker_config>(); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); job_meta->job_id = "hello-job"; job_meta->language = "cpp"; job_meta->file_server_url = "localhost"; auto task = std::make_shared<task_metadata>(); job_meta->tasks.push_back(task); // empty task-id EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // empty task priority task->task_id = "hello-task"; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // empty task binary task->priority = 1; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // empty sandbox name task->binary = "hello"; auto sandbox = std::make_shared<sandbox_config>(); task->sandbox = sandbox; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // non-defined hwgroup name sandbox->name = "fake"; EXPECT_THROW(job(job_meta, worker_conf, dir, fileman), job_exception); // cleanup after yourself remove_all(dir_root); } TEST(job_test, non_empty_details) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_yaml = YAML::Load( "---\n" "submission:\n" " job-id: 5\n" " language: cpp\n" " file-collector: localhost\n" "tasks:\n" " - task-id: eval\n" " priority: 4\n" " fatal-failure: false\n" " cmd:\n" " bin: recodex\n" " args:\n" " - -v\n" " - \"-f 01.in\"\n" " stdin: 01.in\n" " stdout: 01.out\n" " stderr: 01.err\n" " sandbox:\n" " name: fake\n" " limits:\n" " - hw-group-id: group1\n" " time: 5\n" " wall-time: 6\n" " extra-time: 7\n" " stack-size: 50000\n" " memory: 60000\n" " parallel: 1\n" " disk-blocks: 50\n" " disk-inodes: 10\n" " chdir: /eval\n" " environ-variable:\n" " ISOLATE_BOX: /box\n" " ISOLATE_TMP: /tmp\n" " bound-directories:\n" " /tmp/recodex: /recodex/tmp\n" " - hw-group-id: group2\n" "...\n" ); auto job_meta = helpers::build_job_metadata(job_yaml); auto default_yaml = YAML::Load( "worker-id: 8\n" "broker-uri: localhost\n" "headers:\n" " hwgroup: group1\n" "file-managers:\n" " - hostname: http://localhost:80\n" " username: 654321\n" " password: 123456\n" ); auto worker_conf = std::make_shared<worker_config>(default_yaml); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); // given correct (non empty) job/tasks details EXPECT_NO_THROW(job(job_meta, worker_conf, dir, fileman)); // cleanup after yourself remove_all(dir_root); } TEST(job_test, load_of_worker_defaults) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_yaml = YAML::Load( "---\n" "submission:\n" " job-id: 5\n" " language: cpp\n" " file-collector: localhost\n" "tasks:\n" " - task-id: eval\n" " priority: 4\n" " fatal-failure: false\n" " cmd:\n" " bin: recodex\n" " sandbox:\n" " name: fake\n" " limits:\n" " - hw-group-id: group1\n" "...\n" ); auto job_meta = helpers::build_job_metadata(job_yaml); auto default_yaml = YAML::Load( "worker-id: 8\n" "broker-uri: localhost\n" "headers:\n" " hwgroup: group1\n" "file-managers:\n" " - hostname: http://localhost:80\n" " username: 654321\n" " password: 123456\n" "limits:\n" " time: 5\n" " wall-time: 6\n" " extra-time: 2\n" " stack-size: 50000\n" " memory: 60000\n" " parallel: 1\n" " disk-blocks: 50\n" " disk-inodes: 7\n" ); auto worker_conf = std::make_shared<worker_config>(default_yaml); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); // construct and check job result(job_meta, worker_conf, dir, fileman); ASSERT_EQ(result.get_task_queue().size(), 2); // 2 because of fake_task as root auto task = result.get_task_queue().at(1); auto ext_task = std::dynamic_pointer_cast<external_task>(task); sandbox_limits limits = ext_task->get_limits(); ASSERT_EQ(limits.cpu_time, 5); ASSERT_EQ(limits.wall_time, 6); ASSERT_EQ(limits.extra_time, 2); ASSERT_EQ(limits.stack_size, 50000); ASSERT_EQ(limits.memory_usage, 60000); ASSERT_EQ(limits.processes, 1); ASSERT_EQ(limits.disk_blocks, 50); ASSERT_EQ(limits.disk_inodes, 7); // cleanup after yourself remove_all(dir_root); } TEST(job_test, correctly_built_queue) { // prepare all things which need to be prepared path dir_root = temp_directory_path() / "isoeval"; path dir = dir_root / "job_test"; auto job_yaml = YAML::Load( "---\n" "submission:\n" " job-id: 5\n" " language: cpp\n" " file-collector: localhost\n" "tasks:\n" " - task-id: A\n" " priority: 1\n" " fatal-failure: false\n" " cmd:\n" " bin: mkdir\n" " args:\n" " - hello\n" " - task-id: B\n" " priority: 4\n" " fatal-failure: false\n" " dependencies:\n" " - A\n" " cmd:\n" " bin: mkdir\n" " args:\n" " - hello\n" " - task-id: C\n" " priority: 6\n" " fatal-failure: false\n" " dependencies:\n" " - B\n" " - D\n" " cmd:\n" " bin: mkdir\n" " args:\n" " - hello\n" " - task-id: D\n" " priority: 2\n" " fatal-failure: false\n" " dependencies:\n" " - A\n" " cmd:\n" " bin: mkdir\n" " args:\n" " - hello\n" " - task-id: E\n" " priority: 3\n" " fatal-failure: false\n" " dependencies:\n" " - D\n" " cmd:\n" " bin: mkdir\n" " args:\n" " - hello\n" " - task-id: F\n" " priority: 5\n" " fatal-failure: false\n" " dependencies:\n" " - D\n" " cmd:\n" " bin: mkdir\n" " args:\n" " - hello\n" " - task-id: G\n" " priority: 7\n" " fatal-failure: false\n" " dependencies:\n" " - C\n" " cmd:\n" " bin: mkdir\n" " args:\n" " - hello\n" "...\n" ); auto job_meta = helpers::build_job_metadata(job_yaml); auto default_yaml = YAML::Load( "worker-id: 8\n" "broker-uri: localhost\n" "headers:\n" " hwgroup: group1\n" "file-managers:\n" " - hostname: http://localhost:80\n" " username: 654321\n" " password: 123456\n" "limits:\n" " time: 5\n" " wall-time: 6\n" " extra-time: 2\n" " stack-size: 50000\n" " memory: 60000\n" " parallel: 1\n" " disk-blocks: 50\n" " disk-inodes: 7\n" ); auto worker_conf = std::make_shared<worker_config>(default_yaml); auto fileman = std::make_shared<cache_manager>(); create_directories(dir); std::ofstream hello((dir / "hello").string()); hello << "hello" << std::endl; hello.close(); // construct and check job result(job_meta, worker_conf, dir, fileman); auto tasks = result.get_task_queue(); ASSERT_EQ(tasks.size(), 8); // +1 because of fake_task root ASSERT_EQ(tasks.at(0)->get_task_id(), ""); // fake root ASSERT_EQ(tasks.at(1)->get_task_id(), "A"); ASSERT_EQ(tasks.at(2)->get_task_id(), "D"); ASSERT_EQ(tasks.at(3)->get_task_id(), "E"); ASSERT_EQ(tasks.at(4)->get_task_id(), "B"); ASSERT_EQ(tasks.at(5)->get_task_id(), "F"); ASSERT_EQ(tasks.at(6)->get_task_id(), "C"); ASSERT_EQ(tasks.at(7)->get_task_id(), "G"); // cleanup after yourself remove_all(dir_root); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2014. // 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 DBN_RBM_HPP #define DBN_RBM_HPP namespace dbn { /*! * \brief Restricted Boltzmann Machine */ struct rbm { }; } //end of dbn namespace #endif<commit_msg>Create prototype of the header<commit_after>//======================================================================= // Copyright Baptiste Wicht 2014. // 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 DBN_RBM_HPP #define DBN_RBM_HPP namespace dbn { /*! * \brief Restricted Boltzmann Machine */ template<typename Weight = double> struct rbm { }; } //end of dbn namespace #endif<|endoftext|>
<commit_before>#pragma once #include "spinlock.h" #include "log2.hh" #include <cstddef> #include <type_traits> namespace locked_snzi { class referenced { enum { LEVELS = ceil_log2_const(NCPU) + 1, FIRST_LEAF = (1 << (LEVELS - 1)) - 1 }; // A binary SNZI tree, indexed starting at the root. For example, // for NCPU=8 // 0 // 1 2 // 3 4 5 6 // 7 8 9 10 11 12 13 14 // The bottom level may be incomplete if NCPU is not a power of two. struct node { // XXX No padding for space reasons. Would be better if we // could stride allocate this between different SNZIs. // XXX Could use a bit_spinlock and pack it into val. spinlock lock; uint64_t val; constexpr node() : lock("locked_snzi::referenced::node"), val(0) {} } nodes[FIRST_LEAF + NCPU]; /// Return the parent of @c nodes[n]. static inline std::size_t parent(std::size_t n) { return (n - 1)/2; } /// Return the first child of @c nodes[n]. The second child is /// the returned index plus one. static inline std::size_t first_child(std::size_t n) { return 2*n + 1; } /// Return the sibling of @c nodes[n]. static inline std::size_t sibling(std::size_t n) { return ((n + 1) ^ 1) - 1; } public: referenced() : nodes{} { } referenced(const referenced &o) = delete; referenced(referenced &&o) = delete; referenced &operator=(const referenced &o) = delete; referenced &operator=(referenced &&o) = delete; typedef uint16_t cookie; static_assert(NCPU < (256 << sizeof(cookie)), "cookie too small for NCPU"); // XXX This is awkward. Unlike all other referenced types, we // initialize the count to zero and require an initial_inc because // the caller needs the cookie. This also screws up the transfer // method of sref<locked_snzi::referenced>. cookie initial_inc() { assert(nodes[0].val == 0); cookie leaf = myid(); std::size_t node = leaf + FIRST_LEAF; while (true) { nodes[node].val = 1; if (node == 0) break; node = parent(node); } return leaf; } cookie inc() { cookie leaf = myid(); std::size_t node = leaf + FIRST_LEAF; nodes[node].lock.acquire(); while (true) { if (nodes[node].val++ || node == 0) { // Already non-zero or we've reached the root nodes[node].lock.release(); return leaf; } else { // Transitioned from zero to non-zero std::size_t next = parent(node); nodes[next].lock.acquire(); nodes[node].lock.release(); node = next; } } return leaf; } void dec(cookie c) { std::size_t node = c + FIRST_LEAF; nodes[node].lock.acquire(); while (true) { assert(nodes[node].val); if (--nodes[node].val) { // Still non-zero nodes[node].lock.release(); return; } else if (node == 0) { // Transitioned from non-zero to zero at root nodes[node].lock.release(); onzero(); return; } else { // Transitioned from non-zero to zero std::size_t next = parent(node); nodes[next].lock.acquire(); nodes[node].lock.release(); node = next; } } } protected: virtual ~referenced() { } virtual void onzero() { delete this; } }; } // XXX This specialization is unfortunate because it means that, // unlike a regular pointer, sref cannot be applied to an incomplete // type because we can't evaluate is_base_of. template<class T> class sref<T, typename std::enable_if<std::is_base_of<locked_snzi::referenced, T>::value>::type> { T *ptr_; // XXX(Austin) Cookies are small. Could possibly tuck away in // unused bits of ptr_. typename T::cookie cookie_; constexpr sref(T *ptr, typename T::cookie cookie) noexcept : ptr_(ptr), cookie_(cookie) { } public: constexpr sref() noexcept : ptr_(nullptr), cookie_() { } sref(const sref &o) : ptr_(o.ptr_) { if (ptr_) cookie_ = ptr_->inc(); } sref(sref &&o) noexcept : ptr_(o.ptr_), cookie_(o.cookie_) { o.ptr_ = nullptr; } ~sref() { if (ptr_) ptr_->dec(cookie_); } sref& operator=(const sref& o) { T *optr = o.ptr_; if (optr != ptr_) { typename T::cookie ocookie = 0; if (optr) ocookie = optr->inc(); if (ptr_) ptr_->dec(cookie_); ptr_ = optr; cookie_ = ocookie; } return *this; } sref& operator=(sref&& o) { if (ptr_) ptr_->dec(cookie_); ptr_ = o.ptr_; cookie_ = o.cookie_; o.ptr_ = nullptr; return *this; } static sref transfer(T* p) { // XXX(Austin) This is a complete hack. See comment on // initial_inc. typename T::cookie c = p->initial_inc(); return sref(p, c); } explicit operator bool() const noexcept { return !!ptr_; } T * operator->() const noexcept { return ptr_; } T & operator*() const noexcept { return *ptr_; } T * get() const noexcept { return ptr_; } }; <commit_msg>snzi: Disable specialized sref<commit_after>#pragma once #include "spinlock.h" #include "log2.hh" #include <cstddef> #include <type_traits> namespace locked_snzi { class referenced { enum { LEVELS = ceil_log2_const(NCPU) + 1, FIRST_LEAF = (1 << (LEVELS - 1)) - 1 }; // A binary SNZI tree, indexed starting at the root. For example, // for NCPU=8 // 0 // 1 2 // 3 4 5 6 // 7 8 9 10 11 12 13 14 // The bottom level may be incomplete if NCPU is not a power of two. struct node { // XXX No padding for space reasons. Would be better if we // could stride allocate this between different SNZIs. // XXX Could use a bit_spinlock and pack it into val. spinlock lock; uint64_t val; constexpr node() : lock("locked_snzi::referenced::node"), val(0) {} } nodes[FIRST_LEAF + NCPU]; /// Return the parent of @c nodes[n]. static inline std::size_t parent(std::size_t n) { return (n - 1)/2; } /// Return the first child of @c nodes[n]. The second child is /// the returned index plus one. static inline std::size_t first_child(std::size_t n) { return 2*n + 1; } /// Return the sibling of @c nodes[n]. static inline std::size_t sibling(std::size_t n) { return ((n + 1) ^ 1) - 1; } public: referenced() : nodes{} { } referenced(const referenced &o) = delete; referenced(referenced &&o) = delete; referenced &operator=(const referenced &o) = delete; referenced &operator=(referenced &&o) = delete; typedef uint16_t cookie; static_assert(NCPU < (256 << sizeof(cookie)), "cookie too small for NCPU"); // XXX This is awkward. Unlike all other referenced types, we // initialize the count to zero and require an initial_inc because // the caller needs the cookie. This also screws up the transfer // method of sref<locked_snzi::referenced>. cookie initial_inc() { assert(nodes[0].val == 0); cookie leaf = myid(); std::size_t node = leaf + FIRST_LEAF; while (true) { nodes[node].val = 1; if (node == 0) break; node = parent(node); } return leaf; } cookie inc() { cookie leaf = myid(); std::size_t node = leaf + FIRST_LEAF; nodes[node].lock.acquire(); while (true) { if (nodes[node].val++ || node == 0) { // Already non-zero or we've reached the root nodes[node].lock.release(); return leaf; } else { // Transitioned from zero to non-zero std::size_t next = parent(node); nodes[next].lock.acquire(); nodes[node].lock.release(); node = next; } } return leaf; } void dec(cookie c) { std::size_t node = c + FIRST_LEAF; nodes[node].lock.acquire(); while (true) { assert(nodes[node].val); if (--nodes[node].val) { // Still non-zero nodes[node].lock.release(); return; } else if (node == 0) { // Transitioned from non-zero to zero at root nodes[node].lock.release(); onzero(); return; } else { // Transitioned from non-zero to zero std::size_t next = parent(node); nodes[next].lock.acquire(); nodes[node].lock.release(); node = next; } } } protected: virtual ~referenced() { } virtual void onzero() { delete this; } }; } #if 0 // XXX This specialization is unfortunate because it means that, // unlike a regular pointer, sref cannot be applied to an incomplete // type because we can't evaluate is_base_of. Disable it since we're // not using SNZI's. template<class T> class sref<T, typename std::enable_if<std::is_base_of<locked_snzi::referenced, T>::value>::type> { T *ptr_; // XXX(Austin) Cookies are small. Could possibly tuck away in // unused bits of ptr_. typename T::cookie cookie_; constexpr sref(T *ptr, typename T::cookie cookie) noexcept : ptr_(ptr), cookie_(cookie) { } public: constexpr sref() noexcept : ptr_(nullptr), cookie_() { } sref(const sref &o) : ptr_(o.ptr_) { if (ptr_) cookie_ = ptr_->inc(); } sref(sref &&o) noexcept : ptr_(o.ptr_), cookie_(o.cookie_) { o.ptr_ = nullptr; } ~sref() { if (ptr_) ptr_->dec(cookie_); } sref& operator=(const sref& o) { T *optr = o.ptr_; if (optr != ptr_) { typename T::cookie ocookie = 0; if (optr) ocookie = optr->inc(); if (ptr_) ptr_->dec(cookie_); ptr_ = optr; cookie_ = ocookie; } return *this; } sref& operator=(sref&& o) { if (ptr_) ptr_->dec(cookie_); ptr_ = o.ptr_; cookie_ = o.cookie_; o.ptr_ = nullptr; return *this; } static sref transfer(T* p) { // XXX(Austin) This is a complete hack. See comment on // initial_inc. typename T::cookie c = p->initial_inc(); return sref(p, c); } explicit operator bool() const noexcept { return !!ptr_; } T * operator->() const noexcept { return ptr_; } T & operator*() const noexcept { return *ptr_; } T * get() const noexcept { return ptr_; } }; #endif <|endoftext|>
<commit_before>/** \file * * Copyright (c) 2012 by Travis Gockel. All rights reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the Apache License * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later * version. * * \author Travis Gockel (travis@gockelhut.com) **/ #include "test.hpp" #include <jsonv/value.hpp> #include <jsonv/parse.hpp> TEST(parse_unicode_single) { std::string s = jsonv::parse("\"\\u0004\"").as_string(); ensure(s.size() == 1); ensure(s[0] == '\x04'); } TEST(parse_unicode_inline) { std::string s = jsonv::parse("\"é\"").as_string(); ensure(s.size() == 2); ensure(s[0] == '\xc3'); ensure(s[1] == '\xa9'); } TEST(parse_unicode_multi) { std::string s = jsonv::parse("\"\\u00e9\"").as_string(); ensure(s.size() == 2); ensure(s[0] == '\xc3'); ensure(s[1] == '\xa9'); } TEST(parse_unicode_insanity) { std::string s = jsonv::parse("\"\\uface\"").as_string(); ensure(s.size() == 3); // The right answer according to Python: u'\uface'.encode('utf-8') const char vals[] = "\xef\xab\x8e"; for (unsigned idx = 0; idx < 3; ++idx) ensure(s[idx] == vals[idx]); } // TODO: This test should be re-enabled when parsing options are supported. /*TEST(parse_unicode_invalid_surrogates) { std::string s = jsonv::parse("\"\\udead\\ubeef\"").as_string(); ensure(s.size() == 6); // The right answer according to Python: u'\udead\ubeef'.encode('utf-8') const char vals[] = "\xed\xba\xad\xeb\xbb\xaf"; for (unsigned idx = 0; idx < sizeof vals; ++idx) ensure(s[idx] == vals[idx]); }*/ <commit_msg>Re-enables unit test parse_unicode_invalid_surrogates and adds parse_unicode_invalid_surrogates_cesu8 for the invalid case.<commit_after>/** \file * * Copyright (c) 2012-2014 by Travis Gockel. All rights reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the Apache License * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later * version. * * \author Travis Gockel (travis@gockelhut.com) **/ #include "test.hpp" #include <jsonv/value.hpp> #include <jsonv/parse.hpp> TEST(parse_unicode_single) { std::string s = jsonv::parse("\"\\u0004\"").as_string(); ensure(s.size() == 1); ensure(s[0] == '\x04'); } TEST(parse_unicode_inline) { std::string s = jsonv::parse("\"é\"").as_string(); ensure(s.size() == 2); ensure(s[0] == '\xc3'); ensure(s[1] == '\xa9'); } TEST(parse_unicode_multi) { std::string s = jsonv::parse("\"\\u00e9\"").as_string(); ensure(s.size() == 2); ensure(s[0] == '\xc3'); ensure(s[1] == '\xa9'); } TEST(parse_unicode_insanity) { std::string s = jsonv::parse("\"\\uface\"").as_string(); ensure(s.size() == 3); // The right answer according to Python: u'\uface'.encode('utf-8') const char vals[] = "\xef\xab\x8e"; for (unsigned idx = 0; idx < 3; ++idx) ensure(s[idx] == vals[idx]); } TEST(parse_unicode_invalid_surrogates) { ensure_throws(jsonv::parse_error, jsonv::parse("\"\\udead\\ubeef\"").as_string()); } TEST(parse_unicode_invalid_surrogates_cesu8) { std::string s = jsonv::parse("\"\\udead\\ubeef\"", jsonv::parse_options().string_encoding(jsonv::parse_options::encoding::cesu8) ).as_string(); ensure(s.size() == 6); // The right answer according to Python: u'\udead\ubeef'.encode('utf-8') const char vals[] = "\xed\xba\xad\xeb\xbb\xaf"; for (unsigned idx = 0; idx < sizeof vals; ++idx) ensure(s[idx] == vals[idx]); } <|endoftext|>
<commit_before>#include "Data.h" #include <CCfits/CCfits> using namespace CCfits; Data Data::instance; Data::Data() { } // A function for reading in Kepler light curve data from a FITS file. // This uses the C++ CFITSIO interface CCfits. // See http://heasarc.gsfc.nasa.gov/docs/software/fitsio/ccfits/html/readtable.html for an example void Data::load(const char* filename) { // use the verbose mode to output any errors in reading files FITS::setVerboseMode(true); // Empty the vectors t.clear(); // the light curve time stamps in days from the first value y.clear(); // the light curve flux // set the names of the Kepler FITS file HDUs std::vector<string> hdus(3); hdus[0] = "PRIMARY"; hdus[1] = "LIGHTCURVE"; // contains the light curve data hdus[2] = "APERTURE"; // create the FITS class (false means that all data is *not* read on construction) std::auto_ptr<FITS> pInfile(new FITS(filename, Read, hdus, false)); // create a table for the LIGHTCURVE HDU ExtHDU& table = pInfile->extension(hdus[1]); long nrows = table.rows(); // number of values in the light curve // read in the times (in days in the light curve file) and make epoch from first time stamp table.column("TIME").read( t, 1, nrows ); // read from first row (1) to last for ( std::vector<double>::iterator i=t.begin(); i != t.end(); ++i ) { *i -= t[0]; } // data times step dt = t[1]; // read in the light curve data from the PDCSAP_FLUX data channel // - there are other channels available, see http://archive.stsci.edu/kepler/manuals/archive_manual.pdf table.column("PDCSAP_FLUX").read( y, 1, nrows ); // loop through light curve and remove any NaN or inf entries int j = 0, i = 0, size = y.size(); for ( i=0; i < size; i++ ){ if ( std::isnan(y[j]) || std::isinf(y[j]) ){ y.erase(y.begin()+j); t.erase(t.begin()+j); } else{ j++; } } // calculate median of the data std::vector<double> yc; yc = y; // copy of y size_t newsize = yc.size(); std::sort(yc.begin(), yc.end()); // sort for median if ( newsize % 2 == 0 ){ y_median = (yc[newsize/2 - 1] + yc[newsize/2]) / 2.; } else{ y_median = yc[newsize/2]; } // calculate the mean of the data y_mean = 0.; for ( i=0; i < (int)newsize; i++ ){ y_mean += y[i]; } y_mean /= (double)newsize; // remove the median from the data to rescale for ( i=0; i < (int)newsize; i++ ){ y[i] -= y_median; } } <commit_msg>Fixed data reading function so that NaNs do get removed<commit_after>#include "Data.h" #include <CCfits/CCfits> #include <cmath> using namespace CCfits; Data Data::instance; Data::Data() { } // A function for reading in Kepler light curve data from a FITS file. // This uses the C++ CFITSIO interface CCfits. // See http://heasarc.gsfc.nasa.gov/docs/software/fitsio/ccfits/html/readtable.html for an example void Data::load(const char* filename) { // use the verbose mode to output any errors in reading files FITS::setVerboseMode(true); // Empty the vectors t.clear(); // the light curve time stamps in days from the first value y.clear(); // the light curve flux // set the names of the Kepler FITS file HDUs std::vector<string> hdus(3); hdus[0] = "PRIMARY"; hdus[1] = "LIGHTCURVE"; // contains the light curve data hdus[2] = "APERTURE"; // create the FITS class (false means that all data is *not* read on construction) std::auto_ptr<FITS> pInfile(new FITS(filename, Read, hdus, false)); // create a table for the LIGHTCURVE HDU ExtHDU& table = pInfile->extension(hdus[1]); long nrows = table.rows(); // number of values in the light curve // read in the times (in days in the light curve file) and make epoch from first time stamp table.column("TIME").read( t, 1, nrows ); // read from first row (1) to last for ( std::vector<double>::iterator i=t.begin(); i != t.end(); ++i ) { *i -= t[0]; } // data times step dt = t[1]; // read in the light curve data from the PDCSAP_FLUX data channel // - there are other channels available, see http://archive.stsci.edu/kepler/manuals/archive_manual.pdf table.column("PDCSAP_FLUX").read( y, 1, nrows ); // loop through light curve and remove any NaN or inf entries std::vector<double>::iterator ity, itt; for (ity = y.begin(), itt = t.begin(); ity != y.end(); ){ if ( isnan(*ity) || isinf(*ity) ){ ity = y.erase(ity); itt = t.erase(itt); } else { ++ity; ++itt; } } // calculate median of the data std::vector<double> yc; yc = y; // copy of y size_t newsize = yc.size(); std::sort(yc.begin(), yc.end()); // sort for median if ( newsize % 2 == 0 ){ y_median = (yc[newsize/2 - 1] + yc[newsize/2]) / 2.; } else{ y_median = yc[newsize/2]; } // calculate the mean of the data y_mean = 0.; for ( int i=0; i < (int)newsize; i++ ){ y_mean += y[i]; } y_mean /= (double)newsize; // remove the median from the data to rescale for ( int i=0; i < (int)newsize; i++ ){ y[i] -= y_median; } } <|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-2011 Francois Beaune // // 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 "samplegeneratorjob.h" // appleseed.renderer headers. #include "renderer/kernel/rendering/progressive/samplecounter.h" #include "renderer/kernel/rendering/accumulationframebuffer.h" #include "renderer/kernel/rendering/isamplegenerator.h" #include "renderer/kernel/rendering/itilecallback.h" // Standard headers. #include <algorithm> using namespace foundation; using namespace std; namespace renderer { // // SampleGeneratorJob class implementation. // namespace { const size_t MinSampleCount = 1024 * 4; // minimum number of samples in one pass const size_t MaxSampleCount = 1024 * 64; // maximum number of samples in one pass const size_t MinSamplePassCount = 8; // number of passes that will stick to the minimum number of samples const size_t SampleIncrement = 1024 * 4; // number of samples added at each pass const bool RoundRobinRender = false; // enable/disable Round Robin rendering size_t compute_sample_count(const size_t pass) { return pass < MinSamplePassCount ? MinSampleCount : min( MinSampleCount + (pass - MinSamplePassCount) * SampleIncrement, MaxSampleCount); } } SampleGeneratorJob::SampleGeneratorJob( Frame& frame, AccumulationFramebuffer& framebuffer, ISampleGenerator* sample_generator, SampleCounter& sample_counter, ITileCallback* tile_callback, JobQueue& job_queue, const size_t job_index, const size_t job_count, const size_t pass, AbortSwitch& abort_switch) : m_frame(frame) , m_framebuffer(framebuffer) , m_sample_generator(sample_generator) , m_sample_counter(sample_counter) , m_tile_callback(tile_callback) , m_job_queue(job_queue) , m_job_index(job_index) , m_job_count(job_count) , m_pass(pass) , m_abort_switch(abort_switch) { } void SampleGeneratorJob::execute(const size_t thread_index) { const size_t sample_count = m_sample_counter.reserve(compute_sample_count(m_pass)); if (sample_count == 0) return; if (m_tile_callback) { m_tile_callback->pre_render( 0, 0, m_framebuffer.get_width(), m_framebuffer.get_height()); } m_sample_generator->generate_samples( sample_count, m_framebuffer, m_abort_switch); if (!RoundRobinRender || m_pass % m_job_count == m_job_index) m_framebuffer.render_to_frame(m_frame); if (m_tile_callback) m_tile_callback->post_render(m_frame); if (!m_abort_switch.is_aborted()) { m_job_queue.schedule( new SampleGeneratorJob( m_frame, m_framebuffer, m_sample_generator, m_sample_counter, m_tile_callback, m_job_queue, m_job_index, m_job_count, m_pass + 1, m_abort_switch)); } } } // namespace renderer <commit_msg>tweaked the distribution of samples over rendering passes in the progressive renderer, and fixed a minor bug.<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-2011 Francois Beaune // // 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 "samplegeneratorjob.h" // appleseed.renderer headers. #include "renderer/kernel/rendering/progressive/samplecounter.h" #include "renderer/kernel/rendering/accumulationframebuffer.h" #include "renderer/kernel/rendering/isamplegenerator.h" #include "renderer/kernel/rendering/itilecallback.h" // Standard headers. #include <algorithm> using namespace foundation; using namespace std; namespace renderer { // // SampleGeneratorJob class implementation. // namespace { const size_t MinSampleCount = 1024 * 4; // minimum number of samples in one pass const size_t MaxSampleCount = 1024 * 128; // maximum number of samples in one pass const size_t MinSamplePassCount = 6; // number of passes that will stick to the minimum number of samples const size_t SampleIncrement = 1024 * 8; // number of samples added at each pass const bool RoundRobinRender = false; // enable/disable Round Robin rendering size_t compute_sample_count(const size_t pass) { return pass < MinSamplePassCount ? MinSampleCount : min( MinSampleCount + (pass - MinSamplePassCount + 1) * SampleIncrement, MaxSampleCount); } } SampleGeneratorJob::SampleGeneratorJob( Frame& frame, AccumulationFramebuffer& framebuffer, ISampleGenerator* sample_generator, SampleCounter& sample_counter, ITileCallback* tile_callback, JobQueue& job_queue, const size_t job_index, const size_t job_count, const size_t pass, AbortSwitch& abort_switch) : m_frame(frame) , m_framebuffer(framebuffer) , m_sample_generator(sample_generator) , m_sample_counter(sample_counter) , m_tile_callback(tile_callback) , m_job_queue(job_queue) , m_job_index(job_index) , m_job_count(job_count) , m_pass(pass) , m_abort_switch(abort_switch) { } void SampleGeneratorJob::execute(const size_t thread_index) { const size_t sample_count = m_sample_counter.reserve(compute_sample_count(m_pass)); if (sample_count == 0) return; if (m_tile_callback) { m_tile_callback->pre_render( 0, 0, m_framebuffer.get_width(), m_framebuffer.get_height()); } m_sample_generator->generate_samples( sample_count, m_framebuffer, m_abort_switch); if (!RoundRobinRender || m_pass % m_job_count == m_job_index) m_framebuffer.render_to_frame(m_frame); if (m_tile_callback) m_tile_callback->post_render(m_frame); if (!m_abort_switch.is_aborted()) { m_job_queue.schedule( new SampleGeneratorJob( m_frame, m_framebuffer, m_sample_generator, m_sample_counter, m_tile_callback, m_job_queue, m_job_index, m_job_count, m_pass + 1, m_abort_switch)); } } } // namespace renderer <|endoftext|>
<commit_before>/******************************************************************************* The MIT License (MIT) Copyright (c) 2013, 2014 JCube001 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 <math.h> #include "marg_filter.h" #include "quaternion.h" MARGFilter::MARGFilter() : Filter(), Eb_hat(Quaternion(0.0f, 1.0f, 0.0f, 0.0f)), Sw_b(Quaternion()), zeta(1.0f) { } void MARGFilter::setGyroDriftGain(const float drift) { zeta = sqrt(3.0f / 4.0f) * drift; } void MARGFilter::update(float wx, float wy, float wz, float ax, float ay, float az, float mx, float my, float mz) { // Auxiliary variables to avoid repeated calculations const Quaternion two_SEq = 2.0f * SEq_hat; // Compute the magnetic flux in the earth frame const Quaternion Eh_hat = SEq_hat * Sm_hat * SEq_hat.conjugate(); // Normalize the magnetic flux vector to have only x and z components Eb_hat = Quaternion(0.0f, sqrt((Eh_hat.x * Eh_hat.x) + (Eh_hat.y * Eh_hat.y)), 0.0f, Eh_hat.z); // Compute the gravity objective function const Quaternion f_g = SEq_hat.conjugate() * Eg_hat * SEq_hat - Quaternion(0.0f, ax, ay, az).normalized(); // Compute the gravity Jacobian matrix // TODO // Compute the magnetic field objective function const Quaternion Sm_hat = Quaternion(0.0f, mx, my, mz).normalized(); const Quaternion f_b = SEq_hat.conjugate() * Eb_hat * SEq_hat - Sm_hat; // Compute the magnetic field Jacobian matrix // TODO // Compute the normalized gradient descent (matrix multiplication) // TODO const Quaternion SEq_hat_dot = Quaternion().normalized; // Compute the angular estimated direction of gyroscope error then compute // and remove the gyroscope biases while computing the quaternion // derivative measured by the gyroscope Sw_b += zeta * (two_SEq.conjugate() * SEq_hat_dot) * deltaTime; const Quaternion SEq_dot_omega = 0.5f * SEq_hat * (Quaternion(0.0f, wx, wy, wz) - Sw_b); // Compute then integrate the estimated quaternion derivative SEq_hat += (SEq_dot_omega - (beta * SEq_hat_dot)) * deltaTime; // Normalize the output quaternion SEq_hat.normalize(); } <commit_msg>Implemented the rest of the MARG filter<commit_after>/******************************************************************************* The MIT License (MIT) Copyright (c) 2013, 2014 JCube001 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 <math.h> #include "marg_filter.h" #include "quaternion.h" MARGFilter::MARGFilter() : Filter(), Eb_hat(Quaternion(0.0f, 1.0f, 0.0f, 0.0f)), Sw_b(Quaternion()), zeta(1.0f) { } void MARGFilter::setGyroDriftGain(const float drift) { zeta = sqrt(3.0f / 4.0f) * drift; } void MARGFilter::update(float wx, float wy, float wz, float ax, float ay, float az, float mx, float my, float mz) { // Auxiliary variables to avoid repeated calculations const Quaternion two_SEq = 2.0f * SEq_hat; const Quaternion two_Eb = 2.0f * Eb_hat; const Quaternion two_Eb_x_SEq = two_Eb.x * SEq_hat; const Quaternion two_Eb_z_SEq = two_Eb.z * SEq_hat; // Compute the gravity objective function const Quaternion f_g = SEq_hat.conjugate() * Eg_hat * SEq_hat - Quaternion(0.0f, ax, ay, az).normalized(); // Compute the gravity Jacobian matrix // Negative elements are negated in matrix multiplication const float J_11_or_24 = two_SEq.y; const float J_12_or_23 = two_SEq.z; const float J_13_or_22 = two_SEq.w; const float J_14_or_21 = two_SEq.x; const float J_32 = 2.0f * J_14_or_21; const float J_33 = 2.0f * J_11_or_24; // Compute the magnetic field objective function const Quaternion Sm_hat = Quaternion(0.0f, mx, my, mz).normalized(); const Quaternion f_b = SEq_hat.conjugate() * Eb_hat * SEq_hat - Sm_hat; // Compute the magnetic field Jacobian matrix // Negative elements are negated in matrix multiplication const float J_41 = two_Eb_z_SEq.y; const float J_42 = two_Eb_z_SEq.z; const float J_43 = 2.0f * two_Eb_x_SEq.y + two_Eb_z_SEq.w; const float J_44 = 2.0f * two_Eb_x_SEq.z - two_Eb_z_SEq.x; const float J_51 = two_Eb_x_SEq.z - two_Eb_z_SEq.x; const float J_52 = two_Eb_x_SEq.y + two_Eb_z_SEq.w; const float J_53 = two_Eb_x_SEq.x + two_Eb_z_SEq.z; const float J_54 = two_Eb_x_SEq.w - two_Eb_z_SEq.y; const float J_61 = two_Eb_x_SEq.y; const float J_62 = two_Eb_x_SEq.z - 2.0f * two_Eb_z_SEq.x; const float J_63 = two_Eb_x_SEq.w - 2.0f * two_Eb_z_SEq.y; const float J_64 = two_Eb_x_SEq.x; // Compute the normalized gradient descent (matrix multiplication) const Quaternion SEq_hat_dot = Quaternion(J_14_or_21 * f_g.y - J_11_or_24 * f_g.x - J_41 * f_b.x - J_51 * f_b.y + J_61 * f_b.z, J_12_or_23 * f_g.x + J_13_or_22 * f_g.y - J_32 * f_g.z + J_42 * f_b.x + J_52 * f_b.y + J_62 * f_b.z, J_12_or_23 * f_g.y - J_33 * f_g.z - J_13_or_22 * f_g.x - J_43 * f_b.x + J_53 * f_b.y + J_63 * f_b.z, J_14_or_21 * f_g.x + J_11_or_24 * f_g.y - J_44 * f_b.x - J_54 * f_b.y + J_64 * f_b.z).normalized(); // Compute the angular estimated direction of gyroscope error then compute // and remove the gyroscope biases while computing the quaternion // derivative measured by the gyroscope Sw_b += zeta * (two_SEq.conjugate() * SEq_hat_dot) * deltaTime; const Quaternion SEq_dot_omega = 0.5f * SEq_hat * (Quaternion(0.0f, wx, wy, wz) - Sw_b); // Compute then integrate the estimated quaternion derivative SEq_hat += (SEq_dot_omega - (beta * SEq_hat_dot)) * deltaTime; // Normalize the output quaternion SEq_hat.normalize(); // Compute the magnetic flux in the earth frame const Quaternion Eh_hat = SEq_hat * Sm_hat * SEq_hat.conjugate(); // Normalize the magnetic flux vector to have only x and z components Eb_hat = Quaternion(0.0f, sqrt((Eh_hat.x * Eh_hat.x) + (Eh_hat.y * Eh_hat.y)), 0.0f, Eh_hat.z); } <|endoftext|>
<commit_before>#include "webcam.hpp" #include <chrono> using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } unsigned long long getMilliseconds() { return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1); } void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = ellipticKernel(factor); if (diler) { erode(downsample, downsample, kernel); } else { dilate(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } unsigned long long times[100]; int f = 0; for (int i=0; i<100; i++) times[i] = 0; ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; unsigned long long timenow = getMilliseconds(); while (keepGoing) { image = cvQueryFrame(capture); times[0] += getMilliseconds() - timenow; timenow = getMilliseconds(); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray, blurred_img; cvtColor(image, gray, CV_RGB2GRAY); blur(image, blurred_img, Size(50,50)); times[1] += getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask filters out areas with too many edges // removed for now; it didn't generalize well /* Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); imshow("canny mask", gray.mul(canny)); */ // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; absdiff(blurred_img, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); morphFast(flow); threshold(flow, flow, 60, 1, THRESH_BINARY); // imshow("flow mask", gray.mul(flow)); times[2] += getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark; equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); // imshow("dark mask", gray.mul(kindofdark)); times[3] += getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask gets rid of anything far away from red stuff // did not work well and was slow /* Mat notlips; Mat channels[3]; split(image, channels); channels[2].convertTo(notlips, CV_32FC1); divide(notlips, gray, notlips, 1, CV_32FC1); //equalistHist is horrible for a red background //equalizeHist(notlips, notlips); threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY); notlips.convertTo(notlips, CV_8UC1); imshow("lip mask", notlips*255); Mat otherMorph = notlips.clone(); int tx = tracker1+1-(tracker1%2); if (tx<3) tx=1; if (tx>90) tx=91; morphFast(notlips, 100, tx, 0, 0); int ty = tracker2+1-(tracker2%2); if (ty<3) ty=1; if (ty>90) ty=91; morphFast(notlips, 100, ty, 0, 1); imshow("lips2", notlips.mul(gray)); morphFast(otherMorph, 100, tx, 0, 1); morphFast(otherMorph, 100, tx, 0, 0); imshow("lips3", otherMorph.mul(gray)); waitKey(1); */ Mat mask = flow.mul(kindofdark); // open the mask Mat smallMask0, smallMask1; resize(mask, smallMask0, Size(width/5,height/5)); Mat smallKernel = ellipticKernel(69,79); erode(smallMask0, smallMask1, smallKernel); dilate(smallMask1, smallMask1, smallKernel); bitwise_and(smallMask0, smallMask1, smallMask1); resize(smallMask1, mask, Size(width, height)); // imshow("morph mask", gray.mul(mask)); times[4] += getMilliseconds() - timenow; timenow = getMilliseconds(); // update background with new morph mask // average what we know is background with prior background // dilate it first since we really want to be sure it's bg /* // actually dilation is slow and our current mask is already // really nice :) Mat dilatedMask; dilate(smallMask1, dilatedMask, smallKernel); resize(dilatedMask, dilatedMask, Size(width, height)); imshow("erosion", dilatedMask.mul(gray)); */ Mat mask_; subtract(1, mask ,mask_); Mat mask3, mask3_; channel[0] = mask; channel[1] = mask; channel[2] = mask; merge(channel, 3, mask3); channel[0] = mask_; channel[1] = mask_; channel[2] = mask_; merge(channel, 3, mask3_); background = background.mul(mask3) + (background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2); times[5] += getMilliseconds() - timenow; timenow = getMilliseconds(); // imshow("background", background); /* Moments lol = moments(gray, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("leimage", image); */ CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; int scale = 3; Mat classifyThis; equalizeHist(gray, gray);//ew; watch out not to use this later resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale)); // bilateralFilter(gray, classifyThis, 15, 10, 1); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE); Mat rectImage(width, height, CV_8UC1, Scalar(0)); for (size_t i=0; i<mouths.size(); i++) { Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale); // rectangle(image, scaled, Scalar(255,0,0)); // rectangle(rectImage, scaled, Scalar(1), 5); } // blur(rectImage, rectImage, Size(tracker2+1,tracker2+1)); // threshold(rectImage, rectImage, tracker1, 1, THRESH_BINARY); times[6] += getMilliseconds() - timenow; timenow = getMilliseconds(); imshow("MOUTH", gray.mul(rectImage)); for (int i=0; i<7; i++) { printf("%llu , ", times[i]); times[i] = 0; } printf("\n"); keepGoing = (waitKey(1)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" #include <chrono> using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } unsigned long long getMilliseconds() { return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1); } void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = ellipticKernel(factor); if (diler) { erode(downsample, downsample, kernel); } else { dilate(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } unsigned long long times[100]; int f = 0; for (int i=0; i<100; i++) times[i] = 0; ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; unsigned long long timenow = getMilliseconds(); while (keepGoing) { image = cvQueryFrame(capture); times[0] += getMilliseconds() - timenow; timenow = getMilliseconds(); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray, blurred_img; cvtColor(image, gray, CV_RGB2GRAY); blur(image, blurred_img, Size(50,50)); times[1] += getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask filters out areas with too many edges // removed for now; it didn't generalize well /* Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); imshow("canny mask", gray.mul(canny)); */ // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; absdiff(blurred_img, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); morphFast(flow); threshold(flow, flow, 60, 1, THRESH_BINARY); // imshow("flow mask", gray.mul(flow)); times[2] += getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark; equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); // imshow("dark mask", gray.mul(kindofdark)); times[3] += getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask gets rid of anything far away from red stuff // did not work well and was slow /* Mat notlips; Mat channels[3]; split(image, channels); channels[2].convertTo(notlips, CV_32FC1); divide(notlips, gray, notlips, 1, CV_32FC1); //equalistHist is horrible for a red background //equalizeHist(notlips, notlips); threshold(notlips, notlips, tracker3/30.0, 1, THRESH_BINARY); notlips.convertTo(notlips, CV_8UC1); imshow("lip mask", notlips*255); Mat otherMorph = notlips.clone(); int tx = tracker1+1-(tracker1%2); if (tx<3) tx=1; if (tx>90) tx=91; morphFast(notlips, 100, tx, 0, 0); int ty = tracker2+1-(tracker2%2); if (ty<3) ty=1; if (ty>90) ty=91; morphFast(notlips, 100, ty, 0, 1); imshow("lips2", notlips.mul(gray)); morphFast(otherMorph, 100, tx, 0, 1); morphFast(otherMorph, 100, tx, 0, 0); imshow("lips3", otherMorph.mul(gray)); waitKey(1); */ Mat mask = flow.mul(kindofdark); // open the mask Mat smallMask0, smallMask1; resize(mask, smallMask0, Size(width/5,height/5)); Mat smallKernel = ellipticKernel(69,79); erode(smallMask0, smallMask1, smallKernel); dilate(smallMask1, smallMask1, smallKernel); bitwise_and(smallMask0, smallMask1, smallMask1); resize(smallMask1, mask, Size(width, height)); // imshow("morph mask", gray.mul(mask)); times[4] += getMilliseconds() - timenow; timenow = getMilliseconds(); // update background with new morph mask // average what we know is background with prior background // dilate it first since we really want to be sure it's bg /* // actually dilation is slow and our current mask is already // really nice :) Mat dilatedMask; dilate(smallMask1, dilatedMask, smallKernel); resize(dilatedMask, dilatedMask, Size(width, height)); imshow("erosion", dilatedMask.mul(gray)); */ Mat mask_; subtract(1, mask ,mask_); Mat mask3, mask3_; channel[0] = mask; channel[1] = mask; channel[2] = mask; merge(channel, 3, mask3); channel[0] = mask_; channel[1] = mask_; channel[2] = mask_; merge(channel, 3, mask3_); background = background.mul(mask3) + (background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2); times[5] += getMilliseconds() - timenow; timenow = getMilliseconds(); // imshow("background", background); /* Moments lol = moments(gray, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("leimage", image); */ CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; int scale = 3; Mat classifyThis; equalizeHist(gray, gray);//ew; watch out not to use this later resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale)); // bilateralFilter(gray, classifyThis, 15, 10, 1); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE); Mat rectImage(width, height, CV_8UC1, Scalar(0)); for (size_t i=0; i<mouths.size(); i++) { Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale); rectangle(image, scaled, Scalar(255,0,0)); rectangle(rectImage, scaled, Scalar(1), 5); } // blur(rectImage, rectImage, Size(tracker2+1,tracker2+1)); threshold(rectImage, rectImage, tracker1, 1, THRESH_BINARY); times[6] += getMilliseconds() - timenow; timenow = getMilliseconds(); imshow("MOUTH", rectImage); for (int i=0; i<7; i++) { printf("%llu , ", times[i]); times[i] = 0; } printf("\n"); keepGoing = (waitKey(1)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // Copyright 2010 Bastian Holst <bastianholst@gmx.de> // #include "MarbleThemeSelectView.h" #include "global.h" #include "MarbleDirs.h" #include "MapWizard.h" #include "MarbleDebug.h" #include <QtCore/QFileInfo> #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QDateTime> #include <QtCore/QModelIndex> #include <QtGui/QResizeEvent> #include <QtGui/QMenu> #include <QtGui/QMessageBox> #include <QtGui/QStandardItemModel> using namespace Marble; class MarbleThemeSelectView::Private { public: explicit Private( MarbleThemeSelectView * const parent ); void deleteDirectory( const QString& path ); void deleteDataDirectories( const QString& path ); void deletePreview( const QString& path ); QString currentThemeName(); QString currentThemePath(); private: MarbleThemeSelectView *m_parent; }; MarbleThemeSelectView::Private::Private( MarbleThemeSelectView * const parent ) : m_parent( parent ) { } void MarbleThemeSelectView::Private::deleteDirectory( const QString& path ) { QDir directory( path ); foreach( QString filename, directory.entryList( QDir::Files | QDir::NoDotAndDotDot ) ) QFile( path + filename ).remove(); QDir().rmdir( path ); } void MarbleThemeSelectView::Private::deleteDataDirectories( const QString& path ) { QDir directoryv( path ); foreach( QString filename, directoryv.entryList( QDir::AllEntries | QDir::NoDotAndDotDot ) ) { QString filepath = path + "/" + filename; QFile file( filepath ); if( QFileInfo( filepath ).isDir() && filename.contains( QRegExp( "^[0-9]+$" ) ) ) { deleteDataDirectories( filepath ); QDir().rmdir( filepath ); } else if( filename.contains( QRegExp( "^[0-9]\\..+" ) ) ) file.remove(); } } void MarbleThemeSelectView::Private::deletePreview( const QString& path ) { QDir directoryv( path, "preview.*" ); foreach( QString filename, directoryv.entryList() ) QFile( path + "/" + filename ).remove(); } QString MarbleThemeSelectView::Private::currentThemeName() { QModelIndex index = m_parent->currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 0, QModelIndex() ); return ( model->data( columnIndex )).toString(); } QString MarbleThemeSelectView::Private::currentThemePath() { QModelIndex index = m_parent-> currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() ); return ( model->data( columnIndex )).toString(); } MarbleThemeSelectView::MarbleThemeSelectView(QWidget *parent) : QListView( parent ), m_settings( "kde.org", "Marble Desktop Globe" ), d( new Private( this ) ) { bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen; if ( smallScreen ) { setViewMode( QListView::ListMode ); setIconSize( QSize( 64, 64 ) ); } else { setViewMode( QListView::IconMode ); setIconSize( QSize( 136, 136 ) ); setFlow( QListView::LeftToRight ); setWrapping( true ); setResizeMode( QListView::Fixed ); setUniformItemSizes( true ); } setMovement( QListView::Static ); setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); setEditTriggers( QAbstractItemView::NoEditTriggers ); setSelectionMode( QAbstractItemView::SingleSelection ); loadFavorites(); connect( this, SIGNAL( activated( QModelIndex ) ), SLOT( selectedMapTheme( QModelIndex ) ) ); connect( this, SIGNAL( customContextMenuRequested( QPoint ) ), SLOT( showContextMenu( QPoint ) ) ); } MarbleThemeSelectView::~MarbleThemeSelectView() { delete d; } void MarbleThemeSelectView::resizeEvent( QResizeEvent *event ) { QListView::resizeEvent(event); QSize size = gridSize(); size.setWidth( event->size().width() ); setGridSize(size); } void MarbleThemeSelectView::selectedMapTheme( QModelIndex index ) { const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() ); QString currentmaptheme = ( model->data( columnIndex )).toString(); mDebug() << currentmaptheme; emit selectMapTheme( currentmaptheme ); } void MarbleThemeSelectView::mapWizard() { emit showMapWizard(); } void MarbleThemeSelectView::uploadDialog() { emit showUploadDialog(); } void MarbleThemeSelectView::showContextMenu( const QPoint& pos ) { QMenu menu; menu.addAction( "&Create a New Map...", this, SLOT( mapWizard() ) ); if( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath() ).exists() ) menu.addAction( tr( "&Delete Map Theme" ), this, SLOT( deleteMap() ) ); menu.addAction( tr( "&Upload Map..." ), this, SLOT( uploadDialog() ) ); QAction *favAction = menu.addAction( tr( "&Favorite" ), this, SLOT( toggleFavorite() ) ); favAction->setCheckable( true ); if( currentIsFavorite() ) favAction->setChecked( true ); else favAction->setChecked( false ); menu.exec( mapToGlobal( pos ) ); } void MarbleThemeSelectView::deleteMap() { if(QMessageBox::warning( this, tr( "Marble" ), tr( "Are you sure that you want to delete \"%1\"?" ).arg( d->currentThemeName() ), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes ) { QDir mapthemedir( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).path()); d->deleteDirectory( mapthemedir.path() + "/legend/" ); d->deleteDataDirectories( mapthemedir.path() + "/" ); d->deletePreview( mapthemedir.path() + "/" ); QFile( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).remove(); QFile( mapthemedir.path() + "/legend.html" ).remove(); QDir().rmdir( mapthemedir.path() ); } } void MarbleThemeSelectView::toggleFavorite() { QModelIndex index = currentIndex(); QAbstractItemModel *model = this->model(); QModelIndex columnIndex = model->index( index.row(), 0 ); if( currentIsFavorite() ) { m_settings.beginGroup( "Favorites" ); m_settings.remove( model->data( columnIndex ).toString() ); } else { m_settings.beginGroup( "Favorites" ); m_settings.setValue( model->data( columnIndex ).toString(), QDateTime::currentDateTime() ); } m_settings.endGroup(); model->sort( 0 ); } void MarbleThemeSelectView::loadFavorites() { m_settings.beginGroup( "Favorites" ); if( !m_settings.contains( "initialized" ) ) { m_settings.setValue( "initialized", true ); QDateTime currentDateTime = QDateTime::currentDateTime(); m_settings.setValue( "Atlas", currentDateTime ); m_settings.setValue( "OpenStreetMap", currentDateTime ); m_settings.setValue( "Satellite View", currentDateTime ); } m_settings.endGroup(); } bool MarbleThemeSelectView::currentIsFavorite() { QModelIndex index = currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex nameIndex = model->index( index.row(), 0, QModelIndex() ); m_settings.beginGroup( "Favorites" ); bool favorite = m_settings.contains( model->data( nameIndex ).toString() ); m_settings.endGroup(); return favorite; } #include "MarbleThemeSelectView.moc" <commit_msg>Use the activate signal only on Maemo, old behavior elsewhere.<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // Copyright 2010 Bastian Holst <bastianholst@gmx.de> // #include "MarbleThemeSelectView.h" #include "global.h" #include "MarbleDirs.h" #include "MapWizard.h" #include "MarbleDebug.h" #include <QtCore/QFileInfo> #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QDateTime> #include <QtCore/QModelIndex> #include <QtGui/QResizeEvent> #include <QtGui/QMenu> #include <QtGui/QMessageBox> #include <QtGui/QStandardItemModel> using namespace Marble; class MarbleThemeSelectView::Private { public: explicit Private( MarbleThemeSelectView * const parent ); void deleteDirectory( const QString& path ); void deleteDataDirectories( const QString& path ); void deletePreview( const QString& path ); QString currentThemeName(); QString currentThemePath(); private: MarbleThemeSelectView *m_parent; }; MarbleThemeSelectView::Private::Private( MarbleThemeSelectView * const parent ) : m_parent( parent ) { } void MarbleThemeSelectView::Private::deleteDirectory( const QString& path ) { QDir directory( path ); foreach( QString filename, directory.entryList( QDir::Files | QDir::NoDotAndDotDot ) ) QFile( path + filename ).remove(); QDir().rmdir( path ); } void MarbleThemeSelectView::Private::deleteDataDirectories( const QString& path ) { QDir directoryv( path ); foreach( QString filename, directoryv.entryList( QDir::AllEntries | QDir::NoDotAndDotDot ) ) { QString filepath = path + "/" + filename; QFile file( filepath ); if( QFileInfo( filepath ).isDir() && filename.contains( QRegExp( "^[0-9]+$" ) ) ) { deleteDataDirectories( filepath ); QDir().rmdir( filepath ); } else if( filename.contains( QRegExp( "^[0-9]\\..+" ) ) ) file.remove(); } } void MarbleThemeSelectView::Private::deletePreview( const QString& path ) { QDir directoryv( path, "preview.*" ); foreach( QString filename, directoryv.entryList() ) QFile( path + "/" + filename ).remove(); } QString MarbleThemeSelectView::Private::currentThemeName() { QModelIndex index = m_parent->currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 0, QModelIndex() ); return ( model->data( columnIndex )).toString(); } QString MarbleThemeSelectView::Private::currentThemePath() { QModelIndex index = m_parent-> currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() ); return ( model->data( columnIndex )).toString(); } MarbleThemeSelectView::MarbleThemeSelectView(QWidget *parent) : QListView( parent ), m_settings( "kde.org", "Marble Desktop Globe" ), d( new Private( this ) ) { bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen; if ( smallScreen ) { setViewMode( QListView::ListMode ); setIconSize( QSize( 64, 64 ) ); } else { setViewMode( QListView::IconMode ); setIconSize( QSize( 136, 136 ) ); setFlow( QListView::LeftToRight ); setWrapping( true ); setResizeMode( QListView::Fixed ); setUniformItemSizes( true ); } setMovement( QListView::Static ); setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); setEditTriggers( QAbstractItemView::NoEditTriggers ); setSelectionMode( QAbstractItemView::SingleSelection ); loadFavorites(); #ifdef Q_WS_MAEMO_5 // The pressed signal on Maemo interfers with touch-based // scrolling, leading to sluggish behavior connect( this, SIGNAL( activated( QModelIndex ) ), SLOT( selectedMapTheme( QModelIndex ) ) ); #else // Q_WS_MAEMO_5 connect( this, SIGNAL( pressed( QModelIndex ) ), SLOT( selectedMapTheme( QModelIndex ) ) ); #endif // Q_WS_MAEMO_5 connect( this, SIGNAL( customContextMenuRequested( QPoint ) ), SLOT( showContextMenu( QPoint ) ) ); } MarbleThemeSelectView::~MarbleThemeSelectView() { delete d; } void MarbleThemeSelectView::resizeEvent( QResizeEvent *event ) { QListView::resizeEvent(event); QSize size = gridSize(); size.setWidth( event->size().width() ); setGridSize(size); } void MarbleThemeSelectView::selectedMapTheme( QModelIndex index ) { const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() ); QString currentmaptheme = ( model->data( columnIndex )).toString(); mDebug() << currentmaptheme; emit selectMapTheme( currentmaptheme ); } void MarbleThemeSelectView::mapWizard() { emit showMapWizard(); } void MarbleThemeSelectView::uploadDialog() { emit showUploadDialog(); } void MarbleThemeSelectView::showContextMenu( const QPoint& pos ) { QMenu menu; menu.addAction( "&Create a New Map...", this, SLOT( mapWizard() ) ); if( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath() ).exists() ) menu.addAction( tr( "&Delete Map Theme" ), this, SLOT( deleteMap() ) ); menu.addAction( tr( "&Upload Map..." ), this, SLOT( uploadDialog() ) ); QAction *favAction = menu.addAction( tr( "&Favorite" ), this, SLOT( toggleFavorite() ) ); favAction->setCheckable( true ); if( currentIsFavorite() ) favAction->setChecked( true ); else favAction->setChecked( false ); menu.exec( mapToGlobal( pos ) ); } void MarbleThemeSelectView::deleteMap() { if(QMessageBox::warning( this, tr( "Marble" ), tr( "Are you sure that you want to delete \"%1\"?" ).arg( d->currentThemeName() ), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes ) { QDir mapthemedir( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).path()); d->deleteDirectory( mapthemedir.path() + "/legend/" ); d->deleteDataDirectories( mapthemedir.path() + "/" ); d->deletePreview( mapthemedir.path() + "/" ); QFile( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).remove(); QFile( mapthemedir.path() + "/legend.html" ).remove(); QDir().rmdir( mapthemedir.path() ); } } void MarbleThemeSelectView::toggleFavorite() { QModelIndex index = currentIndex(); QAbstractItemModel *model = this->model(); QModelIndex columnIndex = model->index( index.row(), 0 ); if( currentIsFavorite() ) { m_settings.beginGroup( "Favorites" ); m_settings.remove( model->data( columnIndex ).toString() ); } else { m_settings.beginGroup( "Favorites" ); m_settings.setValue( model->data( columnIndex ).toString(), QDateTime::currentDateTime() ); } m_settings.endGroup(); model->sort( 0 ); } void MarbleThemeSelectView::loadFavorites() { m_settings.beginGroup( "Favorites" ); if( !m_settings.contains( "initialized" ) ) { m_settings.setValue( "initialized", true ); QDateTime currentDateTime = QDateTime::currentDateTime(); m_settings.setValue( "Atlas", currentDateTime ); m_settings.setValue( "OpenStreetMap", currentDateTime ); m_settings.setValue( "Satellite View", currentDateTime ); } m_settings.endGroup(); } bool MarbleThemeSelectView::currentIsFavorite() { QModelIndex index = currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex nameIndex = model->index( index.row(), 0, QModelIndex() ); m_settings.beginGroup( "Favorites" ); bool favorite = m_settings.contains( model->data( nameIndex ).toString() ); m_settings.endGroup(); return favorite; } #include "MarbleThemeSelectView.moc" <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtSystems module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativevaluespacepublishermetaobject_p.h" QT_BEGIN_NAMESPACE QDeclarativeValueSpacePublisherMetaObject::QDeclarativeValueSpacePublisherMetaObject(QDeclarativeValueSpacePublisher *parent) : metaObject(0) , object(parent) { metaObjectBuilder.setSuperClass(parent->metaObject()); metaObjectBuilder.setClassName(parent->metaObject()->className()); metaObjectBuilder.setFlags(QMetaObjectBuilder::DynamicMetaObject); metaObject = metaObjectBuilder.toMetaObject(); signalOffset = metaObject->methodOffset(); propertyOffset = metaObject->propertyCount(); d = metaObject->d; } QDeclarativeValueSpacePublisherMetaObject::~QDeclarativeValueSpacePublisherMetaObject() { qFree(metaObject); } int QDeclarativeValueSpacePublisherMetaObject::createProperty(const char *name, const char *type) { int id = metaObjectBuilder.propertyCount(); metaObjectBuilder.addSignal("__" + QByteArray::number(id) + "()"); metaObjectBuilder.addProperty(name, type, id); qFree(metaObject); metaObject = metaObjectBuilder.toMetaObject(); d = metaObject->d; dynamicProperties.insert(id, QPair<QString, QVariant>(QString::fromUtf8(name), QVariant())); return propertyOffset + id; } int QDeclarativeValueSpacePublisherMetaObject::metaCall(QMetaObject::Call c, int id, void **a) { if ((c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty) && id >= propertyOffset) { if (c == QMetaObject::ReadProperty) { *reinterpret_cast<QVariant*>(a[0]) = dynamicProperties[id - propertyOffset].second; } else if (c == QMetaObject::WriteProperty) { dynamicProperties[id - propertyOffset].second = *reinterpret_cast<QVariant*>(a[0]); activate(object, signalOffset + id, 0); } return -1; } else { return object->qt_metacall(c, id, a); } } QT_END_NAMESPACE <commit_msg>qFree is deprecated, use ::free instead.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtSystems module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativevaluespacepublishermetaobject_p.h" QT_BEGIN_NAMESPACE QDeclarativeValueSpacePublisherMetaObject::QDeclarativeValueSpacePublisherMetaObject(QDeclarativeValueSpacePublisher *parent) : metaObject(0) , object(parent) { metaObjectBuilder.setSuperClass(parent->metaObject()); metaObjectBuilder.setClassName(parent->metaObject()->className()); metaObjectBuilder.setFlags(QMetaObjectBuilder::DynamicMetaObject); metaObject = metaObjectBuilder.toMetaObject(); signalOffset = metaObject->methodOffset(); propertyOffset = metaObject->propertyCount(); d = metaObject->d; } QDeclarativeValueSpacePublisherMetaObject::~QDeclarativeValueSpacePublisherMetaObject() { ::free(metaObject); } int QDeclarativeValueSpacePublisherMetaObject::createProperty(const char *name, const char *type) { int id = metaObjectBuilder.propertyCount(); metaObjectBuilder.addSignal("__" + QByteArray::number(id) + "()"); metaObjectBuilder.addProperty(name, type, id); ::free(metaObject); metaObject = metaObjectBuilder.toMetaObject(); d = metaObject->d; dynamicProperties.insert(id, QPair<QString, QVariant>(QString::fromUtf8(name), QVariant())); return propertyOffset + id; } int QDeclarativeValueSpacePublisherMetaObject::metaCall(QMetaObject::Call c, int id, void **a) { if ((c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty) && id >= propertyOffset) { if (c == QMetaObject::ReadProperty) { *reinterpret_cast<QVariant*>(a[0]) = dynamicProperties[id - propertyOffset].second; } else if (c == QMetaObject::WriteProperty) { dynamicProperties[id - propertyOffset].second = *reinterpret_cast<QVariant*>(a[0]); activate(object, signalOffset + id, 0); } return -1; } else { return object->qt_metacall(c, id, a); } } QT_END_NAMESPACE <|endoftext|>
<commit_before>#include "Chunk.h" #include "DataBuffer.h" #include <algorithm> namespace Minecraft { Chunk::Chunk() { for (s32 y = 0; y < 16; ++y) { for (s32 z = 0; z < 16; ++z) { for (s32 x = 0; x < 16; ++x) { std::size_t index = y * 16 * 16 + z * 16 + x; m_Blocks[index] = BlockRegistry::GetInstance()->GetBlock(0, 0); } } } } void Chunk::Load(DataBuffer& in, ChunkColumnMetadata* meta, s32 chunkIndex) { for (s32 y = 0; y < 16; ++y) { for (s32 z = 0; z < 16; ++z) { for (s32 x = 0; x < 16; ++x) { s16 data; in >> data; std::reverse((u8*)&data, (u8*)&data + sizeof(s16)); std::size_t index = y * 16 * 16 + z * 16 + x; m_Blocks[index] = BlockRegistry::GetInstance()->GetBlock(data); } } } } BlockPtr Chunk::GetBlock(Vector3i chunkPosition) { if (chunkPosition.y < 0) return BlockRegistry::GetInstance()->GetBlock(0, 0); std::size_t index = (std::size_t)(chunkPosition.y * 16 * 16 + chunkPosition.z * 16 + chunkPosition.x); return m_Blocks[index]; } void Chunk::SetBlock(Vector3i chunkPosition, BlockPtr block) { std::size_t index = (std::size_t)(chunkPosition.y * 16 * 16 + chunkPosition.z * 16 + chunkPosition.x); m_Blocks[index] = block; } ChunkColumn::ChunkColumn(ChunkColumnMetadata metadata) : m_Metadata(metadata) { for (std::size_t i = 0; i < m_Chunks.size(); ++i) m_Chunks[i] = nullptr; } BlockPtr ChunkColumn::GetBlock(Vector3i position) { s32 chunkIndex = (s32)(position.y / 16); Vector3i relativePosition(position.x, position.y % 16, position.z); if (!m_Chunks[chunkIndex]) return nullptr; return m_Chunks[chunkIndex]->GetBlock(relativePosition); } DataBuffer& operator>>(DataBuffer& in, ChunkColumn& column) { ChunkColumnMetadata* meta = &column.m_Metadata; for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) { // The section mask says whether or not there is data in this chunk. if (meta->sectionmask & (1 << i)) { column.m_Chunks[i] = std::make_shared<Chunk>(); column.m_Chunks[i]->Load(in, meta, i); } else { // Air section, leave null column.m_Chunks[i] = nullptr; } } static const s64 lightSize = 16 * 16 * 16 / 2; for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) { // Block light data if (meta->sectionmask & (1 << i)) in.SetReadOffset(in.GetReadOffset() + lightSize); } if (meta->skylight) { for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) { // Skylight data if (meta->sectionmask & (1 << i)) in.SetReadOffset(in.GetReadOffset() + lightSize); } } if (meta->continuous) in.SetReadOffset(in.GetReadOffset() + 256); return in; } } // ns Minecraft <commit_msg>Fix GetBlock on null chunks in a valid ChunkColumn<commit_after>#include "Chunk.h" #include "DataBuffer.h" #include <algorithm> namespace Minecraft { Chunk::Chunk() { for (s32 y = 0; y < 16; ++y) { for (s32 z = 0; z < 16; ++z) { for (s32 x = 0; x < 16; ++x) { std::size_t index = y * 16 * 16 + z * 16 + x; m_Blocks[index] = BlockRegistry::GetInstance()->GetBlock(0, 0); } } } } void Chunk::Load(DataBuffer& in, ChunkColumnMetadata* meta, s32 chunkIndex) { for (s32 y = 0; y < 16; ++y) { for (s32 z = 0; z < 16; ++z) { for (s32 x = 0; x < 16; ++x) { s16 data; in >> data; std::reverse((u8*)&data, (u8*)&data + sizeof(s16)); std::size_t index = y * 16 * 16 + z * 16 + x; m_Blocks[index] = BlockRegistry::GetInstance()->GetBlock(data); } } } } BlockPtr Chunk::GetBlock(Vector3i chunkPosition) { if (chunkPosition.y < 0) return BlockRegistry::GetInstance()->GetBlock(0, 0); std::size_t index = (std::size_t)(chunkPosition.y * 16 * 16 + chunkPosition.z * 16 + chunkPosition.x); return m_Blocks[index]; } void Chunk::SetBlock(Vector3i chunkPosition, BlockPtr block) { std::size_t index = (std::size_t)(chunkPosition.y * 16 * 16 + chunkPosition.z * 16 + chunkPosition.x); m_Blocks[index] = block; } ChunkColumn::ChunkColumn(ChunkColumnMetadata metadata) : m_Metadata(metadata) { for (std::size_t i = 0; i < m_Chunks.size(); ++i) m_Chunks[i] = nullptr; } BlockPtr ChunkColumn::GetBlock(Vector3i position) { s32 chunkIndex = (s32)(position.y / 16); Vector3i relativePosition(position.x, position.y % 16, position.z); if (!m_Chunks[chunkIndex]) return BlockRegistry::GetInstance()->GetBlock(0, 0); return m_Chunks[chunkIndex]->GetBlock(relativePosition); } DataBuffer& operator>>(DataBuffer& in, ChunkColumn& column) { ChunkColumnMetadata* meta = &column.m_Metadata; for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) { // The section mask says whether or not there is data in this chunk. if (meta->sectionmask & (1 << i)) { column.m_Chunks[i] = std::make_shared<Chunk>(); column.m_Chunks[i]->Load(in, meta, i); } else { // Air section, leave null column.m_Chunks[i] = nullptr; } } static const s64 lightSize = 16 * 16 * 16 / 2; for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) { // Block light data if (meta->sectionmask & (1 << i)) in.SetReadOffset(in.GetReadOffset() + lightSize); } if (meta->skylight) { for (s16 i = 0; i < ChunkColumn::ChunksPerColumn; ++i) { // Skylight data if (meta->sectionmask & (1 << i)) in.SetReadOffset(in.GetReadOffset() + lightSize); } } if (meta->continuous) in.SetReadOffset(in.GetReadOffset() + 256); return in; } } // ns Minecraft <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2005 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mediaobject.h" #include "mediaobject_p.h" #include "factory.h" #include "bytestreaminterface.h" #include "mediaobjectinterface.h" #include <kdebug.h> #define PHONON_CLASSNAME MediaObject #define PHONON_INTERFACENAME MediaObjectInterface namespace Phonon { PHONON_HEIR_IMPL( AbstractMediaProducer ) MediaObject::MediaObject( Phonon::MediaObjectPrivate& dd, QObject* parent ) : AbstractMediaProducer( dd, parent ) { } PHONON_INTERFACE_GETTER( KUrl, url, d->url ) PHONON_GETTER( qint32, aboutToFinishTime, d->aboutToFinishTime ) qint64 MediaObject::totalTime() const { K_D( const MediaObject ); if( !d->backendObject ) return -1; MediaObjectInterface *iface = qobject_cast<MediaObjectInterface*>( d->backendObject ); if( iface ) return iface->totalTime(); else { ByteStreamInterface *iface2 = qobject_cast<ByteStreamInterface*>( d->backendObject ); if( iface2 ) return iface2->totalTime(); } return -1; } qint64 MediaObject::remainingTime() const { K_D( const MediaObject ); if( !d->backendObject ) return -1; qint64 ret; if( !BACKEND_GET( qint64, ret, "remainingTime" ) ) ret = totalTime() - currentTime(); if( ret < 0 ) return -1; return ret; } void MediaObject::setUrl( const KUrl& url ) { K_D( MediaObject ); d->url = url; if( iface() ) { stop(); // first call stop as that often is the expected state // for setting a new URL INTERFACE_CALL1( setUrl, url ); //FIXME: the stateChanged signal will be emitted. Perhaps it should be //disabled for the setUrl call and then replayed when it didn't go into //ErrorState if( state() == Phonon::ErrorState ) { d->deleteIface(); //at this point MediaObject uses a ByteStream //instead and sends the data it receives from the KIO Job via writeBuffer. //This essentially makes all media frameworks read data via KIO... d->setupKioStreaming(); } } } void MediaObject::stop() { AbstractMediaProducer::stop(); K_D( MediaObject ); if( d->kiojob ) { d->kiojob->kill(); // if( do pre-buffering ) d->setupKioJob(); } } PHONON_SETTER( setAboutToFinishTime, aboutToFinishTime, qint32 ) void MediaObjectPrivate::setupKioJob() { K_Q( MediaObject ); Q_ASSERT( backendObject ); kiojob = KIO::get( url, false, false ); kiojob->addMetaData( "UserAgent", QLatin1String( "KDE Phonon" ) ); QObject::connect( kiojob, SIGNAL(data(KIO::Job*,const QByteArray&)), q, SLOT(_k_bytestreamData(KIO::Job*,const QByteArray&)) ); QObject::connect( kiojob, SIGNAL(result(KJob*)), q, SLOT(_k_bytestreamResult(KJob*)) ); QObject::connect( kiojob, SIGNAL(totalSize(KJob*, qulonglong)), q, SLOT(_k_bytestreamTotalSize(KJob*,qulonglong)) ); QObject::connect( backendObject, SIGNAL(finished()), q, SIGNAL(finished()) ); QObject::connect( backendObject, SIGNAL(aboutToFinish(qint32)), q, SIGNAL(aboutToFinish(qint32)) ); QObject::connect( backendObject, SIGNAL(length(qint64)), q, SIGNAL(length(qint64)) ); QObject::connect( backendObject, SIGNAL(needData()), q, SLOT(_k_bytestreamNeedData()) ); QObject::connect( backendObject, SIGNAL(enoughData()), q, SLOT(_k_bytestreamEnoughData()) ); pBACKEND_CALL1( "setStreamSeekable", bool, false ); //FIXME: KIO doesn't support seeking at this point //connect( backendObject, SIGNAL(seekStream(qint64)), kiojob, SLOT( } void MediaObjectPrivate::setupKioStreaming() { K_Q( MediaObject ); Q_ASSERT( backendObject == 0 ); backendObject = Factory::self()->createByteStream( q ); if( backendObject ) { QObject::connect( backendObject, SIGNAL( destroyed( QObject* ) ), q, SLOT( _k_cleanupByteStream() ) ); //setupIface for ByteStream if( kiojob ) kiojob->kill(); setupKioJob(); static_cast<AbstractMediaProducer*>( q )->setupIface(); } } void MediaObjectPrivate::_k_bytestreamNeedData() { if( kiojob->isSuspended() ) kiojob->resume(); } void MediaObjectPrivate::_k_bytestreamEnoughData() { if( !kiojob->isSuspended() ) kiojob->suspend(); } void MediaObjectPrivate::_k_bytestreamData( KIO::Job*, const QByteArray& data ) { ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject ); bs->writeData( data ); } void MediaObjectPrivate::_k_bytestreamResult( KJob* job ) { ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject ); bs->endOfData(); kiojob = 0; if( job->error() ) { //TODO } } void MediaObjectPrivate::_k_bytestreamTotalSize( KJob*, qulonglong size ) { pBACKEND_CALL1( "setStreamSize", quint64, size ); } void MediaObjectPrivate::_k_cleanupByteStream() { if( kiojob ) { kiojob->kill(); kiojob = 0; } } bool MediaObjectPrivate::aboutToDeleteIface() { //kDebug( 600 ) << k_funcinfo << endl; pBACKEND_GET( qint32, aboutToFinishTime, "aboutToFinishTime" ); return AbstractMediaProducerPrivate::aboutToDeleteIface(); } // setupIface is not called for ByteStream void MediaObject::setupIface() { K_D( MediaObject ); Q_ASSERT( d->backendObject ); //kDebug( 600 ) << k_funcinfo << endl; AbstractMediaProducer::setupIface(); connect( d->backendObject, SIGNAL( finished() ), SIGNAL( finished() ) ); connect( d->backendObject, SIGNAL( aboutToFinish( qint32 ) ), SIGNAL( aboutToFinish( qint32 ) ) ); connect( d->backendObject, SIGNAL( length( qint64 ) ), SIGNAL( length( qint64 ) ) ); // set up attributes if( !d->url.isEmpty() ) INTERFACE_CALL1( setUrl, d->url ); if( state() == Phonon::ErrorState ) { d->deleteIface(); //at this point MediaObject uses a ByteStream //instead and sends the data it receives from the KIO Job via writeBuffer. //This essentially makes all media frameworks read data via KIO... d->setupKioStreaming(); return; } BACKEND_CALL1( "setAboutToFinishTime", qint32, d->aboutToFinishTime ); } } //namespace Phonon #include "mediaobject.moc" // vim: sw=4 ts=4 tw=80 noet <commit_msg>fixed a missing check on MediaObject<commit_after>/* This file is part of the KDE project Copyright (C) 2005 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mediaobject.h" #include "mediaobject_p.h" #include "factory.h" #include "bytestreaminterface.h" #include "mediaobjectinterface.h" #include <kdebug.h> #define PHONON_CLASSNAME MediaObject #define PHONON_INTERFACENAME MediaObjectInterface namespace Phonon { PHONON_HEIR_IMPL( AbstractMediaProducer ) MediaObject::MediaObject( Phonon::MediaObjectPrivate& dd, QObject* parent ) : AbstractMediaProducer( dd, parent ) { } PHONON_INTERFACE_GETTER( KUrl, url, d->url ) PHONON_GETTER( qint32, aboutToFinishTime, d->aboutToFinishTime ) qint64 MediaObject::totalTime() const { K_D( const MediaObject ); if( !d->backendObject ) return -1; MediaObjectInterface *iface = qobject_cast<MediaObjectInterface*>( d->backendObject ); if( iface ) return iface->totalTime(); else { ByteStreamInterface *iface2 = qobject_cast<ByteStreamInterface*>( d->backendObject ); if( iface2 ) return iface2->totalTime(); } return -1; } qint64 MediaObject::remainingTime() const { K_D( const MediaObject ); if( !d->backendObject ) return -1; qint64 ret; if( !BACKEND_GET( qint64, ret, "remainingTime" ) ) ret = totalTime() - currentTime(); if( ret < 0 ) return -1; return ret; } void MediaObject::setUrl( const KUrl& url ) { K_D( MediaObject ); d->url = url; if( iface() ) { stop(); // first call stop as that often is the expected state // for setting a new URL INTERFACE_CALL1( setUrl, url ); //FIXME: the stateChanged signal will be emitted. Perhaps it should be //disabled for the setUrl call and then replayed when it didn't go into //ErrorState if( state() == Phonon::ErrorState ) { d->deleteIface(); //at this point MediaObject uses a ByteStream //instead and sends the data it receives from the KIO Job via writeBuffer. //This essentially makes all media frameworks read data via KIO... d->setupKioStreaming(); } } } void MediaObject::stop() { AbstractMediaProducer::stop(); K_D( MediaObject ); if( d->kiojob ) { d->kiojob->kill(); // if( do pre-buffering ) d->setupKioJob(); } } PHONON_SETTER( setAboutToFinishTime, aboutToFinishTime, qint32 ) void MediaObjectPrivate::setupKioJob() { K_Q( MediaObject ); Q_ASSERT( backendObject ); kiojob = KIO::get( url, false, false ); kiojob->addMetaData( "UserAgent", QLatin1String( "KDE Phonon" ) ); QObject::connect( kiojob, SIGNAL(data(KIO::Job*,const QByteArray&)), q, SLOT(_k_bytestreamData(KIO::Job*,const QByteArray&)) ); QObject::connect( kiojob, SIGNAL(result(KJob*)), q, SLOT(_k_bytestreamResult(KJob*)) ); QObject::connect( kiojob, SIGNAL(totalSize(KJob*, qulonglong)), q, SLOT(_k_bytestreamTotalSize(KJob*,qulonglong)) ); QObject::connect( backendObject, SIGNAL(finished()), q, SIGNAL(finished()) ); QObject::connect( backendObject, SIGNAL(aboutToFinish(qint32)), q, SIGNAL(aboutToFinish(qint32)) ); QObject::connect( backendObject, SIGNAL(length(qint64)), q, SIGNAL(length(qint64)) ); QObject::connect( backendObject, SIGNAL(needData()), q, SLOT(_k_bytestreamNeedData()) ); QObject::connect( backendObject, SIGNAL(enoughData()), q, SLOT(_k_bytestreamEnoughData()) ); pBACKEND_CALL1( "setStreamSeekable", bool, false ); //FIXME: KIO doesn't support seeking at this point //connect( backendObject, SIGNAL(seekStream(qint64)), kiojob, SLOT( } void MediaObjectPrivate::setupKioStreaming() { K_Q( MediaObject ); Q_ASSERT( backendObject == 0 ); backendObject = Factory::self()->createByteStream( q ); if( backendObject ) { QObject::connect( backendObject, SIGNAL( destroyed( QObject* ) ), q, SLOT( _k_cleanupByteStream() ) ); //setupIface for ByteStream if( kiojob ) kiojob->kill(); setupKioJob(); static_cast<AbstractMediaProducer*>( q )->setupIface(); } } void MediaObjectPrivate::_k_bytestreamNeedData() { if( kiojob && kiojob->isSuspended() ) kiojob->resume(); } void MediaObjectPrivate::_k_bytestreamEnoughData() { if( !kiojob->isSuspended() ) kiojob->suspend(); } void MediaObjectPrivate::_k_bytestreamData( KIO::Job*, const QByteArray& data ) { ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject ); bs->writeData( data ); } void MediaObjectPrivate::_k_bytestreamResult( KJob* job ) { ByteStreamInterface* bs = qobject_cast<ByteStreamInterface*>( backendObject ); bs->endOfData(); kiojob = 0; if( job->error() ) { //TODO } } void MediaObjectPrivate::_k_bytestreamTotalSize( KJob*, qulonglong size ) { pBACKEND_CALL1( "setStreamSize", quint64, size ); } void MediaObjectPrivate::_k_cleanupByteStream() { if( kiojob ) { kiojob->kill(); kiojob = 0; } } bool MediaObjectPrivate::aboutToDeleteIface() { //kDebug( 600 ) << k_funcinfo << endl; pBACKEND_GET( qint32, aboutToFinishTime, "aboutToFinishTime" ); return AbstractMediaProducerPrivate::aboutToDeleteIface(); } // setupIface is not called for ByteStream void MediaObject::setupIface() { K_D( MediaObject ); Q_ASSERT( d->backendObject ); //kDebug( 600 ) << k_funcinfo << endl; AbstractMediaProducer::setupIface(); connect( d->backendObject, SIGNAL( finished() ), SIGNAL( finished() ) ); connect( d->backendObject, SIGNAL( aboutToFinish( qint32 ) ), SIGNAL( aboutToFinish( qint32 ) ) ); connect( d->backendObject, SIGNAL( length( qint64 ) ), SIGNAL( length( qint64 ) ) ); // set up attributes if( !d->url.isEmpty() ) INTERFACE_CALL1( setUrl, d->url ); if( state() == Phonon::ErrorState ) { d->deleteIface(); //at this point MediaObject uses a ByteStream //instead and sends the data it receives from the KIO Job via writeBuffer. //This essentially makes all media frameworks read data via KIO... d->setupKioStreaming(); return; } BACKEND_CALL1( "setAboutToFinishTime", qint32, d->aboutToFinishTime ); } } //namespace Phonon #include "mediaobject.moc" // vim: sw=4 ts=4 tw=80 noet <|endoftext|>
<commit_before>#ifndef MGF_SCANNER_HPP #define MGF_SCANNER_HPP #if ! defined(yyFlexLexerOnce) #include <mgf/FlexLexer.hpp> #endif // Override the interface for yylex since we namespaced it #undef YY_DECL #define YY_DECL int mgf::Scanner::yylex() // Include Bison for types / tokens #include <mgf/Parser.tab.hh> namespace mgf { class Parser; //typename Parser::semantic_type; /*** * \brief The lexer that tokenize the input */ class Scanner : public yyFlexLexer { public: /** * \brief Construct from a input * \param in MGF imput */ Scanner(std::istream& in); Scanner(const Scanner&) = delete; Scanner& operator=(const Scanner&) = delete; /** * \breief save the pointer to yylval so we can change it, and invoke scanner * \parap lval For Lex/bison * \return 0if all input is parse, MGF_END_IONS if end of ion, else, error */ int yylex(mgf::Parser::semantic_type *lval); protected: private: /** * \breief Scanning function created by Flex; make this private to force usage * of the overloaded method so we can get a pointer to Bison's yylval */ int yylex(); /* yyval ptr */ mgf::Parser::semantic_type *yylval; ///< For Lex/bison }; } #endif <commit_msg>add doc to Scanner<commit_after>#ifndef MGF_SCANNER_HPP #define MGF_SCANNER_HPP #if ! defined(yyFlexLexerOnce) #include <mgf/FlexLexer.hpp> #endif // Override the interface for yylex since we namespaced it #undef YY_DECL #define YY_DECL int mgf::Scanner::yylex() // Include Bison for types / tokens #include <mgf/Parser.tab.hh> namespace mgf { class Parser; //typename Parser::semantic_type; /** * \brief The lexer that tokenize the input */ class Scanner : public yyFlexLexer { public: /** * \brief Construct from a input * \param in MGF imput */ Scanner(std::istream& in); Scanner(const Scanner&) = delete; Scanner& operator=(const Scanner&) = delete; /** * \breief save the pointer to yylval so we can change it, and invoke scanner * \parap lval For Lex/bison * \return 0if all input is parse, MGF_END_IONS if end of ion, else, error */ int yylex(mgf::Parser::semantic_type *lval); protected: private: /** * \breief Scanning function created by Flex; make this private to force usage * of the overloaded method so we can get a pointer to Bison's yylval */ int yylex(); /* yyval ptr */ mgf::Parser::semantic_type *yylval; ///< For Lex/bison }; } #endif <|endoftext|>
<commit_before>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //رϷ { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } return 0; } <commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //رϷ { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { } return 0; } <|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2008-2009 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "sidebarpage.h" #include <KDE/KDebug> #include <KDE/KInputDialog> #include <KDE/KLocale> #include <KDE/KMessageBox> #include <KJob> #include <QtGui/QVBoxLayout> #include <QtGui/QHeaderView> #include "globaldefs.h" #include "todohelpers.h" #include "todotreeview.h" #include "pimitemrelationinterface.h" SideBarPage::SideBarPage(QAbstractItemModel *model, const QList<QAction*> &contextActions, QWidget *parent) : QWidget(parent) { setLayout(new QVBoxLayout(this)); m_treeView = new TodoTreeView(this); layout()->addWidget(m_treeView); layout()->setContentsMargins(0, 0, 0, 0); m_treeView->setFocusPolicy(Qt::NoFocus); m_treeView->header()->hide(); m_treeView->setSortingEnabled(true); m_treeView->sortByColumn(0, Qt::AscendingOrder); m_treeView->setAnimated(true); m_treeView->setModel(model); m_treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_treeView->setDragEnabled(true); m_treeView->viewport()->setAcceptDrops(true); m_treeView->setDropIndicatorShown(true); m_treeView->setRootIsDecorated(false); m_treeView->setStyleSheet("QTreeView { background: transparent; border-style: none; }"); m_treeView->setCurrentIndex(m_treeView->model()->index(0, 0)); connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), m_treeView, SLOT(expand(QModelIndex))); m_treeView->setContextMenuPolicy(Qt::ActionsContextMenu); m_treeView->addActions(contextActions); } QItemSelectionModel *SideBarPage::selectionModel() const { return m_treeView->selectionModel(); } void SideBarPage::addNewItem() { QModelIndex parentItem = selectionModel()->currentIndex(); Zanshin::ItemType type = (Zanshin::ItemType) parentItem.data(Zanshin::ItemTypeRole).toInt(); QString title; QString text; if (type==Zanshin::Collection || type==Zanshin::ProjectTodo) { title = i18n("New Project"); text = i18n("Enter project name:"); } else if (type==Zanshin::CategoryRoot || type==Zanshin::Category) { title = i18n("New Context"); text = i18n("Enter context name:"); } else if (type==Zanshin::TopicRoot || type==Zanshin::Topic) { title = i18n("New Topic"); text = i18n("Enter topic name:"); } else { kFatal() << "We should never, ever, get in this case..."; } bool ok; QString summary = KInputDialog::getText(title, text, QString(), &ok, this); summary = summary.trimmed(); if (!ok || summary.isEmpty()) return; if (type==Zanshin::Collection) { Akonadi::Collection collection = parentItem.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); PimItemStructureInterface::create(PimNode::Project, summary, QList<PimNode>(), collection); } else if (type==Zanshin::ProjectTodo) { PimItemStructureInterface::create(PimNode::Project, summary, QList<PimNode>() << PimItemStructureInterface::fromIndex(parentItem)); } else if (type==Zanshin::CategoryRoot) { PimItemStructureInterface::create(PimNode::Context, summary); } else if (type==Zanshin::Category) { PimItemStructureInterface::create(PimNode::Context, summary, QList<PimNode>() << PimItemStructureInterface::fromIndex(parentItem)); } else if (type==Zanshin::TopicRoot) { PimItemStructureInterface::create(PimNode::Topic, summary); } else if (type==Zanshin::Topic) { PimItemStructureInterface::create(PimNode::Topic, summary, QList<PimNode>() << PimItemStructureInterface::fromIndex(parentItem)); } else { kFatal() << "We should never, ever, get in this case..."; } } void SideBarPage::result(KJob *job) { kDebug() << job->error() << job->errorString(); } void SideBarPage::removeCurrentItem() { QModelIndex current = selectionModel()->currentIndex(); if (!current.isValid()) { return; } PimItemStructureInterface::remove(PimItemStructureInterface::fromIndex(current), this); //TODO only if remove succeeded m_treeView->setCurrentIndex(current.parent()); } void SideBarPage::renameCurrentItem() { m_treeView->edit(selectionModel()->currentIndex()); } void SideBarPage::selectPreviousItem() { QModelIndex index = m_treeView->currentIndex(); index = m_treeView->indexAbove(index); if (index.isValid()) { m_treeView->setCurrentIndex(index); } } void SideBarPage::selectNextItem() { QModelIndex index = m_treeView->currentIndex(); m_treeView->expand(index); index = m_treeView->indexBelow(index); if (index.isValid()) { m_treeView->setCurrentIndex(index); } } <commit_msg>Create new projects in the right parent collection.<commit_after>/* This file is part of Zanshin Todo. Copyright 2008-2009 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "sidebarpage.h" #include <KDE/KDebug> #include <KDE/KInputDialog> #include <KDE/KLocale> #include <KDE/KMessageBox> #include <KJob> #include <QtGui/QVBoxLayout> #include <QtGui/QHeaderView> #include "globaldefs.h" #include "todohelpers.h" #include "todotreeview.h" #include "pimitemrelationinterface.h" SideBarPage::SideBarPage(QAbstractItemModel *model, const QList<QAction*> &contextActions, QWidget *parent) : QWidget(parent) { setLayout(new QVBoxLayout(this)); m_treeView = new TodoTreeView(this); layout()->addWidget(m_treeView); layout()->setContentsMargins(0, 0, 0, 0); m_treeView->setFocusPolicy(Qt::NoFocus); m_treeView->header()->hide(); m_treeView->setSortingEnabled(true); m_treeView->sortByColumn(0, Qt::AscendingOrder); m_treeView->setAnimated(true); m_treeView->setModel(model); m_treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_treeView->setDragEnabled(true); m_treeView->viewport()->setAcceptDrops(true); m_treeView->setDropIndicatorShown(true); m_treeView->setRootIsDecorated(false); m_treeView->setStyleSheet("QTreeView { background: transparent; border-style: none; }"); m_treeView->setCurrentIndex(m_treeView->model()->index(0, 0)); connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), m_treeView, SLOT(expand(QModelIndex))); m_treeView->setContextMenuPolicy(Qt::ActionsContextMenu); m_treeView->addActions(contextActions); } QItemSelectionModel *SideBarPage::selectionModel() const { return m_treeView->selectionModel(); } void SideBarPage::addNewItem() { QModelIndex parentItem = selectionModel()->currentIndex(); Zanshin::ItemType type = (Zanshin::ItemType) parentItem.data(Zanshin::ItemTypeRole).toInt(); QString title; QString text; if (type==Zanshin::Collection || type==Zanshin::ProjectTodo) { title = i18n("New Project"); text = i18n("Enter project name:"); } else if (type==Zanshin::CategoryRoot || type==Zanshin::Category) { title = i18n("New Context"); text = i18n("Enter context name:"); } else if (type==Zanshin::TopicRoot || type==Zanshin::Topic) { title = i18n("New Topic"); text = i18n("Enter topic name:"); } else { kFatal() << "We should never, ever, get in this case..."; } bool ok; QString summary = KInputDialog::getText(title, text, QString(), &ok, this); summary = summary.trimmed(); if (!ok || summary.isEmpty()) return; if (type==Zanshin::Collection) { Akonadi::Collection collection = parentItem.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); PimItemStructureInterface::create(PimNode::Project, summary, QList<PimNode>(), collection); } else if (type==Zanshin::ProjectTodo) { Akonadi::Collection collection = parentItem.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>(); PimItemStructureInterface::create(PimNode::Project, summary, QList<PimNode>() << PimItemStructureInterface::fromIndex(parentItem), collection); } else if (type==Zanshin::CategoryRoot) { PimItemStructureInterface::create(PimNode::Context, summary); } else if (type==Zanshin::Category) { PimItemStructureInterface::create(PimNode::Context, summary, QList<PimNode>() << PimItemStructureInterface::fromIndex(parentItem)); } else if (type==Zanshin::TopicRoot) { PimItemStructureInterface::create(PimNode::Topic, summary); } else if (type==Zanshin::Topic) { PimItemStructureInterface::create(PimNode::Topic, summary, QList<PimNode>() << PimItemStructureInterface::fromIndex(parentItem)); } else { kFatal() << "We should never, ever, get in this case..."; } } void SideBarPage::result(KJob *job) { kDebug() << job->error() << job->errorString(); } void SideBarPage::removeCurrentItem() { QModelIndex current = selectionModel()->currentIndex(); if (!current.isValid()) { return; } PimItemStructureInterface::remove(PimItemStructureInterface::fromIndex(current), this); //TODO only if remove succeeded m_treeView->setCurrentIndex(current.parent()); } void SideBarPage::renameCurrentItem() { m_treeView->edit(selectionModel()->currentIndex()); } void SideBarPage::selectPreviousItem() { QModelIndex index = m_treeView->currentIndex(); index = m_treeView->indexAbove(index); if (index.isValid()) { m_treeView->setCurrentIndex(index); } } void SideBarPage::selectNextItem() { QModelIndex index = m_treeView->currentIndex(); m_treeView->expand(index); index = m_treeView->indexBelow(index); if (index.isValid()) { m_treeView->setCurrentIndex(index); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2004 The Regents of The University of Michigan * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black * Ali Saidi * Nathan Binkert */ //The purpose of this file is to provide endainness conversion utility //functions. Depending on the endianness of the guest system, either //the LittleEndianGuest or BigEndianGuest namespace is used. #ifndef __SIM_BYTE_SWAP_HH__ #define __SIM_BYTE_SWAP_HH__ #include "base/misc.hh" #include "sim/host.hh" // This lets us figure out what the byte order of the host system is #if defined(linux) #include <endian.h> // If this is a linux system, lets used the optimized definitions if they exist. // If one doesn't exist, we pretty much get what is listed below, so it all // works out #include <byteswap.h> #elif defined (__sun__) #include <sys/isa_defs.h> #else #include <machine/endian.h> #endif #if defined(__APPLE__) #include <libkern/OSByteOrder.h> #endif //These functions actually perform the swapping for parameters //of various bit lengths static inline uint64_t swap_byte64(uint64_t x) { #if defined(linux) return bswap_64(x); #elif defined(__APPLE__) return OSSwapInt64(x); #else return (uint64_t)((((uint64_t)(x) & 0xff) << 56) | ((uint64_t)(x) & 0xff00ULL) << 40 | ((uint64_t)(x) & 0xff0000ULL) << 24 | ((uint64_t)(x) & 0xff000000ULL) << 8 | ((uint64_t)(x) & 0xff00000000ULL) >> 8 | ((uint64_t)(x) & 0xff0000000000ULL) >> 24 | ((uint64_t)(x) & 0xff000000000000ULL) >> 40 | ((uint64_t)(x) & 0xff00000000000000ULL) >> 56) ; #endif } static inline uint32_t swap_byte32(uint32_t x) { #if defined(linux) return bswap_32(x); #elif defined(__APPLE__) return OSSwapInt32(x); #else return (uint32_t)(((uint32_t)(x) & 0xff) << 24 | ((uint32_t)(x) & 0xff00) << 8 | ((uint32_t)(x) & 0xff0000) >> 8 | ((uint32_t)(x) & 0xff000000) >> 24); #endif } static inline uint16_t swap_byte16(uint16_t x) { #if defined(linux) return bswap_16(x); #elif defined(__APPLE__) return OSSwapInt16(x); #else return (uint16_t)(((uint16_t)(x) & 0xff) << 8 | ((uint16_t)(x) & 0xff00) >> 8); #endif } // This function lets the compiler figure out how to call the // swap_byte functions above for different data types. Since the // sizeof() values are known at compiel time, it should inline to a // direct call to the right swap_byteNN() function. template <typename T> static inline T swap_byte(T x) { if (sizeof(T) == 8) return swap_byte64((uint64_t)x); else if (sizeof(T) == 4) return swap_byte32((uint32_t)x); else if (sizeof(T) == 2) return swap_byte16((uint16_t)x); else if (sizeof(T) == 1) return x; else panic("Can't byte-swap values larger than 64 bits"); } //The conversion functions with fixed endianness on both ends don't need to //be in a namespace template <typename T> static inline T betole(T value) {return swap_byte(value);} template <typename T> static inline T letobe(T value) {return swap_byte(value);} //For conversions not involving the guest system, we can define the functions //conditionally based on the BYTE_ORDER macro and outside of the namespaces #if defined(_BIG_ENDIAN) || BYTE_ORDER == BIG_ENDIAN template <typename T> static inline T htole(T value) {return swap_byte(value);} template <typename T> static inline T letoh(T value) {return swap_byte(value);} template <typename T> static inline T htobe(T value) {return value;} template <typename T> static inline T betoh(T value) {return value;} #elif defined(_LITTLE_ENDIAN) || BYTE_ORDER == LITTLE_ENDIAN template <typename T> static inline T htole(T value) {return value;} template <typename T> static inline T letoh(T value) {return value;} template <typename T> static inline T htobe(T value) {return swap_byte(value);} template <typename T> static inline T betoh(T value) {return swap_byte(value);} #else #error Invalid Endianess #endif namespace BigEndianGuest { template <typename T> static inline T gtole(T value) {return betole(value);} template <typename T> static inline T letog(T value) {return letobe(value);} template <typename T> static inline T gtobe(T value) {return value;} template <typename T> static inline T betog(T value) {return value;} template <typename T> static inline T htog(T value) {return htobe(value);} template <typename T> static inline T gtoh(T value) {return betoh(value);} } namespace LittleEndianGuest { template <typename T> static inline T gtole(T value) {return value;} template <typename T> static inline T letog(T value) {return value;} template <typename T> static inline T gtobe(T value) {return letobe(value);} template <typename T> static inline T betog(T value) {return betole(value);} template <typename T> static inline T htog(T value) {return htole(value);} template <typename T> static inline T gtoh(T value) {return letoh(value);} } #endif // __SIM_BYTE_SWAP_HH__ <commit_msg>fix compiling on x86/Solaris<commit_after>/* * Copyright (c) 2004 The Regents of The University of Michigan * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black * Ali Saidi * Nathan Binkert */ //The purpose of this file is to provide endainness conversion utility //functions. Depending on the endianness of the guest system, either //the LittleEndianGuest or BigEndianGuest namespace is used. #ifndef __SIM_BYTE_SWAP_HH__ #define __SIM_BYTE_SWAP_HH__ #include "base/misc.hh" #include "sim/host.hh" // This lets us figure out what the byte order of the host system is #if defined(linux) #include <endian.h> // If this is a linux system, lets used the optimized definitions if they exist. // If one doesn't exist, we pretty much get what is listed below, so it all // works out #include <byteswap.h> #elif defined (__sun__) #include <sys/isa_defs.h> #else #include <machine/endian.h> #endif #if defined(__APPLE__) #include <libkern/OSByteOrder.h> #endif //These functions actually perform the swapping for parameters //of various bit lengths static inline uint64_t swap_byte64(uint64_t x) { #if defined(linux) return bswap_64(x); #elif defined(__APPLE__) return OSSwapInt64(x); #else return (uint64_t)((((uint64_t)(x) & 0xff) << 56) | ((uint64_t)(x) & 0xff00ULL) << 40 | ((uint64_t)(x) & 0xff0000ULL) << 24 | ((uint64_t)(x) & 0xff000000ULL) << 8 | ((uint64_t)(x) & 0xff00000000ULL) >> 8 | ((uint64_t)(x) & 0xff0000000000ULL) >> 24 | ((uint64_t)(x) & 0xff000000000000ULL) >> 40 | ((uint64_t)(x) & 0xff00000000000000ULL) >> 56) ; #endif } static inline uint32_t swap_byte32(uint32_t x) { #if defined(linux) return bswap_32(x); #elif defined(__APPLE__) return OSSwapInt32(x); #else return (uint32_t)(((uint32_t)(x) & 0xff) << 24 | ((uint32_t)(x) & 0xff00) << 8 | ((uint32_t)(x) & 0xff0000) >> 8 | ((uint32_t)(x) & 0xff000000) >> 24); #endif } static inline uint16_t swap_byte16(uint16_t x) { #if defined(linux) return bswap_16(x); #elif defined(__APPLE__) return OSSwapInt16(x); #else return (uint16_t)(((uint16_t)(x) & 0xff) << 8 | ((uint16_t)(x) & 0xff00) >> 8); #endif } // This function lets the compiler figure out how to call the // swap_byte functions above for different data types. Since the // sizeof() values are known at compiel time, it should inline to a // direct call to the right swap_byteNN() function. template <typename T> static inline T swap_byte(T x) { if (sizeof(T) == 8) return swap_byte64((uint64_t)x); else if (sizeof(T) == 4) return swap_byte32((uint32_t)x); else if (sizeof(T) == 2) return swap_byte16((uint16_t)x); else if (sizeof(T) == 1) return x; else panic("Can't byte-swap values larger than 64 bits"); } //The conversion functions with fixed endianness on both ends don't need to //be in a namespace template <typename T> static inline T betole(T value) {return swap_byte(value);} template <typename T> static inline T letobe(T value) {return swap_byte(value);} //For conversions not involving the guest system, we can define the functions //conditionally based on the BYTE_ORDER macro and outside of the namespaces #if defined(_BIG_ENDIAN) || !defined(_LITTLE_ENDIAN) && BYTE_ORDER == BIG_ENDIAN template <typename T> static inline T htole(T value) {return swap_byte(value);} template <typename T> static inline T letoh(T value) {return swap_byte(value);} template <typename T> static inline T htobe(T value) {return value;} template <typename T> static inline T betoh(T value) {return value;} #elif defined(_LITTLE_ENDIAN) || BYTE_ORDER == LITTLE_ENDIAN template <typename T> static inline T htole(T value) {return value;} template <typename T> static inline T letoh(T value) {return value;} template <typename T> static inline T htobe(T value) {return swap_byte(value);} template <typename T> static inline T betoh(T value) {return swap_byte(value);} #else #error Invalid Endianess #endif namespace BigEndianGuest { template <typename T> static inline T gtole(T value) {return betole(value);} template <typename T> static inline T letog(T value) {return letobe(value);} template <typename T> static inline T gtobe(T value) {return value;} template <typename T> static inline T betog(T value) {return value;} template <typename T> static inline T htog(T value) {return htobe(value);} template <typename T> static inline T gtoh(T value) {return betoh(value);} } namespace LittleEndianGuest { template <typename T> static inline T gtole(T value) {return value;} template <typename T> static inline T letog(T value) {return value;} template <typename T> static inline T gtobe(T value) {return letobe(value);} template <typename T> static inline T betog(T value) {return betole(value);} template <typename T> static inline T htog(T value) {return htole(value);} template <typename T> static inline T gtoh(T value) {return letoh(value);} } #endif // __SIM_BYTE_SWAP_HH__ <|endoftext|>
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER 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. * * WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>. */ // // This file gets processed by doxygen and ends up as the main page in index.html. // Do not put code here, just comments for doxyen that don't seem to fit elsewhere. // /** *************************************************************** @mainpage @section Introduction The watcher system is composed of three components: a number of test node daemons, a watcher daemon instance, @section Build @subsection Dependencies The watcher relies on a bunch of stuff, they are here: @ref WatcherDependencies. @subsection Instructions The watcher system is built using auto-tools. @section Components @subsection Test Node Daemons @ref sendColorMessage @ref sendConnectivityMessage @ref sendGPSMessage @subpage watcherd "Watcher Daemon" @subsection GUIs @subsubsection Legacy Watcher @subsubsection Watcher3d @section About Point of contact: Geoff Lawler <geoff.lawler@cobham.com> ** **********************************************************************/ /** @namespace libconfig * The libconfig namespace is the namespace in the third party library libconfig++, which the watcher system uses for reading and writing cfg files */ /** @namespace log4cxx * The namespace for the third party library log4cxx which the watcher uses to do all its logging. */ /** * @page UsersGuide * @section TOC * <h3>Table of Contents</h3> * @section Modules * Module Descriptions * @section HowTo * How to do stuff * @section Glossary * Glossary of Terms * @section Index */ /** * @page WatcherDependencies * * @section ThirdParty * * @li libconfig 1.3.1 * * the system uses this for creating, reading, and writing to configuration ("cfg") files. * * @li log4cxx 0.10.0, which depends on lib apr 1.3.3 and lib apr util 1.3.4 * * This is used for all logging. * * @li boost 1.38 * * C++ library used more many things: serialization, network code, regular expressions, etc. * * @li qt 4.3 * * Used in the GUI for window frames, GUI widgets, mouse and keyboard handling, etc. * * @li sqlite 3 * * This is the database used in the watcher daemon. * * @li qwt-5.1.1 * * A small Qt-based library used to draw the 2d scrolling graphs in the watcher . * * @section Internal * * @li libwatcherutil * * Holds a few things that most components need, like parsing command line args to get to the cfg file. * * @li liblogger * * A small wrapper around log4cxx to abstract which logging library we use. * * @li libwatcher * * The core of the watcher messaging system, the watcher APIs between test node daemons, a watcher daemon, and the GUI(s)s. * * */ <commit_msg>point people to the ./src/doc directory for the User's Guide.<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER 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. * * WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>. */ // // This file gets processed by doxygen and ends up as the main page in index.html. // Do not put code here, just comments for doxyen that don't seem to fit elsewhere. // /** *************************************************************** @mainpage @section Introduction The watcher system is composed of three components: a number of test node daemons, a watcher daemon instance, @section Build @subsection Dependencies The watcher relies on a bunch of stuff, they are here: @ref WatcherDependencies. @subsection Instructions The watcher system is built using auto-tools. @section Components @subsection Test Node Daemons @ref sendColorMessage @ref sendConnectivityMessage @ref sendGPSMessage @subpage watcherd "Watcher Daemon" @subsection GUIs @subsubsection Legacy Watcher @subsubsection Watcher3d @section About Point of contact: Geoff Lawler <geoff.lawler@cobham.com> ** **********************************************************************/ /** @namespace libconfig * The libconfig namespace is the namespace in the third party library libconfig++, which the watcher system uses for reading and writing cfg files */ /** @namespace log4cxx * The namespace for the third party library log4cxx which the watcher uses to do all its logging. */ /** * @page UsersGuide * The User's Guide can be built by doing a 'make' in the ./src/doc directory. */ /** * @page WatcherDependencies * * @section ThirdParty * * @li libconfig 1.3.1 * * the system uses this for creating, reading, and writing to configuration ("cfg") files. * * @li log4cxx 0.10.0, which depends on lib apr 1.3.3 and lib apr util 1.3.4 * * This is used for all logging. * * @li boost 1.38 * * C++ library used more many things: serialization, network code, regular expressions, etc. * * @li qt 4.3 * * Used in the GUI for window frames, GUI widgets, mouse and keyboard handling, etc. * * @li sqlite 3 * * This is the database used in the watcher daemon. * * @li qwt-5.1.1 * * A small Qt-based library used to draw the 2d scrolling graphs in the watcher . * * @section Internal * * @li libwatcherutil * * Holds a few things that most components need, like parsing command line args to get to the cfg file. * * @li liblogger * * A small wrapper around log4cxx to abstract which logging library we use. * * @li libwatcher * * The core of the watcher messaging system, the watcher APIs between test node daemons, a watcher daemon, and the GUI(s)s. * * */ <|endoftext|>
<commit_before>// Copyright 2017 The Minimal Configuration Manager Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "luacat/main.h" #include <unistd.h> #include <fcntl.h> #include "kj/debug.h" #include "kj/exception.h" #include "capnp/serialize.h" extern "C" { #include "lauxlib.h" #include "lualib.h" } #include "luacat/convert.h" #include "luacat/lib.h" #include "luacat/path.h" namespace mcm { namespace luacat { namespace { const luaL_Reg loadedlibs[] = { {"_G", luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, {LUA_COLIBNAME, luaopen_coroutine}, {LUA_TABLIBNAME, luaopen_table}, {LUA_STRLIBNAME, luaopen_string}, {LUA_MATHLIBNAME, luaopen_math}, {LUA_UTF8LIBNAME, luaopen_utf8}, {NULL, NULL} }; bool isValidLuaInclude(const kj::ArrayPtr<const char> path) { for (char c: path) { if (c == '?') { return true; } } return false; } int printfunc(lua_State *state) { // Customized implementation of print(). // We could customize this in vendored copy, but this keeps the // application/vendored code separation clean. auto& stream = *reinterpret_cast<kj::OutputStream*>(lua_touserdata(state, lua_upvalueindex(1))); int n = lua_gettop(state); // number of arguments int i; lua_getglobal(state, "tostring"); for (i = 1; i <= n; i++) { const char *s; size_t l; lua_pushvalue(state, -1); // function to be called lua_pushvalue(state, i); // value to print lua_call(state, 1, 1); s = lua_tolstring(state, -1, &l); // get result if (s == NULL) { return luaL_error(state, "'tostring' must return a string to 'print'"); } if (i > 1) { stream.write("\t", 1); } stream.write(s, l); lua_pop(state, 1); // pop result } stream.write("\n", 1); return 0; } } // namespace Main::Main(kj::ProcessContext& context, kj::OutputStream& outStream, kj::OutputStream& logStream): context(context), outStream(&outStream), logStream(logStream) { } void Main::setFallbackIncludePath(kj::StringPtr include) { if (include.size() == 0) { fallbackInclude = kj::heapString(include); return; } auto parts = splitStr(include, ';'); kj::StringTree cleaned; for (auto part: parts) { if (!isValidLuaInclude(part)) { continue; } if (cleaned.size() > 0) { cleaned = kj::strTree(kj::mv(cleaned), ";"); } cleaned = kj::strTree(kj::mv(cleaned), part); } fallbackInclude = cleaned.flatten(); } kj::MainBuilder::Validity Main::addIncludePath(kj::StringPtr include) { auto parts = splitStr(include, ';'); for (auto part: parts) { if (!isValidLuaInclude(part)) { return kj::str("path '", part, "' does not include a '?' wildcard"); } } if (includes.size() == 0) { includes = kj::strTree(include); return true; } includes = kj::strTree(kj::mv(includes), ";", include); return true; } kj::MainBuilder::Validity Main::setOutputPath(kj::StringPtr outPath) { int fd; KJ_SYSCALL(fd = open(outPath.cStr(), O_WRONLY | O_CREAT | O_TRUNC, 0666), outPath); kj::AutoCloseFd autoclose(fd); ownOutStream = kj::heap<kj::FdOutputStream>(kj::mv(autoclose)); outStream = ownOutStream; return true; } kj::MainBuilder::Validity Main::processFile(kj::StringPtr src) { if (src.size() == 0) { return kj::str("empty source"); } auto chunkName = kj::str("@", src); auto maybeExc = kj::runCatchingExceptions([&]() { int fd; KJ_SYSCALL(fd = open(src.cStr(), O_RDONLY, 0), src); kj::AutoCloseFd afd(fd); kj::FdInputStream stream(kj::mv(afd)); capnp::MallocMessageBuilder message; process(message, chunkName, stream); capnp::writeMessage(*outStream, message); }); KJ_IF_MAYBE(e, maybeExc) { context.error(e->getDescription()); } return true; } void Main::process(capnp::MessageBuilder& message, kj::StringPtr chunkName, kj::InputStream& stream) { auto state = newLuaState(); // Load libraries const luaL_Reg *reg; for (reg = loadedlibs; reg->func; reg++) { luaL_requiref(state, reg->name, reg->func, 1); lua_pop(state, 1); // remove lib } LibState libState; openlib(state, libState); // push mcm module lua_setglobal(state, "mcm"); // _G.mcm = module // Override print function. lua_getglobal(state, "_G"); lua_pushlightuserdata(state, &logStream); lua_pushcclosure(state, printfunc, 1); lua_setfield(state, -2, "print"); lua_pop(state, 1); // Set package.path { auto inc = buildIncludePath(chunkName); lua_getglobal(state, "package"); pushLua(state, inc); lua_setfield(state, -2, "path"); lua_pop(state, 1); } // Run script if (luaLoad(state, chunkName, stream) || lua_pcall(state, 0, 0, 0)) { auto errMsg = kj::heapString(luaStringPtr(state, -1)); lua_pop(state, 1); throw kj::Exception(kj::Exception::Type::FAILED, __FILE__, __LINE__, kj::mv(errMsg)); } // Create catalog auto catalog = message.initRoot<Catalog>(); auto resources = libState.getResources(); auto rlist = catalog.initResources(resources.size()); // TODO(soon): sort for (size_t i = 0; i < resources.size(); i++) { rlist.setWithCaveats(i, resources[i].get()); } } kj::String Main::buildIncludePath(kj::StringPtr chunkName) { kj::StringTree tree; if (chunkName.startsWith("@")) { // Actual file name; add containing directory. auto srcDir = dirName(chunkName.slice(1)); tree = kj::strTree(joinPath(srcDir, "?.lua"), ";", joinPath(srcDir, "?", "init.lua")); } if (includes.size() > 0) { if (tree.size() > 0) { tree = kj::strTree(kj::mv(tree), ";"); } tree = kj::strTree(kj::mv(tree), includes.flatten()); } if (fallbackInclude.size() > 0) { if (tree.size() > 0) { tree = kj::strTree(kj::mv(tree), ";"); } tree = kj::strTree(kj::mv(tree), fallbackInclude); } return tree.flatten(); } kj::MainFunc Main::getMain() { return kj::MainBuilder(context, "mcm-luacat", "Interprets Lua source and generates an mcm catalog.") .addOptionWithArg({'I'}, KJ_BIND_METHOD(*this, addIncludePath), "<templates>", "Add a package path template in package.searchpath format.") .addOptionWithArg({'o'}, KJ_BIND_METHOD(*this, setOutputPath), "FILE", "Write output to FILE instead of stdout.") .expectArg("FILE", KJ_BIND_METHOD(*this, processFile)) .build(); } OwnState newLuaState() { // TODO(someday): use lua_newstate and set atpanic lua_State* state = luaL_newstate(); KJ_ASSERT_NONNULL(state); return OwnState(state); } } // namespace luacat } // namespace mcm <commit_msg>luacat: add tty output error<commit_after>// Copyright 2017 The Minimal Configuration Manager Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "luacat/main.h" #include <unistd.h> #include <fcntl.h> #include "kj/debug.h" #include "kj/exception.h" #include "capnp/serialize.h" extern "C" { #include "lauxlib.h" #include "lualib.h" } #include "luacat/convert.h" #include "luacat/lib.h" #include "luacat/path.h" namespace mcm { namespace luacat { namespace { const luaL_Reg loadedlibs[] = { {"_G", luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, {LUA_COLIBNAME, luaopen_coroutine}, {LUA_TABLIBNAME, luaopen_table}, {LUA_STRLIBNAME, luaopen_string}, {LUA_MATHLIBNAME, luaopen_math}, {LUA_UTF8LIBNAME, luaopen_utf8}, {NULL, NULL} }; bool isValidLuaInclude(const kj::ArrayPtr<const char> path) { for (char c: path) { if (c == '?') { return true; } } return false; } int printfunc(lua_State *state) { // Customized implementation of print(). // We could customize this in vendored copy, but this keeps the // application/vendored code separation clean. auto& stream = *reinterpret_cast<kj::OutputStream*>(lua_touserdata(state, lua_upvalueindex(1))); int n = lua_gettop(state); // number of arguments int i; lua_getglobal(state, "tostring"); for (i = 1; i <= n; i++) { const char *s; size_t l; lua_pushvalue(state, -1); // function to be called lua_pushvalue(state, i); // value to print lua_call(state, 1, 1); s = lua_tolstring(state, -1, &l); // get result if (s == NULL) { return luaL_error(state, "'tostring' must return a string to 'print'"); } if (i > 1) { stream.write("\t", 1); } stream.write(s, l); lua_pop(state, 1); // pop result } stream.write("\n", 1); return 0; } } // namespace Main::Main(kj::ProcessContext& context, kj::OutputStream& outStream, kj::OutputStream& logStream): context(context), outStream(&outStream), logStream(logStream) { } void Main::setFallbackIncludePath(kj::StringPtr include) { if (include.size() == 0) { fallbackInclude = kj::heapString(include); return; } auto parts = splitStr(include, ';'); kj::StringTree cleaned; for (auto part: parts) { if (!isValidLuaInclude(part)) { continue; } if (cleaned.size() > 0) { cleaned = kj::strTree(kj::mv(cleaned), ";"); } cleaned = kj::strTree(kj::mv(cleaned), part); } fallbackInclude = cleaned.flatten(); } kj::MainBuilder::Validity Main::addIncludePath(kj::StringPtr include) { auto parts = splitStr(include, ';'); for (auto part: parts) { if (!isValidLuaInclude(part)) { return kj::str("path '", part, "' does not include a '?' wildcard"); } } if (includes.size() == 0) { includes = kj::strTree(include); return true; } includes = kj::strTree(kj::mv(includes), ";", include); return true; } kj::MainBuilder::Validity Main::setOutputPath(kj::StringPtr outPath) { int fd; KJ_SYSCALL(fd = open(outPath.cStr(), O_WRONLY | O_CREAT | O_TRUNC, 0666), outPath); kj::AutoCloseFd autoclose(fd); ownOutStream = kj::heap<kj::FdOutputStream>(kj::mv(autoclose)); outStream = ownOutStream; return true; } kj::MainBuilder::Validity Main::processFile(kj::StringPtr src) { if (src.size() == 0) { return kj::str("empty source"); } auto maybeFdStream = kj::dynamicDowncastIfAvailable<kj::FdOutputStream, kj::OutputStream>(*outStream); KJ_IF_MAYBE(f, maybeFdStream) { if (isatty(f->getFd())) { context.exitError("mcm-luacat: output file is a tty\n\nWriting a binary catalog will likely mess up your terminal. Either\nredirect stdout or use -o."); } } auto chunkName = kj::str("@", src); auto maybeExc = kj::runCatchingExceptions([&]() { int fd; KJ_SYSCALL(fd = open(src.cStr(), O_RDONLY, 0), src); kj::AutoCloseFd afd(fd); kj::FdInputStream stream(kj::mv(afd)); capnp::MallocMessageBuilder message; process(message, chunkName, stream); capnp::writeMessage(*outStream, message); }); KJ_IF_MAYBE(e, maybeExc) { context.error(e->getDescription()); } return true; } void Main::process(capnp::MessageBuilder& message, kj::StringPtr chunkName, kj::InputStream& stream) { auto state = newLuaState(); // Load libraries const luaL_Reg *reg; for (reg = loadedlibs; reg->func; reg++) { luaL_requiref(state, reg->name, reg->func, 1); lua_pop(state, 1); // remove lib } LibState libState; openlib(state, libState); // push mcm module lua_setglobal(state, "mcm"); // _G.mcm = module // Override print function. lua_getglobal(state, "_G"); lua_pushlightuserdata(state, &logStream); lua_pushcclosure(state, printfunc, 1); lua_setfield(state, -2, "print"); lua_pop(state, 1); // Set package.path { auto inc = buildIncludePath(chunkName); lua_getglobal(state, "package"); pushLua(state, inc); lua_setfield(state, -2, "path"); lua_pop(state, 1); } // Run script if (luaLoad(state, chunkName, stream) || lua_pcall(state, 0, 0, 0)) { auto errMsg = kj::heapString(luaStringPtr(state, -1)); lua_pop(state, 1); throw kj::Exception(kj::Exception::Type::FAILED, __FILE__, __LINE__, kj::mv(errMsg)); } // Create catalog auto catalog = message.initRoot<Catalog>(); auto resources = libState.getResources(); auto rlist = catalog.initResources(resources.size()); // TODO(soon): sort for (size_t i = 0; i < resources.size(); i++) { rlist.setWithCaveats(i, resources[i].get()); } } kj::String Main::buildIncludePath(kj::StringPtr chunkName) { kj::StringTree tree; if (chunkName.startsWith("@")) { // Actual file name; add containing directory. auto srcDir = dirName(chunkName.slice(1)); tree = kj::strTree(joinPath(srcDir, "?.lua"), ";", joinPath(srcDir, "?", "init.lua")); } if (includes.size() > 0) { if (tree.size() > 0) { tree = kj::strTree(kj::mv(tree), ";"); } tree = kj::strTree(kj::mv(tree), includes.flatten()); } if (fallbackInclude.size() > 0) { if (tree.size() > 0) { tree = kj::strTree(kj::mv(tree), ";"); } tree = kj::strTree(kj::mv(tree), fallbackInclude); } return tree.flatten(); } kj::MainFunc Main::getMain() { return kj::MainBuilder(context, "mcm-luacat", "Interprets Lua source and generates an mcm catalog.") .addOptionWithArg({'I'}, KJ_BIND_METHOD(*this, addIncludePath), "<templates>", "Add a package path template in package.searchpath format.") .addOptionWithArg({'o'}, KJ_BIND_METHOD(*this, setOutputPath), "FILE", "Write output to FILE instead of stdout.") .expectArg("FILE", KJ_BIND_METHOD(*this, processFile)) .build(); } OwnState newLuaState() { // TODO(someday): use lua_newstate and set atpanic lua_State* state = luaL_newstate(); KJ_ASSERT_NONNULL(state); return OwnState(state); } } // namespace luacat } // namespace mcm <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "chinese_translationdialog.hxx" #include "chinese_dictionarydialog.hxx" #include <com/sun/star/i18n/TextConversionOption.hpp> // header for define RET_OK #include <vcl/msgbox.hxx> // header for class SvtLinguConfigItem #include <unotools/lingucfg.hxx> #include <unotools/linguprops.hxx> #include "helpid.hrc" namespace textconversiondlgs { using namespace ::com::sun::star; using namespace ::com::sun::star::uno; ChineseTranslationDialog::ChineseTranslationDialog( Window* pParent ) : ModalDialog(pParent, "ChineseConversionDialog", "svx/ui/chineseconversiondialog.ui") , m_pDictionaryDialog(0) { get(m_pBP_OK, "ok"); get(m_pPB_Editterms, "editterms"); get(m_pRB_To_Simplified, "tosimplified"); get(m_pRB_To_Traditional, "totraditional"); get(m_pCB_Translate_Commonterms, "commonterms"); SvtLinguConfig aLngCfg; bool bValue; Any aAny( aLngCfg.GetProperty( OUString( UPN_IS_DIRECTION_TO_SIMPLIFIED ) ) ); aAny >>= bValue; if( bValue ) m_pRB_To_Simplified->Check(); else m_pRB_To_Traditional->Check(); aAny = aLngCfg.GetProperty( OUString( UPN_IS_TRANSLATE_COMMON_TERMS ) ); if( aAny >>= bValue ) m_pCB_Translate_Commonterms->Check( bValue ); m_pPB_Editterms->SetClickHdl( LINK( this, ChineseTranslationDialog, DictionaryHdl ) ); m_pBP_OK->SetClickHdl( LINK( this, ChineseTranslationDialog, OkHdl ) ); } ChineseTranslationDialog::~ChineseTranslationDialog() { if(m_pDictionaryDialog) { if(m_pDictionaryDialog->IsInExecute()) m_pDictionaryDialog->EndDialog(); delete m_pDictionaryDialog; } } void ChineseTranslationDialog::getSettings( bool& rbDirectionToSimplified , bool& rbTranslateCommonTerms ) const { rbDirectionToSimplified = m_pRB_To_Simplified->IsChecked(); rbTranslateCommonTerms = m_pCB_Translate_Commonterms->IsChecked(); } IMPL_LINK_NOARG(ChineseTranslationDialog, OkHdl) { //save settings to configuration SvtLinguConfig aLngCfg; Any aAny; aAny <<= m_pRB_To_Simplified->IsChecked(); aLngCfg.SetProperty( OUString( UPN_IS_DIRECTION_TO_SIMPLIFIED ), aAny ); aAny <<= m_pCB_Translate_Commonterms->IsChecked(); aLngCfg.SetProperty( OUString( UPN_IS_TRANSLATE_COMMON_TERMS ), aAny ); EndDialog( RET_OK ); return 0; } IMPL_LINK_NOARG(ChineseTranslationDialog, DictionaryHdl) { if( !m_pDictionaryDialog ) { m_pDictionaryDialog = new ChineseDictionaryDialog(this); } if( m_pDictionaryDialog ) { if( m_pDictionaryDialog->IsInExecute() ) { if( !m_pDictionaryDialog->IsReallyVisible() ) { m_pDictionaryDialog->ToTop(); m_pDictionaryDialog->GrabFocusToFirstControl(); } } else { sal_Int32 nTextConversionOptions = i18n::TextConversionOption::NONE; if( !m_pCB_Translate_Commonterms->IsChecked() ) nTextConversionOptions = nTextConversionOptions | i18n::TextConversionOption::CHARACTER_BY_CHARACTER; m_pDictionaryDialog->setDirectionAndTextConversionOptions( m_pRB_To_Simplified->IsChecked(), nTextConversionOptions ); m_pDictionaryDialog->Execute(); } } return 0; } } //end namespace /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>WaE: 'bValue' may be used uninitialized in this function<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "chinese_translationdialog.hxx" #include "chinese_dictionarydialog.hxx" #include <com/sun/star/i18n/TextConversionOption.hpp> // header for define RET_OK #include <vcl/msgbox.hxx> // header for class SvtLinguConfigItem #include <unotools/lingucfg.hxx> #include <unotools/linguprops.hxx> #include "helpid.hrc" namespace textconversiondlgs { using namespace ::com::sun::star; using namespace ::com::sun::star::uno; ChineseTranslationDialog::ChineseTranslationDialog( Window* pParent ) : ModalDialog(pParent, "ChineseConversionDialog", "svx/ui/chineseconversiondialog.ui") , m_pDictionaryDialog(0) { get(m_pBP_OK, "ok"); get(m_pPB_Editterms, "editterms"); get(m_pRB_To_Simplified, "tosimplified"); get(m_pRB_To_Traditional, "totraditional"); get(m_pCB_Translate_Commonterms, "commonterms"); SvtLinguConfig aLngCfg; bool bValue = false; Any aAny( aLngCfg.GetProperty( OUString( UPN_IS_DIRECTION_TO_SIMPLIFIED ) ) ); aAny >>= bValue; if( bValue ) m_pRB_To_Simplified->Check(); else m_pRB_To_Traditional->Check(); aAny = aLngCfg.GetProperty( OUString( UPN_IS_TRANSLATE_COMMON_TERMS ) ); if( aAny >>= bValue ) m_pCB_Translate_Commonterms->Check( bValue ); m_pPB_Editterms->SetClickHdl( LINK( this, ChineseTranslationDialog, DictionaryHdl ) ); m_pBP_OK->SetClickHdl( LINK( this, ChineseTranslationDialog, OkHdl ) ); } ChineseTranslationDialog::~ChineseTranslationDialog() { if(m_pDictionaryDialog) { if(m_pDictionaryDialog->IsInExecute()) m_pDictionaryDialog->EndDialog(); delete m_pDictionaryDialog; } } void ChineseTranslationDialog::getSettings( bool& rbDirectionToSimplified , bool& rbTranslateCommonTerms ) const { rbDirectionToSimplified = m_pRB_To_Simplified->IsChecked(); rbTranslateCommonTerms = m_pCB_Translate_Commonterms->IsChecked(); } IMPL_LINK_NOARG(ChineseTranslationDialog, OkHdl) { //save settings to configuration SvtLinguConfig aLngCfg; Any aAny; aAny <<= m_pRB_To_Simplified->IsChecked(); aLngCfg.SetProperty( OUString( UPN_IS_DIRECTION_TO_SIMPLIFIED ), aAny ); aAny <<= m_pCB_Translate_Commonterms->IsChecked(); aLngCfg.SetProperty( OUString( UPN_IS_TRANSLATE_COMMON_TERMS ), aAny ); EndDialog( RET_OK ); return 0; } IMPL_LINK_NOARG(ChineseTranslationDialog, DictionaryHdl) { if( !m_pDictionaryDialog ) { m_pDictionaryDialog = new ChineseDictionaryDialog(this); } if( m_pDictionaryDialog ) { if( m_pDictionaryDialog->IsInExecute() ) { if( !m_pDictionaryDialog->IsReallyVisible() ) { m_pDictionaryDialog->ToTop(); m_pDictionaryDialog->GrabFocusToFirstControl(); } } else { sal_Int32 nTextConversionOptions = i18n::TextConversionOption::NONE; if( !m_pCB_Translate_Commonterms->IsChecked() ) nTextConversionOptions = nTextConversionOptions | i18n::TextConversionOption::CHARACTER_BY_CHARACTER; m_pDictionaryDialog->setDirectionAndTextConversionOptions( m_pRB_To_Simplified->IsChecked(), nTextConversionOptions ); m_pDictionaryDialog->Execute(); } } return 0; } } //end namespace /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/** * 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. */ #ifndef __SLAVE_HPP__ #define __SLAVE_HPP__ #include <process/http.hpp> #include <process/process.hpp> #include <process/protobuf.hpp> #include <stout/hashmap.hpp> #include <stout/os.hpp> #include <stout/path.hpp> #include <stout/uuid.hpp> #include "slave/constants.hpp" #include "slave/flags.hpp" #include "slave/gc.hpp" #include "slave/http.hpp" #include "slave/isolation_module.hpp" #include "slave/state.hpp" #include "common/attributes.hpp" #include "common/resources.hpp" #include "common/type_utils.hpp" #include "files/files.hpp" #include "messages/messages.hpp" namespace mesos { namespace internal { namespace slave { using namespace process; // Some forward declarations. struct Executor; struct Framework; class Slave : public ProtobufProcess<Slave> { public: Slave(const Resources& resources, bool local, IsolationModule* isolationModule, Files* files); Slave(const flags::Flags<logging::Flags, slave::Flags>& flags, bool local, IsolationModule *isolationModule, Files* files); virtual ~Slave(); void shutdown(); void newMasterDetected(const UPID& pid); void noMasterDetected(); void masterDetectionFailure(); void registered(const SlaveID& slaveId); void reregistered(const SlaveID& slaveId); void doReliableRegistration(); void runTask(const FrameworkInfo& frameworkInfo, const FrameworkID& frameworkId, const std::string& pid, const TaskInfo& task); void killTask(const FrameworkID& frameworkId, const TaskID& taskId); void shutdownFramework(const FrameworkID& frameworkId); void schedulerMessage(const SlaveID& slaveId, const FrameworkID& frameworkId, const ExecutorID& executorId, const std::string& data); void updateFramework(const FrameworkID& frameworkId, const std::string& pid); void statusUpdateAcknowledgement(const SlaveID& slaveId, const FrameworkID& frameworkId, const TaskID& taskId, const std::string& uuid); void registerExecutor(const FrameworkID& frameworkId, const ExecutorID& executorId); void statusUpdate(const StatusUpdate& update); void executorMessage(const SlaveID& slaveId, const FrameworkID& frameworkId, const ExecutorID& executorId, const std::string& data); void ping(const UPID& from, const std::string& body); void statusUpdateTimeout(const FrameworkID& frameworkId, const UUID& uuid); StatusUpdate createStatusUpdate(const TaskID& taskId, const ExecutorID& executorId, const FrameworkID& frameworkId, TaskState taskState, const std::string& message); void executorStarted(const FrameworkID& frameworkId, const ExecutorID& executorId, pid_t pid); void executorExited(const FrameworkID& frameworkId, const ExecutorID& executorId, int status); void transitionLiveTask(const TaskID& taskId, const ExecutorID& executorId, const FrameworkID& frameworkId, bool command_executor, int status); // NOTE: Pulled this to public to make it visible for testing. // Garbage collects the directories based on the current disk usage. // TODO(vinod): Instead of making this function public, we need to // mock both GarbageCollector (and pass it through slave's constructor) // and os calls. void _checkDiskUsage(const Future<Try<double> >& capacity); protected: virtual void initialize(); virtual void finalize(); virtual void exited(const UPID& pid); void fileAttached(const Future<Nothing>& result); // Helper routine to lookup a framework. Framework* getFramework(const FrameworkID& frameworkId); // Shut down an executor. This is a two phase process. First, an // executor receives a shut down message (shut down phase), then // after a configurable timeout the slave actually forces a kill // (kill phase, via the isolation module) if the executor has not // exited. void shutdownExecutor(Framework* framework, Executor* executor); // Handle the second phase of shutting down an executor for those // executors that have not properly shutdown within a timeout. void shutdownExecutorTimeout(const FrameworkID& frameworkId, const ExecutorID& executorId, const UUID& uuid); // This function returns the max age of executor/slave directories allowed, // given a disk usage. This value could be used to tune gc. Duration age(double usage); // Checks the current disk usage and schedules for gc as necessary. void checkDiskUsage(); private: // HTTP handlers, friends of the slave in order to access state, // they get invoked from within the slave so there is no need to // use synchronization mechanisms to protect state. friend Future<process::http::Response> http::vars( const Slave& slave, const process::http::Request& request); friend Future<process::http::Response> http::json::stats( const Slave& slave, const process::http::Request& request); friend Future<process::http::Response> http::json::state( const Slave& slave, const process::http::Request& request); const flags::Flags<logging::Flags, slave::Flags> flags; bool local; SlaveID id; SlaveInfo info; UPID master; Resources resources; Attributes attributes; hashmap<FrameworkID, Framework*> frameworks; IsolationModule* isolationModule; Files* files; // Statistics (initialized in Slave::initialize). struct { uint64_t tasks[TaskState_ARRAYSIZE]; uint64_t validStatusUpdates; uint64_t invalidStatusUpdates; uint64_t validFrameworkMessages; uint64_t invalidFrameworkMessages; } stats; double startTime; bool connected; // Flag to indicate if slave is registered. GarbageCollector gc; state::SlaveState state; }; // Information describing an executor (goes away if executor crashes). struct Executor { Executor(const FrameworkID& _frameworkId, const ExecutorInfo& _info, const std::string& _directory) : id(_info.executor_id()), info(_info), frameworkId(_frameworkId), directory(_directory), uuid(UUID::random()), pid(UPID()), shutdown(false), resources(_info.resources()) {} ~Executor() { // Delete the tasks. foreachvalue (Task* task, launchedTasks) { delete task; } } Task* addTask(const TaskInfo& task) { // The master should enforce unique task IDs, but just in case // maybe we shouldn't make this a fatal error. CHECK(!launchedTasks.contains(task.task_id())); Task *t = new Task(); t->mutable_framework_id()->MergeFrom(frameworkId); t->set_state(TASK_STAGING); t->set_name(task.name()); t->mutable_task_id()->MergeFrom(task.task_id()); t->mutable_slave_id()->MergeFrom(task.slave_id()); t->mutable_resources()->MergeFrom(task.resources()); if (!task.has_command()) { t->mutable_executor_id()->MergeFrom(id); } launchedTasks[task.task_id()] = t; resources += task.resources(); return t; } void removeTask(const TaskID& taskId) { // Remove the task if it's queued. queuedTasks.erase(taskId); // Update the resources if it's been launched. if (launchedTasks.contains(taskId)) { Task* task = launchedTasks[taskId]; foreach (const Resource& resource, task->resources()) { resources -= resource; } launchedTasks.erase(taskId); delete task; } } void updateTaskState(const TaskID& taskId, TaskState state) { if (launchedTasks.contains(taskId)) { launchedTasks[taskId]->set_state(state); } } const ExecutorID id; const ExecutorInfo info; const FrameworkID frameworkId; const std::string directory; const UUID uuid; // Distinguishes executor instances with same ExecutorID. UPID pid; bool shutdown; // Indicates if executor is being shut down. Resources resources; // Currently consumed resources. hashmap<TaskID, TaskInfo> queuedTasks; hashmap<TaskID, Task*> launchedTasks; }; // Information about a framework. struct Framework { Framework(const FrameworkID& _id, const FrameworkInfo& _info, const UPID& _pid, const Flags& _flags) : id(_id), info(_info), pid(_pid), flags(_flags) {} ~Framework() {} // Returns an ExecutorInfo for a TaskInfo (possibly // constructing one if the task has a CommandInfo). ExecutorInfo getExecutorInfo(const TaskInfo& task) { CHECK(task.has_executor() != task.has_command()); if (task.has_command()) { ExecutorInfo executor; // Prepare an executor id which includes information on the // command being launched. std::string id = "Task " + task.task_id().value() + " ("; if (task.command().value().length() > 15) { id += task.command().value().substr(0, 12) + "...)"; } else { id += task.command().value() + ")"; } executor.mutable_executor_id()->set_value(id); // Now determine the path to the executor. Try<std::string> path = os::realpath( ::path::join(flags.launcher_dir, "mesos-executor")); if (path.isSome()) { executor.mutable_command()->set_value(path.get()); } else { executor.mutable_command()->set_value( "echo '" + path.error() + "'; exit 1"); } // TODO(benh): Set some resources for the executor so that a task // doesn't end up getting killed because the amount of resources of // the executor went over those allocated. Note that this might mean // that the number of resources on the machine will actually be // slightly oversubscribed, so we'll need to reevaluate with respect // to resources that can't be oversubscribed. return executor; } return task.executor(); } Executor* createExecutor(const ExecutorInfo& executorInfo, const std::string& directory) { Executor* executor = new Executor(id, executorInfo, directory); CHECK(!executors.contains(executorInfo.executor_id())); executors[executorInfo.executor_id()] = executor; return executor; } void destroyExecutor(const ExecutorID& executorId) { if (executors.contains(executorId)) { Executor* executor = executors[executorId]; executors.erase(executorId); delete executor; } } Executor* getExecutor(const ExecutorID& executorId) { if (executors.contains(executorId)) { return executors[executorId]; } return NULL; } Executor* getExecutor(const TaskID& taskId) { foreachvalue (Executor* executor, executors) { if (executor->queuedTasks.contains(taskId) || executor->launchedTasks.contains(taskId)) { return executor; } } return NULL; } const FrameworkID id; const FrameworkInfo info; UPID pid; const Flags flags; // Current running executors. hashmap<ExecutorID, Executor*> executors; // Status updates keyed by uuid. hashmap<UUID, StatusUpdate> updates; }; } // namespace slave { } // namespace internal { } // namespace mesos { #endif // __SLAVE_HPP__ <commit_msg>Fixes a bug where tasks that don't have an executor were not getting their URIs or environment properly set up.<commit_after>/** * 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. */ #ifndef __SLAVE_HPP__ #define __SLAVE_HPP__ #include <process/http.hpp> #include <process/process.hpp> #include <process/protobuf.hpp> #include <stout/hashmap.hpp> #include <stout/os.hpp> #include <stout/path.hpp> #include <stout/uuid.hpp> #include "slave/constants.hpp" #include "slave/flags.hpp" #include "slave/gc.hpp" #include "slave/http.hpp" #include "slave/isolation_module.hpp" #include "slave/state.hpp" #include "common/attributes.hpp" #include "common/resources.hpp" #include "common/type_utils.hpp" #include "files/files.hpp" #include "messages/messages.hpp" namespace mesos { namespace internal { namespace slave { using namespace process; // Some forward declarations. struct Executor; struct Framework; class Slave : public ProtobufProcess<Slave> { public: Slave(const Resources& resources, bool local, IsolationModule* isolationModule, Files* files); Slave(const flags::Flags<logging::Flags, slave::Flags>& flags, bool local, IsolationModule *isolationModule, Files* files); virtual ~Slave(); void shutdown(); void newMasterDetected(const UPID& pid); void noMasterDetected(); void masterDetectionFailure(); void registered(const SlaveID& slaveId); void reregistered(const SlaveID& slaveId); void doReliableRegistration(); void runTask(const FrameworkInfo& frameworkInfo, const FrameworkID& frameworkId, const std::string& pid, const TaskInfo& task); void killTask(const FrameworkID& frameworkId, const TaskID& taskId); void shutdownFramework(const FrameworkID& frameworkId); void schedulerMessage(const SlaveID& slaveId, const FrameworkID& frameworkId, const ExecutorID& executorId, const std::string& data); void updateFramework(const FrameworkID& frameworkId, const std::string& pid); void statusUpdateAcknowledgement(const SlaveID& slaveId, const FrameworkID& frameworkId, const TaskID& taskId, const std::string& uuid); void registerExecutor(const FrameworkID& frameworkId, const ExecutorID& executorId); void statusUpdate(const StatusUpdate& update); void executorMessage(const SlaveID& slaveId, const FrameworkID& frameworkId, const ExecutorID& executorId, const std::string& data); void ping(const UPID& from, const std::string& body); void statusUpdateTimeout(const FrameworkID& frameworkId, const UUID& uuid); StatusUpdate createStatusUpdate(const TaskID& taskId, const ExecutorID& executorId, const FrameworkID& frameworkId, TaskState taskState, const std::string& message); void executorStarted(const FrameworkID& frameworkId, const ExecutorID& executorId, pid_t pid); void executorExited(const FrameworkID& frameworkId, const ExecutorID& executorId, int status); void transitionLiveTask(const TaskID& taskId, const ExecutorID& executorId, const FrameworkID& frameworkId, bool command_executor, int status); // NOTE: Pulled this to public to make it visible for testing. // Garbage collects the directories based on the current disk usage. // TODO(vinod): Instead of making this function public, we need to // mock both GarbageCollector (and pass it through slave's constructor) // and os calls. void _checkDiskUsage(const Future<Try<double> >& capacity); protected: virtual void initialize(); virtual void finalize(); virtual void exited(const UPID& pid); void fileAttached(const Future<Nothing>& result); // Helper routine to lookup a framework. Framework* getFramework(const FrameworkID& frameworkId); // Shut down an executor. This is a two phase process. First, an // executor receives a shut down message (shut down phase), then // after a configurable timeout the slave actually forces a kill // (kill phase, via the isolation module) if the executor has not // exited. void shutdownExecutor(Framework* framework, Executor* executor); // Handle the second phase of shutting down an executor for those // executors that have not properly shutdown within a timeout. void shutdownExecutorTimeout(const FrameworkID& frameworkId, const ExecutorID& executorId, const UUID& uuid); // This function returns the max age of executor/slave directories allowed, // given a disk usage. This value could be used to tune gc. Duration age(double usage); // Checks the current disk usage and schedules for gc as necessary. void checkDiskUsage(); private: // HTTP handlers, friends of the slave in order to access state, // they get invoked from within the slave so there is no need to // use synchronization mechanisms to protect state. friend Future<process::http::Response> http::vars( const Slave& slave, const process::http::Request& request); friend Future<process::http::Response> http::json::stats( const Slave& slave, const process::http::Request& request); friend Future<process::http::Response> http::json::state( const Slave& slave, const process::http::Request& request); const flags::Flags<logging::Flags, slave::Flags> flags; bool local; SlaveID id; SlaveInfo info; UPID master; Resources resources; Attributes attributes; hashmap<FrameworkID, Framework*> frameworks; IsolationModule* isolationModule; Files* files; // Statistics (initialized in Slave::initialize). struct { uint64_t tasks[TaskState_ARRAYSIZE]; uint64_t validStatusUpdates; uint64_t invalidStatusUpdates; uint64_t validFrameworkMessages; uint64_t invalidFrameworkMessages; } stats; double startTime; bool connected; // Flag to indicate if slave is registered. GarbageCollector gc; state::SlaveState state; }; // Information describing an executor (goes away if executor crashes). struct Executor { Executor(const FrameworkID& _frameworkId, const ExecutorInfo& _info, const std::string& _directory) : id(_info.executor_id()), info(_info), frameworkId(_frameworkId), directory(_directory), uuid(UUID::random()), pid(UPID()), shutdown(false), resources(_info.resources()) {} ~Executor() { // Delete the tasks. foreachvalue (Task* task, launchedTasks) { delete task; } } Task* addTask(const TaskInfo& task) { // The master should enforce unique task IDs, but just in case // maybe we shouldn't make this a fatal error. CHECK(!launchedTasks.contains(task.task_id())); Task *t = new Task(); t->mutable_framework_id()->MergeFrom(frameworkId); t->set_state(TASK_STAGING); t->set_name(task.name()); t->mutable_task_id()->MergeFrom(task.task_id()); t->mutable_slave_id()->MergeFrom(task.slave_id()); t->mutable_resources()->MergeFrom(task.resources()); if (!task.has_command()) { t->mutable_executor_id()->MergeFrom(id); } launchedTasks[task.task_id()] = t; resources += task.resources(); return t; } void removeTask(const TaskID& taskId) { // Remove the task if it's queued. queuedTasks.erase(taskId); // Update the resources if it's been launched. if (launchedTasks.contains(taskId)) { Task* task = launchedTasks[taskId]; foreach (const Resource& resource, task->resources()) { resources -= resource; } launchedTasks.erase(taskId); delete task; } } void updateTaskState(const TaskID& taskId, TaskState state) { if (launchedTasks.contains(taskId)) { launchedTasks[taskId]->set_state(state); } } const ExecutorID id; const ExecutorInfo info; const FrameworkID frameworkId; const std::string directory; const UUID uuid; // Distinguishes executor instances with same ExecutorID. UPID pid; bool shutdown; // Indicates if executor is being shut down. Resources resources; // Currently consumed resources. hashmap<TaskID, TaskInfo> queuedTasks; hashmap<TaskID, Task*> launchedTasks; }; // Information about a framework. struct Framework { Framework(const FrameworkID& _id, const FrameworkInfo& _info, const UPID& _pid, const Flags& _flags) : id(_id), info(_info), pid(_pid), flags(_flags) {} ~Framework() {} // Returns an ExecutorInfo for a TaskInfo (possibly // constructing one if the task has a CommandInfo). ExecutorInfo getExecutorInfo(const TaskInfo& task) { CHECK(task.has_executor() != task.has_command()); if (task.has_command()) { ExecutorInfo executor; // Prepare an executor id which includes information on the // command being launched. std::string id = "Task " + task.task_id().value() + " ("; if (task.command().value().length() > 15) { id += task.command().value().substr(0, 12) + "...)"; } else { id += task.command().value() + ")"; } executor.mutable_executor_id()->set_value(id); // Copy the CommandInfo to get the URIs and environment, but // update it to invoke 'mesos-executor' (unless we couldn't // resolve 'mesos-executor' via 'realpath', in which case just // echo the error and exit). executor.mutable_command()->MergeFrom(task.command()); Try<std::string> path = os::realpath( path::join(flags.launcher_dir, "mesos-executor")); if (path.isSome()) { executor.mutable_command()->set_value(path.get()); } else { executor.mutable_command()->set_value( "echo '" + path.error() + "'; exit 1"); } // TODO(benh): Set some resources for the executor so that a task // doesn't end up getting killed because the amount of resources of // the executor went over those allocated. Note that this might mean // that the number of resources on the machine will actually be // slightly oversubscribed, so we'll need to reevaluate with respect // to resources that can't be oversubscribed. return executor; } return task.executor(); } Executor* createExecutor(const ExecutorInfo& executorInfo, const std::string& directory) { Executor* executor = new Executor(id, executorInfo, directory); CHECK(!executors.contains(executorInfo.executor_id())); executors[executorInfo.executor_id()] = executor; return executor; } void destroyExecutor(const ExecutorID& executorId) { if (executors.contains(executorId)) { Executor* executor = executors[executorId]; executors.erase(executorId); delete executor; } } Executor* getExecutor(const ExecutorID& executorId) { if (executors.contains(executorId)) { return executors[executorId]; } return NULL; } Executor* getExecutor(const TaskID& taskId) { foreachvalue (Executor* executor, executors) { if (executor->queuedTasks.contains(taskId) || executor->launchedTasks.contains(taskId)) { return executor; } } return NULL; } const FrameworkID id; const FrameworkInfo info; UPID pid; const Flags flags; // Current running executors. hashmap<ExecutorID, Executor*> executors; // Status updates keyed by uuid. hashmap<UUID, StatusUpdate> updates; }; } // namespace slave { } // namespace internal { } // namespace mesos { #endif // __SLAVE_HPP__ <|endoftext|>
<commit_before>/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE Team. All rights reserved. ** ** 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. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: editorutil.cpp // Creator: visualfc <visualfc@gmail.com> #include "editorutil.h" typedef void (*EnumEditorProc)(QTextCursor &cursor, QTextBlock &block, void *param); void EditorUtil::EnumEditor(QPlainTextEdit *ed, EnumEditorProc proc, void *param) { if (!ed) { return; } QTextCursor cur = ed->textCursor(); cur.beginEditBlock(); if (cur.hasSelection()) { QTextBlock begin = ed->document()->findBlock(cur.selectionStart()); QTextBlock end = ed->document()->findBlock(cur.selectionEnd()); if (end.position() == cur.selectionEnd()) { end = end.previous(); } QTextBlock block = begin; do { if (block.text().length() > 0) { proc(cur,block,param); } block = block.next(); } while(block.isValid() && block.position() <= end.position()); } else { QTextBlock block = cur.block(); proc(cur,block,param); } cur.endEditBlock(); ed->setTextCursor(cur); } struct InsertHeadParam { QString tag; bool blockStart; }; static void insertHead(QTextCursor &cur, QTextBlock &block, void *param) { InsertHeadParam *ip = (InsertHeadParam*)param; if (ip->blockStart) { cur.setPosition(block.position()); } else { QString text = block.text(); foreach(QChar c, text) { if (!c.isSpace()) { cur.setPosition(block.position()+text.indexOf(c)); break; } } } cur.insertText(ip->tag); } struct RemoveHeadParam { QStringList tags; bool blockStart; }; struct SwitchHeadParam { QString tagAdd; QStringList tagRemove; bool blockStart; }; static void removeHead(QTextCursor &cur, QTextBlock &block, void *param) { RemoveHeadParam *ip = (RemoveHeadParam*)param; if (ip->blockStart) { cur.setPosition(block.position()); } else { QString text = block.text(); foreach(QChar c, text) { if (!c.isSpace()) { cur.setPosition(block.position()+text.indexOf(c)); break; } } } foreach (QString tag, ip->tags) { if (cur.block().text().startsWith(tag)) { cur.setPosition(block.position()); cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, tag.length()); cur.removeSelectedText(); break; } } } static void switchHead(QTextCursor &cur, QTextBlock &block, void *param) { SwitchHeadParam *ip = (SwitchHeadParam*)param; if (ip->blockStart) { cur.setPosition(block.position()); } else { QString text = block.text(); foreach(QChar c, text) { if (!c.isSpace()) { cur.setPosition(block.position()+text.indexOf(c)); break; } } } foreach (QString tag, ip->tagRemove) { if (cur.block().text().startsWith(tag)) { cur.setPosition(block.position()); cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, tag.length()); cur.removeSelectedText(); return; } } cur.insertText(ip->tagAdd); } void EditorUtil::InsertHead(QPlainTextEdit *ed, const QString &tag, bool blockStart) { InsertHeadParam param = {tag,blockStart}; EnumEditor(ed,&insertHead,&param); } void EditorUtil::RemoveHead(QPlainTextEdit *ed, const QStringList &tags, bool blockStart) { RemoveHeadParam param = {tags,blockStart}; EnumEditor(ed,&removeHead,&param); } void EditorUtil::SwitchHead(QPlainTextEdit *ed, const QString &tagAdd, const QStringList &tagRemove, bool blockStart) { SwitchHeadParam param = {tagAdd,tagRemove,blockStart}; EnumEditor(ed,&switchHead,&param); } void EditorUtil::MarkSelection(QPlainTextEdit *ed, const QString &mark1, const QString &mark2) { if (!ed) { return; } QTextCursor cur = ed->textCursor(); cur.beginEditBlock(); if (cur.hasSelection()) { QTextBlock begin = ed->document()->findBlock(cur.selectionStart()); QTextBlock end = ed->document()->findBlock(cur.selectionEnd()); if (end.position() == cur.selectionEnd()) { end = end.previous(); } int n1 = cur.selectionStart(); int n2 = cur.selectionEnd(); QTextBlock block = begin; do { int c1 = block.position(); int c2 = c1+block.text().length(); if (block.position() == begin.position() && c1 < n1) { c1 = n1; } if (c2 > n2) { c2 = n2; } if (c2 > c1) { if (!mark1.isEmpty()) { cur.setPosition(c1); cur.insertText(mark1); n2 += mark1.length(); } if (!mark2.isEmpty()) { cur.setPosition(c2+mark1.length()); cur.insertText(mark2); n2 += mark2.length(); } } block = block.next(); } while(block.isValid() && block.position() <= end.position()); } else { int pos = cur.position(); cur.insertText(mark1+mark2); cur.setPosition(pos+mark1.length()); } cur.endEditBlock(); ed->setTextCursor(cur); } void EditorUtil::MarkSelection(QPlainTextEdit *ed, const QString &mark) { EditorUtil::MarkSelection(ed,mark,mark); } <commit_msg>update<commit_after>/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE Team. All rights reserved. ** ** 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. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: editorutil.cpp // Creator: visualfc <visualfc@gmail.com> #include "editorutil.h" #include <QTextBlock> #include <QTextCursor> #include <QPlainTextEdit> typedef void (*EnumEditorProc)(QTextCursor &cursor, QTextBlock &block, void *param); void EditorUtil::EnumEditor(QPlainTextEdit *ed, EnumEditorProc proc, void *param) { if (!ed) { return; } QTextCursor cur = ed->textCursor(); cur.beginEditBlock(); if (cur.hasSelection()) { QTextBlock begin = ed->document()->findBlock(cur.selectionStart()); QTextBlock end = ed->document()->findBlock(cur.selectionEnd()); if (end.position() == cur.selectionEnd()) { end = end.previous(); } QTextBlock block = begin; do { if (block.text().length() > 0) { proc(cur,block,param); } block = block.next(); } while(block.isValid() && block.position() <= end.position()); } else { QTextBlock block = cur.block(); proc(cur,block,param); } cur.endEditBlock(); ed->setTextCursor(cur); } struct InsertHeadParam { QString tag; bool blockStart; }; static void insertHead(QTextCursor &cur, QTextBlock &block, void *param) { InsertHeadParam *ip = (InsertHeadParam*)param; if (ip->blockStart) { cur.setPosition(block.position()); } else { QString text = block.text(); foreach(QChar c, text) { if (!c.isSpace()) { cur.setPosition(block.position()+text.indexOf(c)); break; } } } cur.insertText(ip->tag); } struct RemoveHeadParam { QStringList tags; bool blockStart; }; struct SwitchHeadParam { QString tagAdd; QStringList tagRemove; bool blockStart; }; static void removeHead(QTextCursor &cur, QTextBlock &block, void *param) { RemoveHeadParam *ip = (RemoveHeadParam*)param; if (ip->blockStart) { cur.setPosition(block.position()); } else { QString text = block.text(); foreach(QChar c, text) { if (!c.isSpace()) { cur.setPosition(block.position()+text.indexOf(c)); break; } } } foreach (QString tag, ip->tags) { if (cur.block().text().startsWith(tag)) { cur.setPosition(block.position()); cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, tag.length()); cur.removeSelectedText(); break; } } } static void switchHead(QTextCursor &cur, QTextBlock &block, void *param) { SwitchHeadParam *ip = (SwitchHeadParam*)param; if (ip->blockStart) { cur.setPosition(block.position()); } else { QString text = block.text(); foreach(QChar c, text) { if (!c.isSpace()) { cur.setPosition(block.position()+text.indexOf(c)); break; } } } foreach (QString tag, ip->tagRemove) { if (cur.block().text().startsWith(tag)) { cur.setPosition(block.position()); cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, tag.length()); cur.removeSelectedText(); return; } } cur.insertText(ip->tagAdd); } void EditorUtil::InsertHead(QPlainTextEdit *ed, const QString &tag, bool blockStart) { InsertHeadParam param = {tag,blockStart}; EnumEditor(ed,&insertHead,&param); } void EditorUtil::RemoveHead(QPlainTextEdit *ed, const QStringList &tags, bool blockStart) { RemoveHeadParam param = {tags,blockStart}; EnumEditor(ed,&removeHead,&param); } void EditorUtil::SwitchHead(QPlainTextEdit *ed, const QString &tagAdd, const QStringList &tagRemove, bool blockStart) { SwitchHeadParam param = {tagAdd,tagRemove,blockStart}; EnumEditor(ed,&switchHead,&param); } void EditorUtil::MarkSelection(QPlainTextEdit *ed, const QString &mark1, const QString &mark2) { if (!ed) { return; } QTextCursor cur = ed->textCursor(); cur.beginEditBlock(); if (cur.hasSelection()) { QTextBlock begin = ed->document()->findBlock(cur.selectionStart()); QTextBlock end = ed->document()->findBlock(cur.selectionEnd()); if (end.position() == cur.selectionEnd()) { end = end.previous(); } int n1 = cur.selectionStart(); int n2 = cur.selectionEnd(); QTextBlock block = begin; do { int c1 = block.position(); int c2 = c1+block.text().length(); if (block.position() == begin.position() && c1 < n1) { c1 = n1; } if (c2 > n2) { c2 = n2; } if (c2 > c1) { if (!mark1.isEmpty()) { cur.setPosition(c1); cur.insertText(mark1); n2 += mark1.length(); } if (!mark2.isEmpty()) { cur.setPosition(c2+mark1.length()); cur.insertText(mark2); n2 += mark2.length(); } } block = block.next(); } while(block.isValid() && block.position() <= end.position()); } else { int pos = cur.position(); cur.insertText(mark1+mark2); cur.setPosition(pos+mark1.length()); } cur.endEditBlock(); ed->setTextCursor(cur); } void EditorUtil::MarkSelection(QPlainTextEdit *ed, const QString &mark) { EditorUtil::MarkSelection(ed,mark,mark); } <|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2021, Trinity University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ***************************************************************************** #include <mapviz_plugins/pose_publisher_plugin.h> // Declare plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(mapviz_plugins::PosePublisherPlugin, mapviz::MapvizPlugin) namespace mapviz_plugins { PosePublisherPlugin::PosePublisherPlugin() : config_widget_(new QWidget()), map_canvas_(nullptr), is_mouse_down_(false), monitoring_action_state_(false) { // TODO - make pose a field //pose_pub_ = nh_.advertise<geometry_msgs::PoseWithCovarianceStamped>("/selected_pose", 1, false); ui_.setupUi(config_widget_); // Set background white QPalette p(config_widget_->palette()); p.setColor(QPalette::Background, Qt::white); config_widget_->setPalette(p); // Set status text red ui_.status->setText("OK"); QPalette p3(ui_.status->palette()); p3.setColor(QPalette::Text, Qt::green); ui_.status->setPalette(p3); QObject::connect(ui_.pushButtonPose, SIGNAL(toggled()), this, SLOT(on_pushButtonPose_toggled())); QObject::connect(ui_.topic, SIGNAL(textEdited(const QString&)), this, SLOT(topicChanged(const QString&))); timer_ = nh_.createTimer(ros::Duration(1.0), &PosePublisherPlugin::timerCallback, this); frame_timer_.start(1000); QObject::connect(&frame_timer_, SIGNAL(timeout()), this, SLOT(updateFrames())); } PosePublisherPlugin::~PosePublisherPlugin() { if (map_canvas_) { map_canvas_->removeEventFilter(this); } } void PosePublisherPlugin::PrintError(const std::string& message) { PrintErrorHelper( ui_.status, message); } void PosePublisherPlugin::PrintInfo(const std::string& message) { PrintInfoHelper( ui_.status, message); } void PosePublisherPlugin::PrintWarning(const std::string& message) { PrintWarningHelper( ui_.status, message); } QWidget* PosePublisherPlugin::GetConfigWidget(QWidget* parent) { config_widget_->setParent(parent); return config_widget_; } bool PosePublisherPlugin::Initialize(QGLWidget* canvas) { map_canvas_ = static_cast<mapviz::MapCanvas*>(canvas); map_canvas_->installEventFilter(this); initialized_ = true; return true; } bool PosePublisherPlugin::eventFilter(QObject *object, QEvent* event) { switch (event->type()) { case QEvent::MouseButtonPress: return handleMousePress(static_cast<QMouseEvent*>(event)); case QEvent::MouseButtonRelease: return handleMouseRelease(static_cast<QMouseEvent*>(event)); case QEvent::MouseMove: return handleMouseMove(static_cast<QMouseEvent*>(event)); default: return false; } } void PosePublisherPlugin::timerCallback(const ros::TimerEvent &) { ui_.pushButtonPose->setEnabled( true ); PrintInfoHelper( ui_.status, "OK"); } bool PosePublisherPlugin::handleMousePress(QMouseEvent* event) { bool pose_checked = ui_.pushButtonPose->isChecked(); if( !pose_checked) { return false; } if (event->button() == Qt::LeftButton) { is_mouse_down_ = true; arrow_angle_ = 0; #if QT_VERSION >= 0x050000 arrow_tail_position_= map_canvas_->MapGlCoordToFixedFrame( event->localPos() ); #else arrow_tail_position_= map_canvas_->MapGlCoordToFixedFrame( event->posF() ); #endif return true; } return false; } bool PosePublisherPlugin::handleMouseMove(QMouseEvent* event) { if (is_mouse_down_) { #if QT_VERSION >= 0x050000 QPointF head_pos = map_canvas_->MapGlCoordToFixedFrame( event->localPos() ); #else QPointF head_pos = map_canvas_->MapGlCoordToFixedFrame( event->posF() ); #endif arrow_angle_ = atan2( head_pos.y() - arrow_tail_position_.y(), head_pos.x() - arrow_tail_position_.x() ); } return false; } bool PosePublisherPlugin::handleMouseRelease(QMouseEvent* event) { if( !is_mouse_down_ ) { return false; } is_mouse_down_ = false; bool pose_checked = ui_.pushButtonPose->isChecked(); if( !pose_checked ) { return false; } if( pose_checked ) { // Get angle/arrow_tail_position in fixed_frame tf::Quaternion quat_ff = tf::createQuaternionFromYaw(arrow_angle_); geometry_msgs::PoseWithCovarianceStamped pose; // Here it is in the target_frame_ pose.header.frame_id = target_frame_; pose.header.stamp = ros::Time::now(); pose.pose.pose.position.x = arrow_tail_position_.x(); pose.pose.pose.position.y = arrow_tail_position_.y(); pose.pose.pose.position.z = 0.0; tf::quaternionTFToMsg( quat_ff, pose.pose.pose.orientation ); // Try to transform to output_frame swri_transform_util::Transform transform; std::string output_frame = ui_.outputframe->currentText().toStdString(); if (tf_manager_->GetTransform(output_frame, target_frame_, transform)) { pose.header.frame_id = output_frame; tf::Vector3 pose_oframe = transform * tf::Vector3(pose.pose.pose.position.x, pose.pose.pose.position.y, 0); pose.pose.pose.position.x = pose_oframe.x(); pose.pose.pose.position.y = pose_oframe.y(); tf::Quaternion quat_oframe = transform * quat_ff; tf::quaternionTFToMsg( quat_oframe, pose.pose.pose.orientation ); } else { std::stringstream ss; ss << "Couldn't get transform from "<< target_frame_ << " to frame " << output_frame; PrintWarning(ss.str()); } pose_pub_.publish(pose); std::stringstream ss; ss << "Pose published to topic: " << ui_.topic->text().toStdString().c_str() << " in frame " << pose.header.frame_id; PrintInfo(ss.str()); ui_.pushButtonPose->setChecked(false); } return true; } void PosePublisherPlugin::Draw(double x, double y, double scale) { std::array<QPointF, 7> arrow_points; arrow_points[0] = QPointF(10, 0); arrow_points[1] = QPointF(6, -2.5); arrow_points[2] = QPointF(6.5, -1); arrow_points[3] = QPointF(0, -1); arrow_points[4] = QPointF(0, 1); arrow_points[5] = QPointF(6.5, 1); arrow_points[6] = QPointF(6, 2.5); if( is_mouse_down_ ) { QPointF transformed_points[7]; for (size_t i=0; i<7; i++ ) { tf::Vector3 point(arrow_points[i].x(), arrow_points[i].y(), 0); point *= scale*10; point = tf::Transform( tf::createQuaternionFromYaw(arrow_angle_) ) * point; transformed_points[i] = QPointF(point.x() + arrow_tail_position_.x(), point.y() + arrow_tail_position_.y() ); } glColor3f(0.1, 0.9, 0.1); glLineWidth(2); glBegin(GL_TRIANGLE_FAN); for (const QPointF& point: transformed_points ) { glVertex2d(point.x(), point.y()); } glEnd(); glColor3f(0.0, 0.6, 0.0); glBegin(GL_LINE_LOOP); for (const QPointF& point: transformed_points ) { glVertex2d(point.x(), point.y()); } glEnd(); } } void PosePublisherPlugin::LoadConfig(const YAML::Node& node, const std::string& path) { std::string tmp; if (swri_yaml_util::FindValue(node, "topic")) { node["topic"] >> tmp; ui_.topic->setText(QString(tmp.c_str())); topicChanged(ui_.topic->text()); } if (swri_yaml_util::FindValue(node, "output_frame")) { node["output_frame"] >> tmp; ui_.outputframe->addItem(QString(tmp.c_str())); } } void PosePublisherPlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path) { emitter << YAML::Key << "topic" << YAML::Value << ui_.topic->text().toStdString(); emitter << YAML::Key << "output_frame" << YAML::Value << ui_.outputframe->currentText().toStdString(); } void PosePublisherPlugin::on_pushButtonPose_toggled(bool checked) { if(checked) { QPixmap cursor_pixmap = QPixmap(":/images/green-arrow.png"); QApplication::setOverrideCursor(QCursor(cursor_pixmap)); } else { QApplication::restoreOverrideCursor(); } } void PosePublisherPlugin::topicChanged(const QString& topic) { std::stringstream ss; ss << "Publishing points to topic: " << topic.toStdString().c_str(); PrintInfo(ss.str()); if (!topic.isEmpty()) { pose_pub_ = node_.advertise<geometry_msgs::PoseWithCovarianceStamped>(topic.toStdString(), 1000); } } void PosePublisherPlugin::updateFrames() { std::vector<std::string> frames; tf_->getFrameStrings(frames); bool supports_wgs84 = tf_manager_->SupportsTransform( swri_transform_util::_local_xy_frame, swri_transform_util::_wgs84_frame); if (supports_wgs84) { frames.push_back(swri_transform_util::_wgs84_frame); } if (ui_.outputframe->count() >= 0 && static_cast<size_t>(ui_.outputframe->count()) == frames.size()) { bool changed = false; for (size_t i = 0; i < frames.size(); i++) { if (frames[i] != ui_.outputframe->itemText(static_cast<int>(i)).toStdString()) { changed = true; } } if (!changed) return; } std::string output_frame = ui_.outputframe->currentText().toStdString(); ui_.outputframe->clear(); for (size_t i = 0; i < frames.size(); i++) { ui_.outputframe->addItem(frames[i].c_str()); } if (output_frame != "") { int index = ui_.outputframe->findText(output_frame.c_str()); if (index < 0) { ui_.outputframe->addItem(output_frame.c_str()); } index = ui_.outputframe->findText(output_frame.c_str()); ui_.outputframe->setCurrentIndex(index); } } } <commit_msg>clean up comments<commit_after>// ***************************************************************************** // // Copyright (c) 2021, Trinity University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ***************************************************************************** #include <mapviz_plugins/pose_publisher_plugin.h> // Declare plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(mapviz_plugins::PosePublisherPlugin, mapviz::MapvizPlugin) namespace mapviz_plugins { PosePublisherPlugin::PosePublisherPlugin() : config_widget_(new QWidget()), map_canvas_(nullptr), is_mouse_down_(false), monitoring_action_state_(false) { ui_.setupUi(config_widget_); // Set background white QPalette p(config_widget_->palette()); p.setColor(QPalette::Background, Qt::white); config_widget_->setPalette(p); // Set status text green ui_.status->setText("OK"); QPalette p3(ui_.status->palette()); p3.setColor(QPalette::Text, Qt::green); ui_.status->setPalette(p3); QObject::connect(ui_.pushButtonPose, SIGNAL(toggled()), this, SLOT(on_pushButtonPose_toggled())); QObject::connect(ui_.topic, SIGNAL(textEdited(const QString&)), this, SLOT(topicChanged(const QString&))); timer_ = nh_.createTimer(ros::Duration(1.0), &PosePublisherPlugin::timerCallback, this); frame_timer_.start(1000); QObject::connect(&frame_timer_, SIGNAL(timeout()), this, SLOT(updateFrames())); } PosePublisherPlugin::~PosePublisherPlugin() { if (map_canvas_) { map_canvas_->removeEventFilter(this); } } void PosePublisherPlugin::PrintError(const std::string& message) { PrintErrorHelper( ui_.status, message); } void PosePublisherPlugin::PrintInfo(const std::string& message) { PrintInfoHelper( ui_.status, message); } void PosePublisherPlugin::PrintWarning(const std::string& message) { PrintWarningHelper( ui_.status, message); } QWidget* PosePublisherPlugin::GetConfigWidget(QWidget* parent) { config_widget_->setParent(parent); return config_widget_; } bool PosePublisherPlugin::Initialize(QGLWidget* canvas) { map_canvas_ = static_cast<mapviz::MapCanvas*>(canvas); map_canvas_->installEventFilter(this); initialized_ = true; return true; } bool PosePublisherPlugin::eventFilter(QObject *object, QEvent* event) { switch (event->type()) { case QEvent::MouseButtonPress: return handleMousePress(static_cast<QMouseEvent*>(event)); case QEvent::MouseButtonRelease: return handleMouseRelease(static_cast<QMouseEvent*>(event)); case QEvent::MouseMove: return handleMouseMove(static_cast<QMouseEvent*>(event)); default: return false; } } void PosePublisherPlugin::timerCallback(const ros::TimerEvent &) { ui_.pushButtonPose->setEnabled( true ); PrintInfoHelper( ui_.status, "OK"); } bool PosePublisherPlugin::handleMousePress(QMouseEvent* event) { bool pose_checked = ui_.pushButtonPose->isChecked(); if( !pose_checked) { return false; } if (event->button() == Qt::LeftButton) { is_mouse_down_ = true; arrow_angle_ = 0; #if QT_VERSION >= 0x050000 arrow_tail_position_= map_canvas_->MapGlCoordToFixedFrame( event->localPos() ); #else arrow_tail_position_= map_canvas_->MapGlCoordToFixedFrame( event->posF() ); #endif return true; } return false; } bool PosePublisherPlugin::handleMouseMove(QMouseEvent* event) { if (is_mouse_down_) { #if QT_VERSION >= 0x050000 QPointF head_pos = map_canvas_->MapGlCoordToFixedFrame( event->localPos() ); #else QPointF head_pos = map_canvas_->MapGlCoordToFixedFrame( event->posF() ); #endif arrow_angle_ = atan2( head_pos.y() - arrow_tail_position_.y(), head_pos.x() - arrow_tail_position_.x() ); } return false; } bool PosePublisherPlugin::handleMouseRelease(QMouseEvent* event) { if( !is_mouse_down_ ) { return false; } is_mouse_down_ = false; bool pose_checked = ui_.pushButtonPose->isChecked(); if( !pose_checked ) { return false; } if( pose_checked ) { // Get angle/arrow_tail_position in fixed_frame tf::Quaternion quat_ff = tf::createQuaternionFromYaw(arrow_angle_); geometry_msgs::PoseWithCovarianceStamped pose; // Here it is in the target_frame_ pose.header.frame_id = target_frame_; pose.header.stamp = ros::Time::now(); pose.pose.pose.position.x = arrow_tail_position_.x(); pose.pose.pose.position.y = arrow_tail_position_.y(); pose.pose.pose.position.z = 0.0; tf::quaternionTFToMsg( quat_ff, pose.pose.pose.orientation ); // Try to transform to output_frame swri_transform_util::Transform transform; std::string output_frame = ui_.outputframe->currentText().toStdString(); if (tf_manager_->GetTransform(output_frame, target_frame_, transform)) { pose.header.frame_id = output_frame; tf::Vector3 pose_oframe = transform * tf::Vector3(pose.pose.pose.position.x, pose.pose.pose.position.y, 0); pose.pose.pose.position.x = pose_oframe.x(); pose.pose.pose.position.y = pose_oframe.y(); tf::Quaternion quat_oframe = transform * quat_ff; tf::quaternionTFToMsg( quat_oframe, pose.pose.pose.orientation ); } else { std::stringstream ss; ss << "Couldn't get transform from "<< target_frame_ << " to frame " << output_frame; PrintWarning(ss.str()); } pose_pub_.publish(pose); std::stringstream ss; ss << "Pose published to topic: " << ui_.topic->text().toStdString().c_str() << " in frame " << pose.header.frame_id; PrintInfo(ss.str()); ui_.pushButtonPose->setChecked(false); } return true; } void PosePublisherPlugin::Draw(double x, double y, double scale) { std::array<QPointF, 7> arrow_points; arrow_points[0] = QPointF(10, 0); arrow_points[1] = QPointF(6, -2.5); arrow_points[2] = QPointF(6.5, -1); arrow_points[3] = QPointF(0, -1); arrow_points[4] = QPointF(0, 1); arrow_points[5] = QPointF(6.5, 1); arrow_points[6] = QPointF(6, 2.5); if( is_mouse_down_ ) { QPointF transformed_points[7]; for (size_t i=0; i<7; i++ ) { tf::Vector3 point(arrow_points[i].x(), arrow_points[i].y(), 0); point *= scale*10; point = tf::Transform( tf::createQuaternionFromYaw(arrow_angle_) ) * point; transformed_points[i] = QPointF(point.x() + arrow_tail_position_.x(), point.y() + arrow_tail_position_.y() ); } glColor3f(0.1, 0.9, 0.1); glLineWidth(2); glBegin(GL_TRIANGLE_FAN); for (const QPointF& point: transformed_points ) { glVertex2d(point.x(), point.y()); } glEnd(); glColor3f(0.0, 0.6, 0.0); glBegin(GL_LINE_LOOP); for (const QPointF& point: transformed_points ) { glVertex2d(point.x(), point.y()); } glEnd(); } } void PosePublisherPlugin::LoadConfig(const YAML::Node& node, const std::string& path) { std::string tmp; if (swri_yaml_util::FindValue(node, "topic")) { node["topic"] >> tmp; ui_.topic->setText(QString(tmp.c_str())); topicChanged(ui_.topic->text()); } if (swri_yaml_util::FindValue(node, "output_frame")) { node["output_frame"] >> tmp; ui_.outputframe->addItem(QString(tmp.c_str())); } } void PosePublisherPlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path) { emitter << YAML::Key << "topic" << YAML::Value << ui_.topic->text().toStdString(); emitter << YAML::Key << "output_frame" << YAML::Value << ui_.outputframe->currentText().toStdString(); } void PosePublisherPlugin::on_pushButtonPose_toggled(bool checked) { if(checked) { QPixmap cursor_pixmap = QPixmap(":/images/green-arrow.png"); QApplication::setOverrideCursor(QCursor(cursor_pixmap)); } else { QApplication::restoreOverrideCursor(); } } void PosePublisherPlugin::topicChanged(const QString& topic) { std::stringstream ss; ss << "Publishing points to topic: " << topic.toStdString().c_str(); PrintInfo(ss.str()); if (!topic.isEmpty()) { pose_pub_ = node_.advertise<geometry_msgs::PoseWithCovarianceStamped>(topic.toStdString(), 1000); } } void PosePublisherPlugin::updateFrames() { std::vector<std::string> frames; tf_->getFrameStrings(frames); bool supports_wgs84 = tf_manager_->SupportsTransform( swri_transform_util::_local_xy_frame, swri_transform_util::_wgs84_frame); if (supports_wgs84) { frames.push_back(swri_transform_util::_wgs84_frame); } if (ui_.outputframe->count() >= 0 && static_cast<size_t>(ui_.outputframe->count()) == frames.size()) { bool changed = false; for (size_t i = 0; i < frames.size(); i++) { if (frames[i] != ui_.outputframe->itemText(static_cast<int>(i)).toStdString()) { changed = true; } } if (!changed) return; } std::string output_frame = ui_.outputframe->currentText().toStdString(); ui_.outputframe->clear(); for (size_t i = 0; i < frames.size(); i++) { ui_.outputframe->addItem(frames[i].c_str()); } if (output_frame != "") { int index = ui_.outputframe->findText(output_frame.c_str()); if (index < 0) { ui_.outputframe->addItem(output_frame.c_str()); } index = ui_.outputframe->findText(output_frame.c_str()); ui_.outputframe->setCurrentIndex(index); } } } <|endoftext|>
<commit_before>// Copyright 2018 Google LLC // // 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 // // https://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 "jwt_verify_lib/struct_utils.h" namespace google { namespace jwt_verify { StructUtils::StructUtils(const ::google::protobuf::Struct& struct_pb) : struct_pb_(struct_pb) {} StructUtils::FindResult StructUtils::GetString(const std::string& name, std::string* value) { const auto& fields = struct_pb_.fields(); const auto it = fields.find(name); if (it == fields.end()) { return MISSING; } if (it->second.kind_case() != google::protobuf::Value::kStringValue) { return WRONG_TYPE; } *value = it->second.string_value(); return OK; } StructUtils::FindResult StructUtils::GetInt64(const std::string& name, uint64_t* value) { const auto& fields = struct_pb_.fields(); const auto it = fields.find(name); if (it == fields.end()) { return MISSING; } if (it->second.kind_case() != google::protobuf::Value::kNumberValue) { return WRONG_TYPE; } *value = static_cast<uint64_t>(it->second.number_value()); return OK; } StructUtils::FindResult StructUtils::GetStringList(const std::string& name, std::vector<std::string>* list) { const auto& fields = struct_pb_.fields(); const auto it = fields.find(name); if (it == fields.end()) { return MISSING; } if (it->second.kind_case() == google::protobuf::Value::kStringValue) { list->push_back(it->second.string_value()); return OK; } if (it->second.kind_case() == google::protobuf::Value::kListValue) { for (const auto& v : it->second.list_value().values()) { if (v.kind_case() != google::protobuf::Value::kStringValue) { return WRONG_TYPE; } list->push_back(v.string_value()); } return OK; } return WRONG_TYPE; } } // namespace jwt_verify } // namespace google <commit_msg>Fixed code formatting<commit_after>// Copyright 2018 Google LLC // // 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 // // https://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 "jwt_verify_lib/struct_utils.h" namespace google { namespace jwt_verify { StructUtils::StructUtils(const ::google::protobuf::Struct& struct_pb) : struct_pb_(struct_pb) {} StructUtils::FindResult StructUtils::GetString(const std::string& name, std::string* value) { const auto& fields = struct_pb_.fields(); const auto it = fields.find(name); if (it == fields.end()) { return MISSING; } if (it->second.kind_case() != google::protobuf::Value::kStringValue) { return WRONG_TYPE; } *value = it->second.string_value(); return OK; } StructUtils::FindResult StructUtils::GetInt64(const std::string& name, uint64_t* value) { const auto& fields = struct_pb_.fields(); const auto it = fields.find(name); if (it == fields.end()) { return MISSING; } if (it->second.kind_case() != google::protobuf::Value::kNumberValue) { return WRONG_TYPE; } *value = static_cast<uint64_t>(it->second.number_value()); return OK; } StructUtils::FindResult StructUtils::GetStringList( const std::string& name, std::vector<std::string>* list) { const auto& fields = struct_pb_.fields(); const auto it = fields.find(name); if (it == fields.end()) { return MISSING; } if (it->second.kind_case() == google::protobuf::Value::kStringValue) { list->push_back(it->second.string_value()); return OK; } if (it->second.kind_case() == google::protobuf::Value::kListValue) { for (const auto& v : it->second.list_value().values()) { if (v.kind_case() != google::protobuf::Value::kStringValue) { return WRONG_TYPE; } list->push_back(v.string_value()); } return OK; } return WRONG_TYPE; } } // namespace jwt_verify } // namespace google <|endoftext|>
<commit_before>/* * Note: LoRaWAN per sub-band duty-cycle limitation is enforced (1% in g1, * 0.1% in g2). * * Change DEVADDR to a unique address! * See http://thethingsnetwork.org/wiki/AddressSpace * * Do not forget to define the radio type correctly in config.h. */ #include <SPI.h> #include "Lora.h" #include "Logging.h" #if defined(DISABLE_INVERT_IQ_ON_RX) #error This example requires DISABLE_INVERT_IQ_ON_RX to be NOT set. Update \ config.h in the lmic library to set it. #endif // Pin mapping const lmic_pinmap lmic_pins = { .nss = 19, .rxtx = LMIC_UNUSED_PIN, .rst = 18, .dio = {16, 5, 6}, // Moved dio0 from 17 because of overlapping ExtInt4 (pin6) }; typedef enum LoraModeEnum { NeedsConfiguration, // Not enough information to do anything ReadyToJoin, // Has AppKey, AppEUI, and DevEUI Ready, // We have session vars via ABP or OTAA - communicate at will } LoraMode; static LoraMode mode = NeedsConfiguration; static JoinResultCallbackFn onJoinCb = NULL; static TransmitResultCallbackFn onTransmitCb = NULL; static u1_t join_appkey[16]; static u1_t join_appeui[8]; static u1_t join_deveui[8]; void os_getArtEui (u1_t* buf) { debugLogData("Asking for AppEUI", join_appeui, sizeof(join_appeui)); memcpy(buf, join_appeui, sizeof(join_appeui)); } void os_getDevEui (u1_t* buf) { debugLogData("Asking for DevEUI", join_deveui, sizeof(join_deveui)); memcpy(buf, join_deveui, sizeof(join_deveui)); } void os_getDevKey (u1_t* buf) { debugLogData("Asking for AppKey", join_appkey, sizeof(join_appkey)); memcpy(buf, join_appkey, sizeof(join_appkey)); } static osjob_t timeoutjob; static void txtimeout_func(osjob_t *job) { if (LMIC.opmode & OP_JOINING) { // keep waiting.. and don't time out. return; } digitalWrite(LED_BUILTIN, LOW); // off Log.Debug(F("Transmit Timeout" CR)); //txActive = false; LMIC_clrTxData (); } bool loraSendBytes(uint8_t *data, uint16_t len) { if (mode!=Ready) { Log.Debug(F("mode not ready, not sending" CR)); return false; // Did not enqueue } ostime_t t = os_getTime(); //os_setTimedCallback(&txjob, t + ms2osticks(100), tx_func); // Check if there is not a current TX/RX job running if (LMIC.opmode & OP_TXRXPEND) { Log.Debug(F("OP_TXRXPEND, not sending" CR)); return false; // Did not enqueue } else { // Prepare upstream data transmission at the next possible time. Log.Debug(F("Packet queued" CR)); digitalWrite(LED_BUILTIN, HIGH); // off LMIC_setTxData2(1, data, len, 0); if (! (LMIC.opmode & OP_JOINING)) { // connection is up, message is queued: // Timeout TX after 20 seconds os_setTimedCallback(&timeoutjob, t + ms2osticks(20000), txtimeout_func); } return true; } } void onEvent (ev_t ev) { Log.Debug("%d: ", os_getTime()); switch(ev) { case EV_SCAN_TIMEOUT: Log.Debug(F("EV_SCAN_TIMEOUT")); break; case EV_BEACON_FOUND: Log.Debug(F("EV_BEACON_FOUND")); break; case EV_BEACON_MISSED: Log.Debug(F("EV_BEACON_MISSED")); break; case EV_BEACON_TRACKED: Log.Debug(F("EV_BEACON_TRACKED")); break; case EV_JOINING: Log.Debug(F("EV_JOINING")); break; case EV_JOINED: Log.Debug(F("EV_JOINED")); mode = Ready; if (onJoinCb) { u4_t netid = 0; devaddr_t devaddr = 0; u1_t nwkSKey[16]; u1_t appSKey[16]; LMIC_getSessionKeys(&netid, &devaddr, nwkSKey, appSKey); devaddr = __builtin_bswap32(devaddr); // Settings and Bluetooth deal with devAddr as big endian byte array onJoinCb(appSKey, nwkSKey, (u1_t *)&devaddr); } break; case EV_RFU1: Log.Debug(F("EV_RFU1")); break; case EV_JOIN_FAILED: Log.Debug(F("EV_JOIN_FAILED")); if (onJoinCb) { onJoinCb(NULL, NULL, NULL); } break; case EV_REJOIN_FAILED: Log.Debug(F("EV_REJOIN_FAILED")); break; case EV_TXCOMPLETE: os_clearCallback(&timeoutjob); Log.Debug(F("EV_TXCOMPLETE (includes waiting for RX windows)" CR)); digitalWrite(LED_BUILTIN, LOW); // off if (onTransmitCb) { Log.Debug(F("Calling transmit callback..." CR)); u1_t *received = NULL; u1_t len = 0; if (LMIC.dataLen>0) { received = LMIC.frame+LMIC.dataBeg; len = LMIC.dataLen; // Log received data. u1_t *p = received; for (int i=0; i<LMIC.dataLen; ++i) { Log.Debug("%x", *p++); } // Log.Debug("%*h", LMIC.dataLen, LMIC.frame+LMIC.dataBeg); Log.Debug(CR); } uint32_t tx_seq_no = LMIC_getSeqnoUp()-1; // LMIC_getSeqnoUp returns the NEXT one. We want to return the one used. onTransmitCb(0 /* success */, tx_seq_no, received, len); } break; case EV_LOST_TSYNC: Log.Debug(F("EV_LOST_TSYNC")); break; case EV_RESET: Log.Debug(F("EV_RESET")); break; case EV_RXCOMPLETE: // data received in ping slot Log.Debug(F("EV_RXCOMPLETE")); break; case EV_LINK_DEAD: Log.Debug(F("EV_LINK_DEAD")); break; case EV_LINK_ALIVE: Log.Debug(F("EV_LINK_ALIVE")); break; case EV_SCAN_FOUND: Log.Debug(F("EV_SCAN_FOUND")); break; case EV_TXSTART: Log.Debug(F("EV_TXSTART")); break; default: Log.Debug(F("Unknown event: %d"), (int)ev); break; } Log.Debug(CR); } static void configureLora(uint32_t seq_no) { #if defined(CFG_eu868) // Set up the channels used by the Things Network, which corresponds // to the defaults of most gateways. Without this, only three base // channels from the LoRaWAN specification are used, which certainly // works, so it is good for debugging, but can overload those // frequencies, so be sure to configure the full frequency range of // your network here (unless your network autoconfigures them). // Setting up channels should happen after LMIC_setSession, as that // configures the minimal channel set. LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B), BAND_CENTI); // g-band LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(3, 867100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(4, 867300000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(5, 867500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(6, 867700000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(7, 867900000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(8, 868800000, DR_RANGE_MAP(DR_FSK, DR_FSK), BAND_MILLI); // g2-band // TTN defines an additional channel at 869.525Mhz using SF9 for class B // devices' ping slots. LMIC does not have an easy way to define set this // frequency and support for class B is spotty and untested, so this // frequency is not configured here. #endif LMIC_selectSubBand(1); // Disable link check validation LMIC_setLinkCheckMode(0); // Set data rate and transmit power (note: txpow seems to be ignored by the library) LMIC_setDrTxpow(DR_SF10,20); debugLog("Set LoRa seq no:", seq_no); LMIC_setSeqnoUp(seq_no); } void setupLora(TransmitResultCallbackFn txcb) { onTransmitCb = txcb; #ifdef VCC_ENABLE // For Pinoccio Scout boards pinMode(VCC_ENABLE, OUTPUT); digitalWrite(VCC_ENABLE, HIGH); delay(1000); #endif } void loopLora() { if (mode!=NeedsConfiguration) { os_runloop_once(); } } void loraJoin(uint32_t seq_no, u1_t *appkey, u1_t *appeui, u1_t *deveui, JoinResultCallbackFn joincb) { onJoinCb = joincb; memcpy(join_appkey, appkey, sizeof(join_appkey)); memcpy(join_appeui, appeui, sizeof(join_appeui)); memcpy(join_deveui, deveui, sizeof(join_deveui)); // LMIC init os_init(); // Reset the MAC state. Session and pending data transfers will be discarded. LMIC_reset(); configureLora(seq_no); if (LMIC_startJoining()) { debugPrint("Started joining."); } else { debugPrint("Error: Expected to start joining, but did not!"); } mode = ReadyToJoin; } void loraSetSessionKeys(uint32_t seq_no, u1_t *appskey, u1_t *nwkskey, u1_t *devaddr) { debugLogData("Devaddr: ", devaddr, 4); debugLogData("appskey", appskey, 16); debugLogData("nwkskey", nwkskey, 16); // LMIC init os_init(); // Reset the MAC state. Session and pending data transfers will be discarded. LMIC_reset(); devaddr_t da = *(devaddr_t *)devaddr; da = __builtin_bswap32(da); // Settings and Bluetooth deal with devAddr as big endian byte array LMIC_setSession(0x1 /* TTN_NETWORK_ID */, da, nwkskey, appskey); configureLora(seq_no); mode = Ready; } void loraSetSF(uint sf) { dr_t dr; switch (sf) { case 7: dr = DR_SF7; break; case 8: dr = DR_SF8; break; case 9: dr = DR_SF9; break; case 10: dr = DR_SF10; break; default: dr = DR_SF10; Log.Debug(F("Invalid SF value: %d" CR), sf); break; } LMIC_setDrTxpow(dr,20); } <commit_msg>Modified LoRa pin definition so Hackathon boards work.<commit_after>/* * Note: LoRaWAN per sub-band duty-cycle limitation is enforced (1% in g1, * 0.1% in g2). * * Change DEVADDR to a unique address! * See http://thethingsnetwork.org/wiki/AddressSpace * * Do not forget to define the radio type correctly in config.h. */ #include <SPI.h> #include "Lora.h" #include "Logging.h" #if defined(DISABLE_INVERT_IQ_ON_RX) #error This example requires DISABLE_INVERT_IQ_ON_RX to be NOT set. Update \ config.h in the lmic library to set it. #endif /* * Pin mapping * adjusted to conform to pinout shown in image * from this repo's image. */ const lmic_pinmap lmic_pins = { #if 1 .nss = 6 /*feather wing pin D*/, .rxtx = LMIC_UNUSED_PIN, .rst = 5/*feather wing pin E*/, .dio = {12/*feather wing pin above A*/, 11/*feather wing pin A*/, 10 /*feather wing pin B*/}, #else // alternate pinout .nss = 19, .rxtx = LMIC_UNUSED_PIN, .rst = 18, .dio = {16,5,6}, #endif }; typedef enum LoraModeEnum { NeedsConfiguration, // Not enough information to do anything ReadyToJoin, // Has AppKey, AppEUI, and DevEUI Ready, // We have session vars via ABP or OTAA - communicate at will } LoraMode; static LoraMode mode = NeedsConfiguration; static JoinResultCallbackFn onJoinCb = NULL; static TransmitResultCallbackFn onTransmitCb = NULL; static u1_t join_appkey[16]; static u1_t join_appeui[8]; static u1_t join_deveui[8]; void os_getArtEui (u1_t* buf) { debugLogData("Asking for AppEUI", join_appeui, sizeof(join_appeui)); memcpy(buf, join_appeui, sizeof(join_appeui)); } void os_getDevEui (u1_t* buf) { debugLogData("Asking for DevEUI", join_deveui, sizeof(join_deveui)); memcpy(buf, join_deveui, sizeof(join_deveui)); } void os_getDevKey (u1_t* buf) { debugLogData("Asking for AppKey", join_appkey, sizeof(join_appkey)); memcpy(buf, join_appkey, sizeof(join_appkey)); } static osjob_t timeoutjob; static void txtimeout_func(osjob_t *job) { if (LMIC.opmode & OP_JOINING) { // keep waiting.. and don't time out. return; } digitalWrite(LED_BUILTIN, LOW); // off Log.Debug(F("Transmit Timeout" CR)); //txActive = false; LMIC_clrTxData (); } bool loraSendBytes(uint8_t *data, uint16_t len) { if (mode!=Ready) { Log.Debug(F("mode not ready, not sending" CR)); return false; // Did not enqueue } ostime_t t = os_getTime(); //os_setTimedCallback(&txjob, t + ms2osticks(100), tx_func); // Check if there is not a current TX/RX job running if (LMIC.opmode & OP_TXRXPEND) { Log.Debug(F("OP_TXRXPEND, not sending" CR)); return false; // Did not enqueue } else { // Prepare upstream data transmission at the next possible time. Log.Debug(F("Packet queued" CR)); digitalWrite(LED_BUILTIN, HIGH); // off LMIC_setTxData2(1, data, len, 0); if (! (LMIC.opmode & OP_JOINING)) { // connection is up, message is queued: // Timeout TX after 20 seconds os_setTimedCallback(&timeoutjob, t + ms2osticks(20000), txtimeout_func); } return true; } } void onEvent (ev_t ev) { Log.Debug("%d: ", os_getTime()); switch(ev) { case EV_SCAN_TIMEOUT: Log.Debug(F("EV_SCAN_TIMEOUT")); break; case EV_BEACON_FOUND: Log.Debug(F("EV_BEACON_FOUND")); break; case EV_BEACON_MISSED: Log.Debug(F("EV_BEACON_MISSED")); break; case EV_BEACON_TRACKED: Log.Debug(F("EV_BEACON_TRACKED")); break; case EV_JOINING: Log.Debug(F("EV_JOINING")); break; case EV_JOINED: Log.Debug(F("EV_JOINED")); mode = Ready; if (onJoinCb) { u4_t netid = 0; devaddr_t devaddr = 0; u1_t nwkSKey[16]; u1_t appSKey[16]; LMIC_getSessionKeys(&netid, &devaddr, nwkSKey, appSKey); devaddr = __builtin_bswap32(devaddr); // Settings and Bluetooth deal with devAddr as big endian byte array onJoinCb(appSKey, nwkSKey, (u1_t *)&devaddr); } break; case EV_RFU1: Log.Debug(F("EV_RFU1")); break; case EV_JOIN_FAILED: Log.Debug(F("EV_JOIN_FAILED")); if (onJoinCb) { onJoinCb(NULL, NULL, NULL); } break; case EV_REJOIN_FAILED: Log.Debug(F("EV_REJOIN_FAILED")); break; case EV_TXCOMPLETE: os_clearCallback(&timeoutjob); Log.Debug(F("EV_TXCOMPLETE (includes waiting for RX windows)" CR)); digitalWrite(LED_BUILTIN, LOW); // off if (onTransmitCb) { Log.Debug(F("Calling transmit callback..." CR)); u1_t *received = NULL; u1_t len = 0; if (LMIC.dataLen>0) { received = LMIC.frame+LMIC.dataBeg; len = LMIC.dataLen; // Log received data. u1_t *p = received; for (int i=0; i<LMIC.dataLen; ++i) { Log.Debug("%x", *p++); } // Log.Debug("%*h", LMIC.dataLen, LMIC.frame+LMIC.dataBeg); Log.Debug(CR); } uint32_t tx_seq_no = LMIC_getSeqnoUp()-1; // LMIC_getSeqnoUp returns the NEXT one. We want to return the one used. onTransmitCb(0 /* success */, tx_seq_no, received, len); } break; case EV_LOST_TSYNC: Log.Debug(F("EV_LOST_TSYNC")); break; case EV_RESET: Log.Debug(F("EV_RESET")); break; case EV_RXCOMPLETE: // data received in ping slot Log.Debug(F("EV_RXCOMPLETE")); break; case EV_LINK_DEAD: Log.Debug(F("EV_LINK_DEAD")); break; case EV_LINK_ALIVE: Log.Debug(F("EV_LINK_ALIVE")); break; case EV_SCAN_FOUND: Log.Debug(F("EV_SCAN_FOUND")); break; case EV_TXSTART: Log.Debug(F("EV_TXSTART")); break; default: Log.Debug(F("Unknown event: %d"), (int)ev); break; } Log.Debug(CR); } static void configureLora(uint32_t seq_no) { #if defined(CFG_eu868) // Set up the channels used by the Things Network, which corresponds // to the defaults of most gateways. Without this, only three base // channels from the LoRaWAN specification are used, which certainly // works, so it is good for debugging, but can overload those // frequencies, so be sure to configure the full frequency range of // your network here (unless your network autoconfigures them). // Setting up channels should happen after LMIC_setSession, as that // configures the minimal channel set. LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B), BAND_CENTI); // g-band LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(3, 867100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(4, 867300000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(5, 867500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(6, 867700000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(7, 867900000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band LMIC_setupChannel(8, 868800000, DR_RANGE_MAP(DR_FSK, DR_FSK), BAND_MILLI); // g2-band // TTN defines an additional channel at 869.525Mhz using SF9 for class B // devices' ping slots. LMIC does not have an easy way to define set this // frequency and support for class B is spotty and untested, so this // frequency is not configured here. #endif LMIC_selectSubBand(1); // Disable link check validation LMIC_setLinkCheckMode(0); // Set data rate and transmit power (note: txpow seems to be ignored by the library) LMIC_setDrTxpow(DR_SF10,20); debugLog("Set LoRa seq no:", seq_no); LMIC_setSeqnoUp(seq_no); } void setupLora(TransmitResultCallbackFn txcb) { onTransmitCb = txcb; #ifdef VCC_ENABLE // For Pinoccio Scout boards pinMode(VCC_ENABLE, OUTPUT); digitalWrite(VCC_ENABLE, HIGH); delay(1000); #endif } void loopLora() { if (mode!=NeedsConfiguration) { os_runloop_once(); } } void loraJoin(uint32_t seq_no, u1_t *appkey, u1_t *appeui, u1_t *deveui, JoinResultCallbackFn joincb) { onJoinCb = joincb; memcpy(join_appkey, appkey, sizeof(join_appkey)); memcpy(join_appeui, appeui, sizeof(join_appeui)); memcpy(join_deveui, deveui, sizeof(join_deveui)); // LMIC init os_init(); // Reset the MAC state. Session and pending data transfers will be discarded. LMIC_reset(); configureLora(seq_no); if (LMIC_startJoining()) { debugPrint("Started joining."); } else { debugPrint("Error: Expected to start joining, but did not!"); } mode = ReadyToJoin; } void loraSetSessionKeys(uint32_t seq_no, u1_t *appskey, u1_t *nwkskey, u1_t *devaddr) { debugLogData("Devaddr: ", devaddr, 4); debugLogData("appskey", appskey, 16); debugLogData("nwkskey", nwkskey, 16); // LMIC init os_init(); // Reset the MAC state. Session and pending data transfers will be discarded. LMIC_reset(); devaddr_t da = *(devaddr_t *)devaddr; da = __builtin_bswap32(da); // Settings and Bluetooth deal with devAddr as big endian byte array LMIC_setSession(0x1 /* TTN_NETWORK_ID */, da, nwkskey, appskey); configureLora(seq_no); mode = Ready; } void loraSetSF(uint sf) { dr_t dr; switch (sf) { case 7: dr = DR_SF7; break; case 8: dr = DR_SF8; break; case 9: dr = DR_SF9; break; case 10: dr = DR_SF10; break; default: dr = DR_SF10; Log.Debug(F("Invalid SF value: %d" CR), sf); break; } LMIC_setDrTxpow(dr,20); } <|endoftext|>
<commit_before>#include <exception> #include <iostream> #include <stdexcept> #include <unordered_map> #include <unordered_set> #include <tclap/CmdLine.h> #include "printer/cprinter.hpp" #include "printer/cudaprinter.hpp" #include "printer/infoprinter.hpp" #include "printer/printeropt.hpp" #include "printer/simd.hpp" #include "modccutil.hpp" #include "module.hpp" #include "parser.hpp" #include "perfvisitor.hpp" #include "io/bulkio.hpp" using std::cout; using std::cerr; // Options and option parsing: int report_error(const std::string& message) { cerr << red("error: ") << message << "\n"; return 1; } int report_ice(const std::string& message) { cerr << red("internal compiler error: ") << message << "\n" << "\nPlease report this error to the modcc developers.\n"; return 1; } enum class targetKind { cpu, gpu, }; std::unordered_map<std::string, targetKind> targetKindMap = { {"cpu", targetKind::cpu}, {"gpu", targetKind::gpu}, }; std::unordered_map<std::string, enum simd_spec::simd_abi> simdAbiMap = { {"none", simd_spec::none}, {"avx", simd_spec::avx}, {"avx2", simd_spec::avx2}, {"avx512", simd_spec::avx512}, {"default_abi", simd_spec::default_abi}, {"native", simd_spec::native} }; template <typename Map, typename V> auto key_by_value(const Map& map, const V& v) -> decltype(map.begin()->first) { for (const auto& kv: map) { if (kv.second==v) return kv.first; } throw std::out_of_range("value not found in map"); } struct Options { std::string outprefix; std::string modfile; std::string modulename; bool verbose = true; bool analysis = false; std::unordered_set<targetKind, enum_hash> targets; }; // Helper for formatting tabulated output (option reporting). struct table_prefix { std::string text; }; std::ostream& operator<<(std::ostream& out, const table_prefix& tb) { return out << cyan("| "+tb.text) << std::right << std::setw(58-tb.text.size()); }; std::ostream& operator<<(std::ostream& out, simd_spec simd) { std::stringstream s; s << key_by_value(simdAbiMap, simd.abi); if (simd.width!=0) { s << '/' << simd.width; } return out << s.str(); } std::ostream& operator<<(std::ostream& out, const Options& opt) { static const char* noyes[2] = {"no", "yes"}; static const std::string line_end = cyan(" |") + "\n"; std::string targets; for (targetKind t: opt.targets) { targets += " "+key_by_value(targetKindMap, t); } return out << table_prefix{"file"} << opt.modfile << line_end << table_prefix{"output"} << (opt.outprefix.empty()? "-": opt.outprefix) << line_end << table_prefix{"verbose"} << noyes[opt.verbose] << line_end << table_prefix{"targets"} << targets << line_end << table_prefix{"analysis"} << noyes[opt.analysis] << line_end; } std::ostream& operator<<(std::ostream& out, const printer_options& popt) { static const char* noyes[2] = {"no", "yes"}; static const std::string line_end = cyan(" |") + "\n"; return out << table_prefix{"namespace"} << popt.cpp_namespace << line_end << table_prefix{"profile"} << noyes[popt.profile] << line_end << table_prefix{"simd"} << popt.simd << line_end; } // Constraints for TCLAP arguments that are names for enumertion values. struct MapConstraint: private std::vector<std::string>, public TCLAP::ValuesConstraint<std::string> { template <typename Map> MapConstraint(const Map& map): std::vector<std::string>(keys(map)), TCLAP::ValuesConstraint<std::string>(static_cast<std::vector<std::string>&>(*this)) {} template <typename Map> static std::vector<std::string> keys(const Map& map) { std::vector<std::string> ks; for (auto& kv: map) ks.push_back(kv.first); return ks; } }; simd_spec parse_simd_spec(std::string spec) { auto npos = std::string::npos; unsigned width = 0; auto suffix = spec.find_last_of('/'); if (suffix!=npos) { width = stoul(spec.substr(suffix+1)); spec = spec.substr(0, suffix); } return simd_spec(simdAbiMap.at(spec.c_str()), width); } struct SimdAbiConstraint: public TCLAP::Constraint<std::string> { std::string description() const override { return "simd_abi[/n]"; } std::string shortID() const override { return description(); } bool check(const std::string& spec) const override { try { (void)parse_simd_spec(spec); return true; } catch (...) { return false; } } }; int main(int argc, char **argv) { Options opt; printer_options popt; try { TCLAP::CmdLine cmd("modcc code generator for arbor", ' ', "0.1"); TCLAP::UnlabeledValueArg<std::string> fin_arg("input_file", "the name of the .mod file to compile", true, "", "filename", cmd); TCLAP::ValueArg<std::string> fout_arg("o", "output", "prefix for output file names", false, "", "filename", cmd); TCLAP::ValueArg<std::string> namespace_arg("N", "namespace", "namespace for generated code", false, "arb", "name", cmd); MapConstraint targets_arg_constraint(targetKindMap); TCLAP::MultiArg<std::string> target_arg("t", "target", "build module for cpu or gpu back-end", false, &targets_arg_constraint, cmd); TCLAP::SwitchArg simd_arg("s", "simd", "generate code with explicit SIMD vectorization", cmd, false); SimdAbiConstraint simd_abi_constraint; TCLAP::ValueArg<std::string> simd_abi_arg("S", "simd-abi", "override SIMD ABI in generated code. Use /n suffix to force SIMD width to be size n. Examples: 'avx2', 'native/4', ...", false, "", &simd_abi_constraint, cmd); TCLAP::SwitchArg profile_arg("P","profile","build with profiled kernels", cmd, false); TCLAP::SwitchArg verbose_arg("V","verbose","toggle verbose mode", cmd, false); TCLAP::SwitchArg analysis_arg("A","analyse","toggle analysis mode", cmd, false); TCLAP::ValueArg<std::string> module_arg("m", "module", "module name to use (default taken from input .mod file)", false, "", "module", cmd); cmd.parse(argc, argv); opt.outprefix = fout_arg.getValue(); opt.modfile = fin_arg.getValue(); opt.modulename = module_arg.getValue(); opt.verbose = verbose_arg.getValue(); opt.analysis = analysis_arg.getValue(); popt.cpp_namespace = namespace_arg.getValue(); popt.profile = profile_arg.getValue(); if (simd_arg.getValue()) { popt.simd = simd_spec(simd_spec::native); if (!simd_abi_arg.getValue().empty()) { popt.simd = parse_simd_spec(simd_abi_arg.getValue()); } } for (auto& target: target_arg.getValue()) { opt.targets.insert(targetKindMap.at(target)); } } catch(TCLAP::ArgException &e) { return report_error(e.error()+" for argument "+to_string(e.argId())); } try { auto emit_header = [&opt](const char* h) { if (opt.verbose) { cout << green("[") << h << green("]") << "\n"; } }; if (opt.verbose) { static const std::string tableline = cyan("."+std::string(60, '-')+".")+"\n"; cout << tableline; cout << opt; cout << popt; cout << tableline; } // Load module file and initialize Module object. Module m(io::read_all(opt.modfile), opt.modfile); if (m.empty()) { return report_error("empty file: "+opt.modfile); } if (!opt.modulename.empty()) { m.module_name(opt.modulename); } // Perform parsing and semantic analysis passes. emit_header("parsing"); Parser p(m, false); if (!p.parse()) { // Parser::parse() writes its own errors to stderr. return 1; } emit_header("semantic analysis"); m.semantic(); if (m.has_warning()) { cerr << m.warning_string() << "\n"; } if (m.has_error()) { return report_error(m.error_string()); } // Generate backend-specific sources for each backend provided. emit_header("code generation"); // If no output prefix given, use the module name. std::string prefix = opt.outprefix.empty()? m.module_name(): opt.outprefix; io::write_all(build_info_header(m, popt), prefix+".hpp"); for (targetKind target: opt.targets) { std::string outfile = prefix; switch (target) { case targetKind::gpu: io::write_all(emit_cuda_cpp_source(m, popt), outfile+"_gpu.cpp"); io::write_all(emit_cuda_cu_source(m, popt), outfile+"_gpu.cu"); break; case targetKind::cpu: io::write_all(emit_cpp_source(m, popt), outfile+"_cpu.cpp"); break; } } // Optional analysis report. if (opt.analysis) { cout << green("performance analysis\n"); for (auto &symbol: m.symbols()) { if (auto method = symbol.second->is_api_method()) { cout << white("-------------------------\n"); cout << yellow("method " + method->name()) << "\n"; cout << white("-------------------------\n"); FlopVisitor flops; method->accept(&flops); cout << white("FLOPS\n") << flops.print() << "\n"; MemOpVisitor memops; method->accept(&memops); cout << white("MEMOPS\n") << memops.print() << "\n"; } } } } catch(compiler_exception& e) { return report_ice(e.what()+std::string(" @ ")+to_string(e.location())); } catch(std::exception& e) { return report_ice(e.what()); } catch(...) { return report_ice(""); } return 0; } <commit_msg>Better error message on missing file.<commit_after>#include <exception> #include <iostream> #include <stdexcept> #include <unordered_map> #include <unordered_set> #include <tclap/CmdLine.h> #include "printer/cprinter.hpp" #include "printer/cudaprinter.hpp" #include "printer/infoprinter.hpp" #include "printer/printeropt.hpp" #include "printer/simd.hpp" #include "modccutil.hpp" #include "module.hpp" #include "parser.hpp" #include "perfvisitor.hpp" #include "io/bulkio.hpp" using std::cout; using std::cerr; // Options and option parsing: int report_error(const std::string& message) { cerr << red("error: ") << message << "\n"; return 1; } int report_ice(const std::string& message) { cerr << red("internal compiler error: ") << message << "\n" << "\nPlease report this error to the modcc developers.\n"; return 1; } enum class targetKind { cpu, gpu, }; std::unordered_map<std::string, targetKind> targetKindMap = { {"cpu", targetKind::cpu}, {"gpu", targetKind::gpu}, }; std::unordered_map<std::string, enum simd_spec::simd_abi> simdAbiMap = { {"none", simd_spec::none}, {"avx", simd_spec::avx}, {"avx2", simd_spec::avx2}, {"avx512", simd_spec::avx512}, {"default_abi", simd_spec::default_abi}, {"native", simd_spec::native} }; template <typename Map, typename V> auto key_by_value(const Map& map, const V& v) -> decltype(map.begin()->first) { for (const auto& kv: map) { if (kv.second==v) return kv.first; } throw std::out_of_range("value not found in map"); } struct Options { std::string outprefix; std::string modfile; std::string modulename; bool verbose = true; bool analysis = false; std::unordered_set<targetKind, enum_hash> targets; }; // Helper for formatting tabulated output (option reporting). struct table_prefix { std::string text; }; std::ostream& operator<<(std::ostream& out, const table_prefix& tb) { return out << cyan("| "+tb.text) << std::right << std::setw(58-tb.text.size()); }; std::ostream& operator<<(std::ostream& out, simd_spec simd) { std::stringstream s; s << key_by_value(simdAbiMap, simd.abi); if (simd.width!=0) { s << '/' << simd.width; } return out << s.str(); } std::ostream& operator<<(std::ostream& out, const Options& opt) { static const char* noyes[2] = {"no", "yes"}; static const std::string line_end = cyan(" |") + "\n"; std::string targets; for (targetKind t: opt.targets) { targets += " "+key_by_value(targetKindMap, t); } return out << table_prefix{"file"} << opt.modfile << line_end << table_prefix{"output"} << (opt.outprefix.empty()? "-": opt.outprefix) << line_end << table_prefix{"verbose"} << noyes[opt.verbose] << line_end << table_prefix{"targets"} << targets << line_end << table_prefix{"analysis"} << noyes[opt.analysis] << line_end; } std::ostream& operator<<(std::ostream& out, const printer_options& popt) { static const char* noyes[2] = {"no", "yes"}; static const std::string line_end = cyan(" |") + "\n"; return out << table_prefix{"namespace"} << popt.cpp_namespace << line_end << table_prefix{"profile"} << noyes[popt.profile] << line_end << table_prefix{"simd"} << popt.simd << line_end; } // Constraints for TCLAP arguments that are names for enumertion values. struct MapConstraint: private std::vector<std::string>, public TCLAP::ValuesConstraint<std::string> { template <typename Map> MapConstraint(const Map& map): std::vector<std::string>(keys(map)), TCLAP::ValuesConstraint<std::string>(static_cast<std::vector<std::string>&>(*this)) {} template <typename Map> static std::vector<std::string> keys(const Map& map) { std::vector<std::string> ks; for (auto& kv: map) ks.push_back(kv.first); return ks; } }; simd_spec parse_simd_spec(std::string spec) { auto npos = std::string::npos; unsigned width = 0; auto suffix = spec.find_last_of('/'); if (suffix!=npos) { width = stoul(spec.substr(suffix+1)); spec = spec.substr(0, suffix); } return simd_spec(simdAbiMap.at(spec.c_str()), width); } struct SimdAbiConstraint: public TCLAP::Constraint<std::string> { std::string description() const override { return "simd_abi[/n]"; } std::string shortID() const override { return description(); } bool check(const std::string& spec) const override { try { (void)parse_simd_spec(spec); return true; } catch (...) { return false; } } }; int main(int argc, char **argv) { Options opt; printer_options popt; try { TCLAP::CmdLine cmd("modcc code generator for arbor", ' ', "0.1"); TCLAP::UnlabeledValueArg<std::string> fin_arg("input_file", "the name of the .mod file to compile", true, "", "filename", cmd); TCLAP::ValueArg<std::string> fout_arg("o", "output", "prefix for output file names", false, "", "filename", cmd); TCLAP::ValueArg<std::string> namespace_arg("N", "namespace", "namespace for generated code", false, "arb", "name", cmd); MapConstraint targets_arg_constraint(targetKindMap); TCLAP::MultiArg<std::string> target_arg("t", "target", "build module for cpu or gpu back-end", false, &targets_arg_constraint, cmd); TCLAP::SwitchArg simd_arg("s", "simd", "generate code with explicit SIMD vectorization", cmd, false); SimdAbiConstraint simd_abi_constraint; TCLAP::ValueArg<std::string> simd_abi_arg("S", "simd-abi", "override SIMD ABI in generated code. Use /n suffix to force SIMD width to be size n. Examples: 'avx2', 'native/4', ...", false, "", &simd_abi_constraint, cmd); TCLAP::SwitchArg profile_arg("P","profile","build with profiled kernels", cmd, false); TCLAP::SwitchArg verbose_arg("V","verbose","toggle verbose mode", cmd, false); TCLAP::SwitchArg analysis_arg("A","analyse","toggle analysis mode", cmd, false); TCLAP::ValueArg<std::string> module_arg("m", "module", "module name to use (default taken from input .mod file)", false, "", "module", cmd); cmd.parse(argc, argv); opt.outprefix = fout_arg.getValue(); opt.modfile = fin_arg.getValue(); opt.modulename = module_arg.getValue(); opt.verbose = verbose_arg.getValue(); opt.analysis = analysis_arg.getValue(); popt.cpp_namespace = namespace_arg.getValue(); popt.profile = profile_arg.getValue(); if (simd_arg.getValue()) { popt.simd = simd_spec(simd_spec::native); if (!simd_abi_arg.getValue().empty()) { popt.simd = parse_simd_spec(simd_abi_arg.getValue()); } } for (auto& target: target_arg.getValue()) { opt.targets.insert(targetKindMap.at(target)); } } catch(TCLAP::ArgException &e) { return report_error(e.error()+" for argument "+to_string(e.argId())); } try { auto emit_header = [&opt](const char* h) { if (opt.verbose) { cout << green("[") << h << green("]") << "\n"; } }; if (opt.verbose) { static const std::string tableline = cyan("."+std::string(60, '-')+".")+"\n"; cout << tableline; cout << opt; cout << popt; cout << tableline; } // Load module file and initialize Module object. Module m(io::read_all(opt.modfile), opt.modfile); if (m.empty()) { return report_error("empty file: "+opt.modfile); } if (!opt.modulename.empty()) { m.module_name(opt.modulename); } // Perform parsing and semantic analysis passes. emit_header("parsing"); Parser p(m, false); if (!p.parse()) { // Parser::parse() writes its own errors to stderr. return 1; } emit_header("semantic analysis"); m.semantic(); if (m.has_warning()) { cerr << m.warning_string() << "\n"; } if (m.has_error()) { return report_error(m.error_string()); } // Generate backend-specific sources for each backend provided. emit_header("code generation"); // If no output prefix given, use the module name. std::string prefix = opt.outprefix.empty()? m.module_name(): opt.outprefix; io::write_all(build_info_header(m, popt), prefix+".hpp"); for (targetKind target: opt.targets) { std::string outfile = prefix; switch (target) { case targetKind::gpu: io::write_all(emit_cuda_cpp_source(m, popt), outfile+"_gpu.cpp"); io::write_all(emit_cuda_cu_source(m, popt), outfile+"_gpu.cu"); break; case targetKind::cpu: io::write_all(emit_cpp_source(m, popt), outfile+"_cpu.cpp"); break; } } // Optional analysis report. if (opt.analysis) { cout << green("performance analysis\n"); for (auto &symbol: m.symbols()) { if (auto method = symbol.second->is_api_method()) { cout << white("-------------------------\n"); cout << yellow("method " + method->name()) << "\n"; cout << white("-------------------------\n"); FlopVisitor flops; method->accept(&flops); cout << white("FLOPS\n") << flops.print() << "\n"; MemOpVisitor memops; method->accept(&memops); cout << white("MEMOPS\n") << memops.print() << "\n"; } } } } catch (io::bulkio_error& e) { return report_error(e.what()); } catch (compiler_exception& e) { return report_ice(e.what()+std::string(" @ ")+to_string(e.location())); } catch (std::exception& e) { return report_ice(e.what()); } catch (...) { return report_ice(""); } return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2005-2012 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include "Models/TimeSeries/ArModel.hpp" #include <complex> #include <functional> #include "LinAlg/Eigen.hpp" #include "Models/SufstatAbstractCombineImpl.hpp" #include "cpputil/Polynomial.hpp" #include "cpputil/report_error.hpp" #include "distributions.hpp" namespace BOOM{ ArSuf::ArSuf(int number_of_lags) : reg_suf_(new NeRegSuf(number_of_lags)), x_(number_of_lags) {} ArSuf * ArSuf::clone()const{return new ArSuf(*this);} void ArSuf::clear(){ lags_.clear(); reg_suf_->clear(); } void ArSuf::Update(const DoubleData &y) { double yvalue = y.value(); if (lags_.size() == reg_suf_->size()) { x_.assign(lags_.begin(), lags_.end()); reg_suf_->add_mixture_data(yvalue, x_, 1.0); lags_.push_front(yvalue); lags_.pop_back(); } else if (lags_.size() < reg_suf_->size()) { lags_.push_front(yvalue); } else { report_error("Vector of lags is larger than the AR(p) dimension."); } } void ArSuf::add_mixture_data(double y, const Vector &x, double weight){ reg_suf_->add_mixture_data(y, x, weight); } void ArSuf::combine(const Ptr<ArSuf> & s){ reg_suf_->combine(s->reg_suf_); } void ArSuf::combine(const ArSuf &s){ reg_suf_->combine(*s.reg_suf_); } ArSuf * ArSuf::abstract_combine(Sufstat *s) { return abstract_combine_impl<ArSuf>(this, s); } Vector ArSuf::vectorize(bool minimal)const{ return reg_suf_->vectorize(minimal); } Vector::const_iterator ArSuf::unvectorize(Vector::const_iterator &v, bool minimal){ return reg_suf_->unvectorize(v, minimal); } Vector::const_iterator ArSuf::unvectorize(const Vector &v, bool minimal){ return reg_suf_->unvectorize(v, minimal); } ostream & ArSuf::print(ostream &out)const{ reg_suf_->print(out); out << "lags:" << endl; for(int i = 0; i < lags_.size(); ++i) { out << i+1 << ": " << lags_[i] << endl; } return out; } //====================================================================== ArModel::ArModel(int number_of_lags) : ParamPolicy(new GlmCoefs(Vector(number_of_lags, 0.0), true), new UnivParams(1.0)), DataPolicy(new ArSuf(number_of_lags)), filter_coefficients_current_(false) { Phi_prm()->add_observer([this](){this->observe_phi();}); } ArModel::ArModel(const Ptr<GlmCoefs> &autoregression_coefficients, const Ptr<UnivParams> &innovation_variance) : ParamPolicy(autoregression_coefficients, innovation_variance), DataPolicy(new ArSuf(autoregression_coefficients->size())), filter_coefficients_current_(false) { bool ok = check_stationary(autoregression_coefficients->value()); if (!ok) { report_error("Attempt to initialize ArModel with an illegal value " "of the autoregression coefficients."); } Phi_prm()->add_observer([this](){this->observe_phi();}); } ArModel * ArModel::clone()const{return new ArModel(*this);} int ArModel::number_of_lags()const{return phi().size();} double ArModel::sigma()const{ return sqrt(Sigsq_prm()->value()); } double ArModel::sigsq()const{ return Sigsq_prm()->value(); } const Vector &ArModel::phi()const{ return Phi_prm()->value(); } void ArModel::set_sigma(double sigma){ Sigsq_prm()->set(sigma * sigma); } void ArModel::set_sigsq(double sigsq){ Sigsq_prm()->set(sigsq); } void ArModel::set_phi(const Vector &phi){ Phi_prm()->set(phi); } Ptr<GlmCoefs> ArModel::Phi_prm(){ return prm1(); } const Ptr<GlmCoefs> ArModel::Phi_prm()const{ return prm1(); } Ptr<UnivParams> ArModel::Sigsq_prm(){ return prm2(); } const Ptr<UnivParams> ArModel::Sigsq_prm()const{ return prm2(); } const GlmCoefs &ArModel::coef() const { return prm1_ref(); } GlmCoefs &ArModel::coef() { return prm1_ref(); } bool ArModel::check_stationary(const Vector &phi){ // The process is stationary if the roots of the polynomial // // 1 - phi[0]*z - ... - phi[p-1]*z^p. // // all lie outside the unit circle. We can do that by explicitly finding // and checking the roots, but that's kind of expensive. Before doing that // we can do a quick check to see if the coefficients are within a loose // bound. // // Based on Rouche's theorem: // http://en.wikipedia.org/wiki/Properties_of_polynomial_roots#Based_on_the_Rouch.C3.A9_theorem // All the roots will be at least 1 in absolute value as long as // sum(abs(phi)) < 1. if(phi.abs_norm() < 1) return true; // If that didn't work then we're stuck finding roots. // TODO(stevescott): Really we just need to check the smallest root. If we // had a cheap way of finding just the smallest root then that would be more // efficient than finding them all. Vector coefficients = concat(1, -1 * phi); Polynomial polynomial(coefficients); std::vector<std::complex<double> > roots(polynomial.roots()); for (int i = 0; i < roots.size(); ++i) { if (abs(roots[i]) <= 1) return false; } return true; } Vector ArModel::autocovariance(int number_of_lags)const{ set_filter_coefficients(); Vector ans(number_of_lags + 1); for(int lag = 0; lag <= number_of_lags; ++lag){ int n = filter_coefficients_.size() - lag; const ConstVectorView psi(filter_coefficients_, 0, n); const ConstVectorView lag_psi(filter_coefficients_, lag, n); ans[lag] = psi.dot(lag_psi); } return ans * sigsq(); } Vector ArModel::simulate(int n, RNG &rng) const { int p = number_of_lags(); Vector acf = autocovariance(p); SpdMatrix Sigma(p); Sigma.diag() = acf[0]; for(int i = 1; i < p; ++i) { Sigma.subdiag(i) = acf[i]; Sigma.superdiag(i) = acf[i]; } Vector zero(p, 0.0); Vector y0 = rmvn(zero, Sigma); return simulate(n, y0, rng); } Vector ArModel::simulate(int n, const Vector &y0, RNG &rng) const { if(y0.size() != number_of_lags()){ ostringstream err; err << "Error in ArModel::simulate." << endl << "Initial state value y0 was size " << y0.size() << ", but the model has " << number_of_lags() << " lags." << endl; report_error(err.str()); } const Vector &phi(this->phi()); std::deque<double> lags(y0.rbegin(), y0.rend()); Vector ans; ans.reserve(n); for(int i = 0; i < n; ++i) { double mu = 0; for(int lag = 0; lag < number_of_lags(); ++lag) { mu += phi[lag] * lags[lag]; } double y = rnorm_mt(rng, mu, sigma()); lags.push_front(y); lags.pop_back(); ans.push_back(y); } return ans; } // Determine the MA filter coefficients from the AR coefficients by // equating coefficients in the polynomial phi(z)*psi(z) = 1. // phi(z) = 1 - phi_1 z - phi_2 z^2 - ... - phi_p z^p. This implies // that psi[0] = 1. The coefficient of z^n is // // psi[n] - psi[n-1]*phi_1 - psi[n-2]*phi_2 - ... = 0 // implying // psi[n] = psi[n-1]*phi_1 + ... // // The preceding math is unit-offset for phi, but zero-offset for // psi. void ArModel::set_filter_coefficients()const{ if (filter_coefficients_current_) return; const Vector &phi(this->phi()); int p = phi.size(); filter_coefficients_.resize(2); filter_coefficients_[0] = 1.0; if(phi.empty()) return; filter_coefficients_[1] = phi[0]; bool done = false; for(int n = 2; ; ++n){ if (n <= phi.size()) { ConstVectorView phi_view(phi, 0, n); ConstVectorView psi(filter_coefficients_, 0, n); double value = phi_view.dot(psi.reverse()); filter_coefficients_.push_back(value); } else { ConstVectorView psi(filter_coefficients_, n-p, p); double value = phi.dot(psi.reverse()); filter_coefficients_.push_back(value); ConstVectorView psi_tail(filter_coefficients_, n-p, p); // You're done when the last p elements of the vector are all // small. done = psi_tail.abs_norm() < 1e-6; } if(done) break; } filter_coefficients_current_ = true; } } <commit_msg>Removed unnecessary dependency on Eigen.hpp<commit_after>/* Copyright (C) 2005-2012 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include "Models/TimeSeries/ArModel.hpp" #include <complex> #include <functional> #include "Models/SufstatAbstractCombineImpl.hpp" #include "cpputil/Polynomial.hpp" #include "cpputil/report_error.hpp" #include "distributions.hpp" namespace BOOM{ ArSuf::ArSuf(int number_of_lags) : reg_suf_(new NeRegSuf(number_of_lags)), x_(number_of_lags) {} ArSuf * ArSuf::clone()const{return new ArSuf(*this);} void ArSuf::clear(){ lags_.clear(); reg_suf_->clear(); } void ArSuf::Update(const DoubleData &y) { double yvalue = y.value(); if (lags_.size() == reg_suf_->size()) { x_.assign(lags_.begin(), lags_.end()); reg_suf_->add_mixture_data(yvalue, x_, 1.0); lags_.push_front(yvalue); lags_.pop_back(); } else if (lags_.size() < reg_suf_->size()) { lags_.push_front(yvalue); } else { report_error("Vector of lags is larger than the AR(p) dimension."); } } void ArSuf::add_mixture_data(double y, const Vector &x, double weight){ reg_suf_->add_mixture_data(y, x, weight); } void ArSuf::combine(const Ptr<ArSuf> & s){ reg_suf_->combine(s->reg_suf_); } void ArSuf::combine(const ArSuf &s){ reg_suf_->combine(*s.reg_suf_); } ArSuf * ArSuf::abstract_combine(Sufstat *s) { return abstract_combine_impl<ArSuf>(this, s); } Vector ArSuf::vectorize(bool minimal)const{ return reg_suf_->vectorize(minimal); } Vector::const_iterator ArSuf::unvectorize(Vector::const_iterator &v, bool minimal){ return reg_suf_->unvectorize(v, minimal); } Vector::const_iterator ArSuf::unvectorize(const Vector &v, bool minimal){ return reg_suf_->unvectorize(v, minimal); } ostream & ArSuf::print(ostream &out)const{ reg_suf_->print(out); out << "lags:" << endl; for(int i = 0; i < lags_.size(); ++i) { out << i+1 << ": " << lags_[i] << endl; } return out; } //====================================================================== ArModel::ArModel(int number_of_lags) : ParamPolicy(new GlmCoefs(Vector(number_of_lags, 0.0), true), new UnivParams(1.0)), DataPolicy(new ArSuf(number_of_lags)), filter_coefficients_current_(false) { Phi_prm()->add_observer([this](){this->observe_phi();}); } ArModel::ArModel(const Ptr<GlmCoefs> &autoregression_coefficients, const Ptr<UnivParams> &innovation_variance) : ParamPolicy(autoregression_coefficients, innovation_variance), DataPolicy(new ArSuf(autoregression_coefficients->size())), filter_coefficients_current_(false) { bool ok = check_stationary(autoregression_coefficients->value()); if (!ok) { report_error("Attempt to initialize ArModel with an illegal value " "of the autoregression coefficients."); } Phi_prm()->add_observer([this](){this->observe_phi();}); } ArModel * ArModel::clone()const{return new ArModel(*this);} int ArModel::number_of_lags()const{return phi().size();} double ArModel::sigma()const{ return sqrt(Sigsq_prm()->value()); } double ArModel::sigsq()const{ return Sigsq_prm()->value(); } const Vector &ArModel::phi()const{ return Phi_prm()->value(); } void ArModel::set_sigma(double sigma){ Sigsq_prm()->set(sigma * sigma); } void ArModel::set_sigsq(double sigsq){ Sigsq_prm()->set(sigsq); } void ArModel::set_phi(const Vector &phi){ Phi_prm()->set(phi); } Ptr<GlmCoefs> ArModel::Phi_prm(){ return prm1(); } const Ptr<GlmCoefs> ArModel::Phi_prm()const{ return prm1(); } Ptr<UnivParams> ArModel::Sigsq_prm(){ return prm2(); } const Ptr<UnivParams> ArModel::Sigsq_prm()const{ return prm2(); } const GlmCoefs &ArModel::coef() const { return prm1_ref(); } GlmCoefs &ArModel::coef() { return prm1_ref(); } bool ArModel::check_stationary(const Vector &phi){ // The process is stationary if the roots of the polynomial // // 1 - phi[0]*z - ... - phi[p-1]*z^p. // // all lie outside the unit circle. We can do that by explicitly finding // and checking the roots, but that's kind of expensive. Before doing that // we can do a quick check to see if the coefficients are within a loose // bound. // // Based on Rouche's theorem: // http://en.wikipedia.org/wiki/Properties_of_polynomial_roots#Based_on_the_Rouch.C3.A9_theorem // All the roots will be at least 1 in absolute value as long as // sum(abs(phi)) < 1. if(phi.abs_norm() < 1) return true; // If that didn't work then we're stuck finding roots. // TODO(stevescott): Really we just need to check the smallest root. If we // had a cheap way of finding just the smallest root then that would be more // efficient than finding them all. Vector coefficients = concat(1, -1 * phi); Polynomial polynomial(coefficients); std::vector<std::complex<double> > roots(polynomial.roots()); for (int i = 0; i < roots.size(); ++i) { if (abs(roots[i]) <= 1) return false; } return true; } Vector ArModel::autocovariance(int number_of_lags)const{ set_filter_coefficients(); Vector ans(number_of_lags + 1); for(int lag = 0; lag <= number_of_lags; ++lag){ int n = filter_coefficients_.size() - lag; const ConstVectorView psi(filter_coefficients_, 0, n); const ConstVectorView lag_psi(filter_coefficients_, lag, n); ans[lag] = psi.dot(lag_psi); } return ans * sigsq(); } Vector ArModel::simulate(int n, RNG &rng) const { int p = number_of_lags(); Vector acf = autocovariance(p); SpdMatrix Sigma(p); Sigma.diag() = acf[0]; for(int i = 1; i < p; ++i) { Sigma.subdiag(i) = acf[i]; Sigma.superdiag(i) = acf[i]; } Vector zero(p, 0.0); Vector y0 = rmvn(zero, Sigma); return simulate(n, y0, rng); } Vector ArModel::simulate(int n, const Vector &y0, RNG &rng) const { if(y0.size() != number_of_lags()){ ostringstream err; err << "Error in ArModel::simulate." << endl << "Initial state value y0 was size " << y0.size() << ", but the model has " << number_of_lags() << " lags." << endl; report_error(err.str()); } const Vector &phi(this->phi()); std::deque<double> lags(y0.rbegin(), y0.rend()); Vector ans; ans.reserve(n); for(int i = 0; i < n; ++i) { double mu = 0; for(int lag = 0; lag < number_of_lags(); ++lag) { mu += phi[lag] * lags[lag]; } double y = rnorm_mt(rng, mu, sigma()); lags.push_front(y); lags.pop_back(); ans.push_back(y); } return ans; } // Determine the MA filter coefficients from the AR coefficients by // equating coefficients in the polynomial phi(z)*psi(z) = 1. // phi(z) = 1 - phi_1 z - phi_2 z^2 - ... - phi_p z^p. This implies // that psi[0] = 1. The coefficient of z^n is // // psi[n] - psi[n-1]*phi_1 - psi[n-2]*phi_2 - ... = 0 // implying // psi[n] = psi[n-1]*phi_1 + ... // // The preceding math is unit-offset for phi, but zero-offset for // psi. void ArModel::set_filter_coefficients()const{ if (filter_coefficients_current_) return; const Vector &phi(this->phi()); int p = phi.size(); filter_coefficients_.resize(2); filter_coefficients_[0] = 1.0; if(phi.empty()) return; filter_coefficients_[1] = phi[0]; bool done = false; for(int n = 2; ; ++n){ if (n <= phi.size()) { ConstVectorView phi_view(phi, 0, n); ConstVectorView psi(filter_coefficients_, 0, n); double value = phi_view.dot(psi.reverse()); filter_coefficients_.push_back(value); } else { ConstVectorView psi(filter_coefficients_, n-p, p); double value = phi.dot(psi.reverse()); filter_coefficients_.push_back(value); ConstVectorView psi_tail(filter_coefficients_, n-p, p); // You're done when the last p elements of the vector are all // small. done = psi_tail.abs_norm() < 1e-6; } if(done) break; } filter_coefficients_current_ = true; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "NetworkStateNotifier.h" namespace WebCore { // Chromium doesn't currently support network state notifications. This causes // an extra DLL to get loaded into the renderer which can slow things down a // bit. We may want an alternate design. void NetworkStateNotifier::updateState() { } // TODO(darin): Kill this once we stop defining PLATFORM(MAC) #if PLATFORM(MAC) void NetworkStateNotifier::networkStateChangeTimerFired(Timer<NetworkStateNotifier>*) { } #endif #if PLATFORM(OS_WIN) || PLATFORM(MAC) NetworkStateNotifier::NetworkStateNotifier() : m_isOnLine(true) #if PLATFORM(MAC) , m_networkStateChangeTimer(this, &NetworkStateNotifier::networkStateChangeTimerFired) #endif { } #endif } <commit_msg>fix build take 2<commit_after>/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "NetworkStateNotifier.h" namespace WebCore { // Chromium doesn't currently support network state notifications. This causes // an extra DLL to get loaded into the renderer which can slow things down a // bit. We may want an alternate design. void NetworkStateNotifier::updateState() { } // TODO(darin): Kill this once we stop defining PLATFORM(MAC) #if PLATFORM(MAC) void NetworkStateNotifier::networkStateChangeTimerFired(Timer<NetworkStateNotifier>*) { } #endif #if PLATFORM(WIN_OS) || PLATFORM(MAC) NetworkStateNotifier::NetworkStateNotifier() : m_isOnLine(true) #if PLATFORM(MAC) , m_networkStateChangeTimer(this, &NetworkStateNotifier::networkStateChangeTimerFired) #endif { } #endif } <|endoftext|>
<commit_before>#line 2 "togo/memory.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file memory.hpp @brief Memory interface. @ingroup memory */ #pragma once #include <togo/config.hpp> #include <togo/types.hpp> #include <togo/memory_types.hpp> #include <type_traits> #include <new> #include <cstdlib> namespace togo { /** @addtogroup memory @{ */ namespace { template<class T> using pointer_type = typename std::remove_const< typename std::remove_pointer<T>::type >::type; } /// Construct an object with an allocator. #define TOGO_CONSTRUCT(a, T, ...) \ (new ((a).allocate(sizeof(T), alignof(T))) T(__VA_ARGS__)) /// Construct an object with an allocator and no alignment. #define TOGO_CONSTRUCT_NA(a, T, ...) \ (new ((a).allocate(sizeof(T), 0)) T(__VA_ARGS__)) /// Construct an object with an allocator and no initialization parameters. /// This calls the default constructor. #define TOGO_CONSTRUCT_DEFAULT(a, T) \ (new ((a).allocate(sizeof(T), alignof(T))) T()) /// Construct an object with an allocator, no initialization parameters, and no alignment. /// This calls the default constructor. #define TOGO_CONSTRUCT_DEFAULT_NA(a, T) \ (new ((a).allocate(sizeof(T), 0)) T()) /// Destroy an object with an allocator. /// Does nothing if p is nullptr. Calls destructor p->~T(); and /// deallocates the object. // Oh C++. #define TOGO_DESTROY(a, p) \ do { if (p) { \ (p)->~pointer_type<decltype(p)>(); (a).deallocate(p); \ } } while (false) /** %Allocator base class. */ class Allocator { public: static constexpr u32 const /// Default allocation alignment. DEFAULT_ALIGNMENT = 4, /// Size value returned by unsupported operations. SIZE_NOT_TRACKED = static_cast<u32>(-1); Allocator() = default; Allocator(Allocator&&) = default; Allocator& operator=(Allocator&&) = default; Allocator(Allocator const&) = delete; Allocator& operator=(Allocator const&) = delete; /// Allocators should assert that they have no active allocations /// in the destructor. virtual ~Allocator() = 0; /// Get number of active allocations. virtual u32 num_allocations() const = 0; /// Get total number of bytes allocated by the allocator. /// If an allocator does not support this operation, it shall /// return SIZE_NOT_TRACKED. virtual u32 total_size() const = 0; /// Get size of block allocated for p. /// /// This may be greater than the actual size of the object type /// due to internal state and alignment. If an allocator does not /// support this operation, it shall return SIZE_NOT_TRACKED. virtual u32 allocation_size(void const* p) const = 0; /// Allocate a chunk of memory. /// If align is 0, no alignment is used. virtual void* allocate(u32 size, u32 align = DEFAULT_ALIGNMENT) = 0; /// Deallocate a pointer. /// Does nothing if p is nullptr. virtual void deallocate(void* p) = 0; }; inline Allocator::~Allocator() = default; /** @} */ // end of doc-group memory namespace memory { /** @addtogroup memory @{ */ static constexpr u32 const /// Minimum scratch size (8K). SCRATCH_SIZE_MINIMUM = 8 * 1024, /// Default scratch size (4MB). SCRATCH_SIZE_DEFAULT = 4 * 1024 * 1024 ; /// Initialize global allocators. /// scratch_size is size of the scratch space block to pre-allocate. /// If scratch_size < SCRATCH_SIZE_MINIMUM, an assertion will trigger. void init(u32 const scratch_size = SCRATCH_SIZE_MINIMUM); /// Shutdown allocators created by init(). void shutdown(); /// Get the default allocator. /// /// This is a thread-safe growing heap allocator. Allocator& default_allocator(); /// Get the scratch allocator. /// /// This is a thread-safe allocator. /// This should *only* be used for temporary memory. It uses a ring /// buffer for allocations, backed by a block of memory from the /// default allocator. Allocator& scratch_allocator(); /** @} */ // end of doc-group memory } // namespace memory } // namespace togo <commit_msg>memory: doc tidy.<commit_after>#line 2 "togo/memory.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file memory.hpp @brief Memory interface. @ingroup memory */ #pragma once #include <togo/config.hpp> #include <togo/types.hpp> #include <togo/memory_types.hpp> #include <type_traits> #include <new> #include <cstdlib> namespace togo { /** @addtogroup memory @{ */ namespace { template<class T> using pointer_type = typename std::remove_const< typename std::remove_pointer<T>::type >::type; } /// Construct an object with an allocator. #define TOGO_CONSTRUCT(a, T, ...) \ (new ((a).allocate(sizeof(T), alignof(T))) T(__VA_ARGS__)) /// Construct an object with an allocator and no alignment. #define TOGO_CONSTRUCT_NA(a, T, ...) \ (new ((a).allocate(sizeof(T), 0)) T(__VA_ARGS__)) /// Construct an object with an allocator and no initialization parameters. /// This calls the default constructor. #define TOGO_CONSTRUCT_DEFAULT(a, T) \ (new ((a).allocate(sizeof(T), alignof(T))) T()) /// Construct an object with an allocator, no initialization parameters, /// and no alignment. /// /// This calls the default constructor. #define TOGO_CONSTRUCT_DEFAULT_NA(a, T) \ (new ((a).allocate(sizeof(T), 0)) T()) /// Destroy an object with an allocator. /// /// Does nothing if p is nullptr. Calls destructor p->~T(); and /// deallocates the object. // Oh C++. #define TOGO_DESTROY(a, p) \ do { if (p) { \ (p)->~pointer_type<decltype(p)>(); (a).deallocate(p); \ } } while (false) /** %Allocator base class. */ class Allocator { public: static constexpr u32 const /// Default allocation alignment. DEFAULT_ALIGNMENT = 4, /// Size value returned by unsupported operations. SIZE_NOT_TRACKED = static_cast<u32>(-1); Allocator() = default; Allocator(Allocator&&) = default; Allocator& operator=(Allocator&&) = default; Allocator(Allocator const&) = delete; Allocator& operator=(Allocator const&) = delete; /// Allocators should assert that they have no active allocations /// in the destructor. virtual ~Allocator() = 0; /// Get number of active allocations. virtual u32 num_allocations() const = 0; /// Get total number of bytes allocated by the allocator. /// /// If an allocator does not support this operation, it shall /// return SIZE_NOT_TRACKED. virtual u32 total_size() const = 0; /// Get size of block allocated for p. /// /// This may be greater than the actual size of the object type /// due to internal state and alignment. If an allocator does not /// support this operation, it shall return SIZE_NOT_TRACKED. virtual u32 allocation_size(void const* p) const = 0; /// Allocate a chunk of memory. /// /// If align is 0, no alignment is used. virtual void* allocate(u32 size, u32 align = DEFAULT_ALIGNMENT) = 0; /// Deallocate a pointer. /// /// Does nothing if p is nullptr. virtual void deallocate(void* p) = 0; }; inline Allocator::~Allocator() = default; /** @} */ // end of doc-group memory namespace memory { /** @addtogroup memory @{ */ static constexpr u32 const /// Minimum scratch size (8K). SCRATCH_SIZE_MINIMUM = 8 * 1024, /// Default scratch size (4MB). SCRATCH_SIZE_DEFAULT = 4 * 1024 * 1024 ; /// Initialize global allocators. /// /// scratch_size is size of the scratch space block to pre-allocate. /// If scratch_size < SCRATCH_SIZE_MINIMUM, an assertion will trigger. void init(u32 const scratch_size = SCRATCH_SIZE_MINIMUM); /// Shutdown allocators created by init(). void shutdown(); /// Get the default allocator. /// /// This is a thread-safe growing heap allocator. Allocator& default_allocator(); /// Get the scratch allocator. /// /// This is a thread-safe allocator. /// This should *only* be used for temporary memory. It uses a ring /// buffer for allocations, backed by a block of memory from the /// default allocator. Allocator& scratch_allocator(); /** @} */ // end of doc-group memory } // namespace memory } // namespace togo <|endoftext|>
<commit_before>#include <taichi/lang.h> #include <taichi/testing.h> #include <numeric> TLANG_NAMESPACE_BEGIN TC_TEST("gpu_gc_basics") { for (auto arch : {Arch::gpu}) { int n = 32; Program prog(arch); Global(x, i32); layout([&]() { auto i = Index(0); auto j = Index(1); root.dense(i, n).pointer().dense(j, n).place(x); }); kernel([&]() { For(0, n, [&](Expr i) { For(0, i, [&](Expr j) { Activate(x.snode(), {i, j}); }); }); })(); kernel([&]() { For(0, n, [&](Expr i) { For(0, i, [&](Expr j) { x[i, j] = i + j; }); }); })(); auto stat = x.parent().parent().snode()->stat(); TC_CHECK(stat.num_resident_blocks == n - 1); for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { TC_CHECK(x.val<int>(i, j) == i + j); } } x.parent().parent().snode()->clear_data_and_deactivate(); stat = x.parent().parent().snode()->stat(); TC_CHECK(stat.num_resident_blocks == 0); TC_CHECK(stat.num_recycled_blocks == 0); for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { TC_CHECK(x.val<int>(i, j) == 0); } } } }; TC_TEST("parallel_particle_sort") { Program prog(Arch::gpu); CoreState::set_trigger_gdb_when_crash(true); constexpr int n = 256; const real dx = 1.0_f / n, inv_dx = 1.0_f / dx; constexpr int dim = 3; auto f32 = DataType::f32; int grid_block_size = 4; Vector particle_x(f32, dim); Global(l, i32); Vector grid_v(f32, dim); Global(grid_m, f32); int max_n_particles = 1024 * 1024; int n_particles = 0; std::vector<float> benchmark_particles; std::vector<Vector3> p_x; n_particles = max_n_particles; p_x.resize(n_particles); for (int i = 0; i < n_particles; i++) { Vector3 offset = Vector3::rand() - Vector3(0.5_f); p_x[i] = Vector3(0.5_f) + offset * 0.7f; } TC_ASSERT(n_particles <= max_n_particles); auto i = Index(0), j = Index(1), k = Index(2); auto p = Index(3); layout([&]() { auto &fork = root.dynamic(p, max_n_particles); for (int i = 0; i < dim; i++) { fork.place(particle_x(i)); } TC_ASSERT(n % grid_block_size == 0); auto &block = root.dense({i, j, k}, n / grid_block_size).pointer(); block.dense({i, j, k}, grid_block_size) .place(grid_v(0), grid_v(1), grid_v(2), grid_m); }); TC_ASSERT(bit::is_power_of_two(n)); Kernel(sort).def([&] { BlockDim(256); For(particle_x(0), [&](Expr p) { auto node_coord = floor(particle_x[p] * inv_dx - 0.5_f); grid_v[cast<int32>(node_coord(0)), cast<int32>(node_coord(1)), cast<int32>(node_coord(2))](0) = 1; }); }); for (int i = 0; i < n_particles; i++) { for (int d = 0; d < dim; d++) { particle_x(d).val<float32>(i) = p_x[i][d]; } } int last_nb = -1; for (int i = 0; i < 2048; i++) { grid_m.parent().parent().snode()->clear_data_and_deactivate(); sort(); prog.synchronize(); auto stat = grid_m.parent().parent().snode()->stat(); int nb = stat.num_resident_blocks; if (last_nb == -1) { last_nb = nb; TC_P(last_nb); } else { if (last_nb != nb) { TC_P(i); } TC_CHECK(last_nb == nb); } } }; TLANG_NAMESPACE_END <commit_msg>simplified sort test<commit_after>#include <taichi/lang.h> #include <taichi/testing.h> #include <numeric> TLANG_NAMESPACE_BEGIN TC_TEST("gpu_gc_basics") { for (auto arch : {Arch::gpu}) { int n = 32; Program prog(arch); Global(x, i32); layout([&]() { auto i = Index(0); auto j = Index(1); root.dense(i, n).pointer().dense(j, n).place(x); }); kernel([&]() { For(0, n, [&](Expr i) { For(0, i, [&](Expr j) { Activate(x.snode(), {i, j}); }); }); })(); kernel([&]() { For(0, n, [&](Expr i) { For(0, i, [&](Expr j) { x[i, j] = i + j; }); }); })(); auto stat = x.parent().parent().snode()->stat(); TC_CHECK(stat.num_resident_blocks == n - 1); for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { TC_CHECK(x.val<int>(i, j) == i + j); } } x.parent().parent().snode()->clear_data_and_deactivate(); stat = x.parent().parent().snode()->stat(); TC_CHECK(stat.num_resident_blocks == 0); TC_CHECK(stat.num_recycled_blocks == 0); for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { TC_CHECK(x.val<int>(i, j) == 0); } } } }; TC_TEST("parallel_particle_sort") { Program prog(Arch::gpu); CoreState::set_trigger_gdb_when_crash(true); constexpr int n = 256; const real dx = 1.0_f / n, inv_dx = 1.0_f / dx; constexpr int dim = 3; auto f32 = DataType::f32; auto i32 = DataType::i32; int grid_block_size = 4; Vector particle_x(i32, dim); Vector grid_v(f32, dim); Global(grid_m, f32); int max_n_particles = 1024 * 1024; int n_particles = 0; std::vector<float> benchmark_particles; std::vector<Vector3> p_x; n_particles = max_n_particles; p_x.resize(n_particles); for (int i = 0; i < n_particles; i++) { Vector3 offset = Vector3::rand() - Vector3(0.5_f); p_x[i] = Vector3(0.5_f) + offset * 0.7f; } TC_ASSERT(n_particles <= max_n_particles); auto i = Index(0), j = Index(1), k = Index(2); auto p = Index(3); layout([&]() { auto &fork = root.dynamic(p, max_n_particles); for (int i = 0; i < dim; i++) { fork.place(particle_x(i)); } TC_ASSERT(n % grid_block_size == 0); auto &block = root.dense({i, j, k}, n / grid_block_size).pointer(); block.dense({i, j, k}, grid_block_size) .place(grid_v(0), grid_v(1), grid_v(2), grid_m); }); TC_ASSERT(bit::is_power_of_two(n)); Kernel(sort).def([&] { BlockDim(256); For(particle_x(0), [&](Expr p) { grid_v[particle_x[p]](0) = 1; }); }); for (int i = 0; i < n_particles; i++) { for (int d = 0; d < dim; d++) { particle_x(d).val<int32>(i) = p_x[i][d] * inv_dx; } } int last_nb = -1; for (int i = 0; i < 2048; i++) { grid_m.parent().parent().snode()->clear_data_and_deactivate(); sort(); prog.synchronize(); auto stat = grid_m.parent().parent().snode()->stat(); int nb = stat.num_resident_blocks; if (last_nb == -1) { last_nb = nb; TC_P(last_nb); } else { if (last_nb != nb) { TC_P(i); } TC_CHECK(last_nb == nb); } } }; TLANG_NAMESPACE_END <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCProperty.cpp // @Author : LvSheng.Huang // @Date : 2012-03-01 // @Module : NFCProperty // // ------------------------------------------------------------------------- #include "NFCProperty.h" #include <complex> NFCProperty::NFCProperty() { mbPublic = false; mbPrivate = false; mbSave = false; mSelf = NFGUID(); eType = TDATA_UNKNOWN; msPropertyName = ""; } NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue) { mbPublic = bPublic; mbPrivate = bPrivate; mbSave = bSave; mSelf = self; msPropertyName = strPropertyName; mstrRelationValue = strRelationValue; eType = varType; } NFCProperty::~NFCProperty() { for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter) { iter->reset(); } mtPropertyCallback.clear(); mxData.reset(); } void NFCProperty::SetValue(const NFIDataList::TData& TData) { if (eType != TData.GetType()) { return; } if (!mxData.get()) { if (!TData.IsNullValue()) { return; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData)); } NFCDataList::TData oldValue; oldValue = *mxData; mxData->variantData = TData.variantData; NFCDataList::TData newValue; newValue = *mxData; OnEventHandler(oldValue , newValue); } void NFCProperty::SetValue(const NFIProperty* pProperty) { SetValue(pProperty->GetValue()); } const NFIDataList::TData& NFCProperty::GetValue() const { if (mxData.get()) { return *mxData; } return NULL_TDATA; } const std::string& NFCProperty::GetKey() const { return msPropertyName; } const bool NFCProperty::GetSave() const { return mbSave; } const bool NFCProperty::GetPublic() const { return mbPublic; } const bool NFCProperty::GetPrivate() const { return mbPrivate; } const std::string& NFCProperty::GetRelationValue() const { return mstrRelationValue; } void NFCProperty::SetSave(bool bSave) { mbSave = bSave; } void NFCProperty::SetPublic(bool bPublic) { mbPublic = bPublic; } void NFCProperty::SetPrivate(bool bPrivate) { mbPrivate = bPrivate; } void NFCProperty::SetRelationValue(const std::string& strRelationValue) { mstrRelationValue = strRelationValue; } NFINT64 NFCProperty::GetInt() const { if (!mxData.get()) { return 0; } return mxData->GetInt(); } double NFCProperty::GetFloat() const { if (!mxData.get()) { return 0.0; } return mxData->GetFloat(); } const std::string& NFCProperty::GetString() const { if (!mxData.get()) { return NULL_STR; } return mxData->GetString(); } const NFGUID& NFCProperty::GetObject() const { if (!mxData.get()) { return NULL_OBJECT; } return mxData->GetObject(); } void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb) { mtPropertyCallback.push_back(cb); } int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if (mtPropertyCallback.size() <= 0) { return 0; } TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin(); TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end(); for (it; it != end; ++it) { //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self) PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it; PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get(); int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar); } return 0; } bool NFCProperty::SetInt(const NFINT64 value) { if (eType != TDATA_INT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (0 == value) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT)); mxData->SetInt(0); } if (value == mxData->GetInt()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetInt(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetFloat(const double value) { if (eType != TDATA_FLOAT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (std::abs(value) < 0.001) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT)); mxData->SetFloat(0.0); } if (value - mxData->GetFloat() < 0.001) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetFloat(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetString(const std::string& value) { if (eType != TDATA_STRING) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.empty()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING)); mxData->SetString(NULL_STR); } if (value == mxData->GetString()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetString(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetObject(const NFGUID& value) { if (eType != TDATA_OBJECT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.IsNull()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT)); mxData->SetObject(NFGUID()); } if (value == mxData->GetObject()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetObject(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::Changed() const { return GetValue().IsNullValue(); } const TDATA_TYPE NFCProperty::GetType() const { return eType; } const bool NFCProperty::GeUsed() const { if (mxData.get()) { return true; } return false; } std::string NFCProperty::ToString() { std::string strData; const TDATA_TYPE eType = GetType(); switch (eType) { case TDATA_INT: strData = lexical_cast<std::string> (GetInt()); break; case TDATA_FLOAT: strData = lexical_cast<std::string> (GetFloat()); break; case TDATA_STRING: strData = GetString(); break; case TDATA_OBJECT: strData = GetObject().ToString(); break; default: strData = NULL_STR; break; } return strData; } bool NFCProperty::FromString(const std::string& strData) { const TDATA_TYPE eType = GetType(); bool bRet = false; switch (eType) { case TDATA_INT: { NFINT64 nValue = 0; bRet = NF_StrTo(strData, nValue); SetInt(nValue); } break; case TDATA_FLOAT: { double dValue = 0; bRet = NF_StrTo(strData, dValue); SetFloat(dValue); } break; case TDATA_STRING: { SetString(strData); bRet = true; } break; case TDATA_OBJECT: { NFGUID xID; bRet = xID.FromString(strData); SetObject(xID); } break; default: break; } return bRet; } bool NFCProperty::DeSerialization() { bool bRet = false; const TDATA_TYPE eType = GetType(); if (eType == TDATA_STRING) { NFCDataList xDataList; const std::string& strData = mxData->GetString(); xDataList.Split(strData.c_str(), ";"); for (int i = 0; i < xDataList.GetCount(); ++i) { if (nullptr == mxEmbeddedList) { mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>()); } else { mxEmbeddedList->ClearAll(); } if(xDataList.String(i).empty()) { NFASSERT(0, strData, __FILE__, __FUNCTION__); } mxEmbeddedList->Add(xDataList.String(i)); } if (nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0) { std::string strTemData; for (bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData)) { NFCDataList xTemDataList; xTemDataList.Split(strTemData.c_str(), ","); if (xTemDataList.GetCount() > 0) { if (xTemDataList.GetCount() != 2) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } const std::string& strKey = xTemDataList.String(0); const std::string& strValue = xTemDataList.String(0); if (strKey.empty() || strValue.empty()) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } if (nullptr == mxEmbeddedMap) { mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>()); } else { mxEmbeddedMap->ClearAll(); } mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue))) } } bRet = true; } } return bRet; } const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const { return this->mxEmbeddedList; } const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const { return this->mxEmbeddedMap; } <commit_msg>fixed<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCProperty.cpp // @Author : LvSheng.Huang // @Date : 2012-03-01 // @Module : NFCProperty // // ------------------------------------------------------------------------- #include "NFCProperty.h" #include <complex> NFCProperty::NFCProperty() { mbPublic = false; mbPrivate = false; mbSave = false; mSelf = NFGUID(); eType = TDATA_UNKNOWN; msPropertyName = ""; } NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue) { mbPublic = bPublic; mbPrivate = bPrivate; mbSave = bSave; mSelf = self; msPropertyName = strPropertyName; mstrRelationValue = strRelationValue; eType = varType; } NFCProperty::~NFCProperty() { for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter) { iter->reset(); } mtPropertyCallback.clear(); mxData.reset(); } void NFCProperty::SetValue(const NFIDataList::TData& TData) { if (eType != TData.GetType()) { return; } if (!mxData.get()) { if (!TData.IsNullValue()) { return; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData)); } NFCDataList::TData oldValue; oldValue = *mxData; mxData->variantData = TData.variantData; NFCDataList::TData newValue; newValue = *mxData; OnEventHandler(oldValue , newValue); } void NFCProperty::SetValue(const NFIProperty* pProperty) { SetValue(pProperty->GetValue()); } const NFIDataList::TData& NFCProperty::GetValue() const { if (mxData.get()) { return *mxData; } return NULL_TDATA; } const std::string& NFCProperty::GetKey() const { return msPropertyName; } const bool NFCProperty::GetSave() const { return mbSave; } const bool NFCProperty::GetPublic() const { return mbPublic; } const bool NFCProperty::GetPrivate() const { return mbPrivate; } const std::string& NFCProperty::GetRelationValue() const { return mstrRelationValue; } void NFCProperty::SetSave(bool bSave) { mbSave = bSave; } void NFCProperty::SetPublic(bool bPublic) { mbPublic = bPublic; } void NFCProperty::SetPrivate(bool bPrivate) { mbPrivate = bPrivate; } void NFCProperty::SetRelationValue(const std::string& strRelationValue) { mstrRelationValue = strRelationValue; } NFINT64 NFCProperty::GetInt() const { if (!mxData.get()) { return 0; } return mxData->GetInt(); } double NFCProperty::GetFloat() const { if (!mxData.get()) { return 0.0; } return mxData->GetFloat(); } const std::string& NFCProperty::GetString() const { if (!mxData.get()) { return NULL_STR; } return mxData->GetString(); } const NFGUID& NFCProperty::GetObject() const { if (!mxData.get()) { return NULL_OBJECT; } return mxData->GetObject(); } void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb) { mtPropertyCallback.push_back(cb); } int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if (mtPropertyCallback.size() <= 0) { return 0; } TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin(); TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end(); for (it; it != end; ++it) { //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self) PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it; PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get(); int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar); } return 0; } bool NFCProperty::SetInt(const NFINT64 value) { if (eType != TDATA_INT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (0 == value) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT)); mxData->SetInt(0); } if (value == mxData->GetInt()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetInt(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetFloat(const double value) { if (eType != TDATA_FLOAT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (std::abs(value) < 0.001) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT)); mxData->SetFloat(0.0); } if (value - mxData->GetFloat() < 0.001) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetFloat(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetString(const std::string& value) { if (eType != TDATA_STRING) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.empty()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING)); mxData->SetString(NULL_STR); } if (value == mxData->GetString()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetString(value); OnEventHandler(oldValue, *mxData); return true; } bool NFCProperty::SetObject(const NFGUID& value) { if (eType != TDATA_OBJECT) { return false; } if (!mxData.get()) { //ǿվΪûݣûݵľͲ if (value.IsNull()) { return false; } mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT)); mxData->SetObject(NFGUID()); } if (value == mxData->GetObject()) { return false; } NFCDataList::TData oldValue; oldValue = *mxData; mxData->SetObject(value); OnEventHandler(oldValue , *mxData); return true; } bool NFCProperty::Changed() const { return GetValue().IsNullValue(); } const TDATA_TYPE NFCProperty::GetType() const { return eType; } const bool NFCProperty::GeUsed() const { if (mxData.get()) { return true; } return false; } std::string NFCProperty::ToString() { std::string strData; const TDATA_TYPE eType = GetType(); switch (eType) { case TDATA_INT: strData = lexical_cast<std::string> (GetInt()); break; case TDATA_FLOAT: strData = lexical_cast<std::string> (GetFloat()); break; case TDATA_STRING: strData = GetString(); break; case TDATA_OBJECT: strData = GetObject().ToString(); break; default: strData = NULL_STR; break; } return strData; } bool NFCProperty::FromString(const std::string& strData) { const TDATA_TYPE eType = GetType(); bool bRet = false; switch (eType) { case TDATA_INT: { NFINT64 nValue = 0; bRet = NF_StrTo(strData, nValue); SetInt(nValue); } break; case TDATA_FLOAT: { double dValue = 0; bRet = NF_StrTo(strData, dValue); SetFloat(dValue); } break; case TDATA_STRING: { SetString(strData); bRet = true; } break; case TDATA_OBJECT: { NFGUID xID; bRet = xID.FromString(strData); SetObject(xID); } break; default: break; } return bRet; } bool NFCProperty::DeSerialization() { bool bRet = false; const TDATA_TYPE eType = GetType(); if (eType == TDATA_STRING) { NFCDataList xDataList; const std::string& strData = mxData->GetString(); xDataList.Split(strData.c_str(), ";"); for (int i = 0; i < xDataList.GetCount(); ++i) { if (nullptr == mxEmbeddedList) { mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>()); } else { mxEmbeddedList->ClearAll(); } if(xDataList.String(i).empty()) { NFASSERT(0, strData, __FILE__, __FUNCTION__); } mxEmbeddedList->Add(xDataList.String(i)); } if (nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0) { std::string strTemData; for (bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData)) { NFCDataList xTemDataList; xTemDataList.Split(strTemData.c_str(), ","); if (xTemDataList.GetCount() > 0) { if (xTemDataList.GetCount() != 2) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } const std::string& strKey = xTemDataList.String(0); const std::string& strValue = xTemDataList.String(0); if (strKey.empty() || strValue.empty()) { NFASSERT(0, strTemData, __FILE__, __FUNCTION__); } if (nullptr == mxEmbeddedMap) { mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>()); } else { mxEmbeddedMap->ClearAll(); } mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue))); } } bRet = true; } } return bRet; } const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const { return this->mxEmbeddedList; } const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const { return this->mxEmbeddedMap; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "QmitkStdMultiWidgetEditor.h" #include <cherryUIException.h> #include <cherryIWorkbenchPage.h> #include <QWidget> #include <mitkGlobalInteraction.h> #include <mitkDataStorageEditorInput.h> const std::string QmitkStdMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.stdmultiwidget"; QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor() : m_StdMultiWidget(0) { } QmitkStdMultiWidgetEditor::~QmitkStdMultiWidgetEditor() { // we need to wrap the RemovePartListener call inside a // register/unregister block to prevent infinite recursion // due to the destruction of temporary smartpointer to this this->Register(); this->GetSite()->GetPage()->RemovePartListener(cherry::IPartListener::Pointer(this)); this->UnRegister(false); } QmitkStdMultiWidget* QmitkStdMultiWidgetEditor::GetStdMultiWidget() { return m_StdMultiWidget; } void QmitkStdMultiWidgetEditor::Init(cherry::IEditorSite::Pointer site, cherry::IEditorInput::Pointer input) { if (input.Cast<mitk::DataStorageEditorInput>().IsNull()) throw cherry::PartInitException("Invalid Input: Must be IFileEditorInput"); this->SetSite(site); this->SetInput(input); } void QmitkStdMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { if (m_StdMultiWidget == 0) { m_DndFrameWidget = new QmitkDnDFrameWidget(parent); QVBoxLayout* layout = new QVBoxLayout(parent); layout->addWidget(m_DndFrameWidget); layout->setContentsMargins(0,0,0,0); m_StdMultiWidget = new QmitkStdMultiWidget(m_DndFrameWidget); QVBoxLayout* layout2 = new QVBoxLayout(m_DndFrameWidget); layout2->addWidget(m_StdMultiWidget); layout2->setContentsMargins(0,0,0,0); mitk::DataStorage::Pointer ds = this->GetEditorInput().Cast<mitk::DataStorageEditorInput>() ->GetDataStorageReference()->GetDataStorage(); // Tell the multiWidget which (part of) the tree to render m_StdMultiWidget->SetDataStorage(ds); // Initialize views as transversal, sagittal, coronar to all data objects in DataStorage // (from top-left to bottom) mitk::TimeSlicedGeometry::Pointer geo = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view m_StdMultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); // Enable standard handler for levelwindow-slider m_StdMultiWidget->EnableStandardLevelWindow(); // Add the displayed views to the tree to see their positions // in 2D and 3D m_StdMultiWidget->AddDisplayPlaneSubTree(); m_StdMultiWidget->EnableNavigationControllerEventListening(); mitk::GlobalInteraction::GetInstance()->AddListener( m_StdMultiWidget->GetMoveAndZoomInteractor() ); this->GetSite()->GetPage()->AddPartListener(cherry::IPartListener::Pointer(this)); } } cherry::IPartListener::Events::Types QmitkStdMultiWidgetEditor::GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void QmitkStdMultiWidgetEditor::PartClosed( cherry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void QmitkStdMultiWidgetEditor::PartVisible( cherry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->AddPlanesToDataStorage(); } } } void QmitkStdMultiWidgetEditor::PartHidden( cherry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void QmitkStdMultiWidgetEditor::SetFocus() { if (m_StdMultiWidget != 0) m_StdMultiWidget->setFocus(); } <commit_msg>ENH (#1850): added preference for logo file location with ID "DepartmentLogo"<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "QmitkStdMultiWidgetEditor.h" #include <cherryUIException.h> #include <cherryIWorkbenchPage.h> #include <cherryIPreferencesService.h> #include <QWidget> #include <mitkGlobalInteraction.h> #include <mitkDataStorageEditorInput.h> const std::string QmitkStdMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.stdmultiwidget"; QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor() : m_StdMultiWidget(0) { } QmitkStdMultiWidgetEditor::~QmitkStdMultiWidgetEditor() { // we need to wrap the RemovePartListener call inside a // register/unregister block to prevent infinite recursion // due to the destruction of temporary smartpointer to this this->Register(); this->GetSite()->GetPage()->RemovePartListener(cherry::IPartListener::Pointer(this)); this->UnRegister(false); } QmitkStdMultiWidget* QmitkStdMultiWidgetEditor::GetStdMultiWidget() { return m_StdMultiWidget; } void QmitkStdMultiWidgetEditor::Init(cherry::IEditorSite::Pointer site, cherry::IEditorInput::Pointer input) { if (input.Cast<mitk::DataStorageEditorInput>().IsNull()) throw cherry::PartInitException("Invalid Input: Must be IFileEditorInput"); this->SetSite(site); this->SetInput(input); } void QmitkStdMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { if (m_StdMultiWidget == 0) { m_DndFrameWidget = new QmitkDnDFrameWidget(parent); QVBoxLayout* layout = new QVBoxLayout(parent); layout->addWidget(m_DndFrameWidget); layout->setContentsMargins(0,0,0,0); m_StdMultiWidget = new QmitkStdMultiWidget(m_DndFrameWidget); QVBoxLayout* layout2 = new QVBoxLayout(m_DndFrameWidget); layout2->addWidget(m_StdMultiWidget); layout2->setContentsMargins(0,0,0,0); mitk::DataStorage::Pointer ds = this->GetEditorInput().Cast<mitk::DataStorageEditorInput>() ->GetDataStorageReference()->GetDataStorage(); // Tell the multiWidget which (part of) the tree to render m_StdMultiWidget->SetDataStorage(ds); // Initialize views as transversal, sagittal, coronar to all data objects in DataStorage // (from top-left to bottom) mitk::TimeSlicedGeometry::Pointer geo = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view m_StdMultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); // Enable standard handler for levelwindow-slider m_StdMultiWidget->EnableStandardLevelWindow(); // Add the displayed views to the tree to see their positions // in 2D and 3D m_StdMultiWidget->AddDisplayPlaneSubTree(); m_StdMultiWidget->EnableNavigationControllerEventListening(); mitk::GlobalInteraction::GetInstance()->AddListener( m_StdMultiWidget->GetMoveAndZoomInteractor() ); this->GetSite()->GetPage()->AddPartListener(cherry::IPartListener::Pointer(this)); // enable change of logo cherry::IPreferencesService::Pointer prefService = cherry::Platform::GetServiceRegistry() .GetServiceById<cherry::IPreferencesService>(cherry::IPreferencesService::ID); cherry::IPreferences::Pointer logoPref = prefService->GetSystemPreferences()->Node("DepartmentLogo"); std::string departmentLogoLocation = logoPref->Get("DepartmentLogo",""); m_StdMultiWidget->SetDepartmentLogoPath(departmentLogoLocation.c_str()); m_StdMultiWidget->DisableDepartmentLogo(); m_StdMultiWidget->EnableDepartmentLogo(); } } cherry::IPartListener::Events::Types QmitkStdMultiWidgetEditor::GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void QmitkStdMultiWidgetEditor::PartClosed( cherry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void QmitkStdMultiWidgetEditor::PartVisible( cherry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->AddPlanesToDataStorage(); } } } void QmitkStdMultiWidgetEditor::PartHidden( cherry::IWorkbenchPartReference::Pointer partRef ) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); if (m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { m_StdMultiWidget->RemovePlanesFromDataStorage(); } } } void QmitkStdMultiWidgetEditor::SetFocus() { if (m_StdMultiWidget != 0) m_StdMultiWidget->setFocus(); } <|endoftext|>
<commit_before>/** * \file timeout.cc * * * * \author Ethan Burns * \date 2008-12-16 */ #include <iostream> #include <string.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> #include "../search.h" using namespace std; static volatile bool timeout_stopped = false; extern "C" void alarm_action(int sig) { if (timeout_stopped) return; output_search_stats_on_timeout(); cout << "# Time out" << endl << "cost: infinity" << endl << "length: infinity" << endl << "wall_time: infinity" << endl << "CPU_time: infinity" << endl << "generated: infinity" << endl << "expanded: infinity" << endl; exit(EXIT_SUCCESS); } void timeout(unsigned int sec) { struct sigaction sa; memset(&sa, '\0', sizeof(sa)); sa.sa_handler = alarm_action; sigfillset(&sa.sa_mask); sigaction(SIGALRM, &sa, NULL); timeout_stopped = false; alarm(sec); } void timeout_stop(void) { timeout_stopped = true; } <commit_msg>Output what the timelimit was when there is a timeout.<commit_after>/** * \file timeout.cc * * * * \author Ethan Burns * \date 2008-12-16 */ #include <iostream> #include <string.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> #include "../search.h" using namespace std; static volatile bool timeout_stopped = false; static unsigned int timelimit = 0; extern "C" void alarm_action(int sig) { if (timeout_stopped) return; output_search_stats_on_timeout(); cout << "# Time out" << endl << "time-limit: " << timelimit << endl << "cost: infinity" << endl << "length: infinity" << endl << "wall_time: infinity" << endl << "CPU_time: infinity" << endl << "generated: infinity" << endl << "expanded: infinity" << endl; exit(EXIT_SUCCESS); } void timeout(unsigned int sec) { struct sigaction sa; timelimit = sec; memset(&sa, '\0', sizeof(sa)); sa.sa_handler = alarm_action; sigfillset(&sa.sa_mask); sigaction(SIGALRM, &sa, NULL); timeout_stopped = false; alarm(sec); } void timeout_stop(void) { timeout_stopped = true; } <|endoftext|>
<commit_before>#ifndef _UTILS_ALIGN_HPP_ #define _UTILS_ALIGN_HPP_ template<typename T> static inline T align_downto(T n, T align) { return n - (n % align); } template<typename T> static inline T align_upto(T n, T align) { return n % align ? align_downto(n, align) + align : n; } #endif <commit_msg>Remove utils/align.hpp because it duplicates functionality found in utils.hpp and also it's not being used anywhere.<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <math.h> #include <string.h> #include <vector> #include "mex.h" #include <nix.hpp> #include "handle.h" #include "arguments.h" #include "struct.h" #include "datatypes.h" void check_arg_type(const mxArray *arr, nix::DataType dtype) { if (dtype_mex2nix(arr) != dtype) { throw std::invalid_argument("wrong type"); } } mxArray *nmCreateScalar(uint32_t val) { mxArray *arr = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL); void *data = mxGetData(arr); memcpy(data, &val, sizeof(uint32_t)); return arr; } mxArray *dim_to_struct(nix::SetDimension dim) { struct_builder sb({ 1 }, { "type", "type_id", "labels" }); sb.set("set"); sb.set(1); sb.set(dim.labels()); return sb.array(); } mxArray *dim_to_struct(nix::SampledDimension dim) { struct_builder sb({ 1 }, { "type", "type_id", "interval", "label", "unit" }); sb.set("sampled"); sb.set(2); sb.set(dim.samplingInterval()); sb.set(dim.label()); sb.set(dim.unit()); return sb.array(); } mxArray *dim_to_struct(nix::RangeDimension dim) { struct_builder sb({ 1 }, { "type", "type_id", "ticks", "unit" }); sb.set("range"); sb.set(3); sb.set(dim.ticks()); sb.set(dim.unit()); return sb.array(); } nix::NDSize mx_array_to_ndsize(const mxArray *arr) { size_t m = mxGetM(arr); size_t n = mxGetN(arr); //if (m != 1 && n != 1) size_t k = std::max(n, m); nix::NDSize size(k); double *data = mxGetPr(arr); for (size_t i = 0; i < size.size(); i++) { size[i] = static_cast<nix::NDSize::value_type>(data[i]); } return size; } std::string mx_array_to_str(const mxArray *arr) { check_arg_type(arr, nix::DataType::String); char *tmp = mxArrayToString(arr); std::string the_string(tmp); mxFree(tmp); return the_string; } template<typename T> T mx_array_to_num(const mxArray *arr) { check_arg_type(arr, nix::to_data_type<T>::value); if (mxGetNumberOfElements(arr) < 1) { throw std::runtime_error("array empty"); } const void *data = mxGetData(arr); T res; memcpy(&res, data, sizeof(T)); return res; } bool mx_array_to_bool(const mxArray *arr) { check_arg_type(arr, nix::DataType::Bool); const mxLogical *l = mxGetLogicals(arr); return l[0]; } nix::Value mx_array_to_value(const mxArray *arr) { nix::Value val; switch (mxGetClassID(arr)) { case mxLOGICAL_CLASS: val.set(mx_array_to_bool(arr)); break; case mxCHAR_CLASS: val.set(mx_array_to_str(arr)); break; case mxDOUBLE_CLASS: val.set(mx_array_to_num<double>(arr)); break; case mxUINT32_CLASS: val.set(mx_array_to_num<uint32_t>(arr)); break; case mxINT32_CLASS: val.set(mx_array_to_num<int32_t>(arr)); break; case mxUINT64_CLASS: val.set(mx_array_to_num<uint64_t>(arr)); break; case mxINT64_CLASS: val.set(mx_array_to_num<int64_t>(arr)); break; case mxSINGLE_CLASS: throw std::invalid_argument("Element type is not supported"); case mxUINT8_CLASS: throw std::invalid_argument("Element type is not supported"); case mxINT8_CLASS: throw std::invalid_argument("Element type is not supported"); case mxUINT16_CLASS: throw std::invalid_argument("Element type is not supported"); case mxINT16_CLASS: throw std::invalid_argument("Element type is not supported"); default: throw std::invalid_argument("Element type is not recognized"); } return val; } <commit_msg>string construction fix<commit_after>#include <iostream> #include <math.h> #include <string.h> #include <vector> #include "mex.h" #include <nix.hpp> #include "handle.h" #include "arguments.h" #include "struct.h" #include "datatypes.h" void check_arg_type(const mxArray *arr, nix::DataType dtype) { if (dtype_mex2nix(arr) != dtype) { throw std::invalid_argument("wrong type"); } } mxArray *nmCreateScalar(uint32_t val) { mxArray *arr = mxCreateNumericMatrix(1, 1, mxUINT32_CLASS, mxREAL); void *data = mxGetData(arr); memcpy(data, &val, sizeof(uint32_t)); return arr; } mxArray *dim_to_struct(nix::SetDimension dim) { struct_builder sb({ 1 }, { "type", "type_id", "labels" }); sb.set("set"); sb.set(1); sb.set(dim.labels()); return sb.array(); } mxArray *dim_to_struct(nix::SampledDimension dim) { struct_builder sb({ 1 }, { "type", "type_id", "interval", "label", "unit" }); sb.set("sampled"); sb.set(2); sb.set(dim.samplingInterval()); sb.set(dim.label()); sb.set(dim.unit()); return sb.array(); } mxArray *dim_to_struct(nix::RangeDimension dim) { struct_builder sb({ 1 }, { "type", "type_id", "ticks", "unit" }); sb.set("range"); sb.set(3); sb.set(dim.ticks()); sb.set(dim.unit()); return sb.array(); } nix::NDSize mx_array_to_ndsize(const mxArray *arr) { size_t m = mxGetM(arr); size_t n = mxGetN(arr); //if (m != 1 && n != 1) size_t k = std::max(n, m); nix::NDSize size(k); double *data = mxGetPr(arr); for (size_t i = 0; i < size.size(); i++) { size[i] = static_cast<nix::NDSize::value_type>(data[i]); } return size; } std::string mx_array_to_str(const mxArray *arr) { check_arg_type(arr, nix::DataType::String); std::string the_string = mxArrayToString(arr); return the_string; } template<typename T> T mx_array_to_num(const mxArray *arr) { check_arg_type(arr, nix::to_data_type<T>::value); if (mxGetNumberOfElements(arr) < 1) { throw std::runtime_error("array empty"); } const void *data = mxGetData(arr); T res; memcpy(&res, data, sizeof(T)); return res; } bool mx_array_to_bool(const mxArray *arr) { check_arg_type(arr, nix::DataType::Bool); const mxLogical *l = mxGetLogicals(arr); return l[0]; } nix::Value mx_array_to_value(const mxArray *arr) { nix::Value val; switch (mxGetClassID(arr)) { case mxLOGICAL_CLASS: val.set(mx_array_to_bool(arr)); break; case mxCHAR_CLASS: val.set(mx_array_to_str(arr)); break; case mxDOUBLE_CLASS: val.set(mx_array_to_num<double>(arr)); break; case mxUINT32_CLASS: val.set(mx_array_to_num<uint32_t>(arr)); break; case mxINT32_CLASS: val.set(mx_array_to_num<int32_t>(arr)); break; case mxUINT64_CLASS: val.set(mx_array_to_num<uint64_t>(arr)); break; case mxINT64_CLASS: val.set(mx_array_to_num<int64_t>(arr)); break; case mxSINGLE_CLASS: throw std::invalid_argument("Element type is not supported"); case mxUINT8_CLASS: throw std::invalid_argument("Element type is not supported"); case mxINT8_CLASS: throw std::invalid_argument("Element type is not supported"); case mxUINT16_CLASS: throw std::invalid_argument("Element type is not supported"); case mxINT16_CLASS: throw std::invalid_argument("Element type is not supported"); default: throw std::invalid_argument("Element type is not recognized"); } return val; } <|endoftext|>
<commit_before>/* * Stock of connections to a memcached server. * * author: Max Kellermann <mk@cm4all.com> */ #include "memcached_stock.hxx" #include "memcached_client.hxx" #include "stock/GetHandler.hxx" #include "stock/Item.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "address_list.hxx" #include "lease.hxx" #include "pool.hxx" #include "istream/istream.hxx" #include "net/SocketAddress.hxx" #include <glib.h> #include <assert.h> #include <string.h> #include <sys/socket.h> struct MemachedStock { TcpBalancer &tcp_balancer; const AddressList &address; MemachedStock(TcpBalancer &_tcp_balancer, const AddressList &_address) :tcp_balancer(_tcp_balancer), address(_address) {} }; MemachedStock * memcached_stock_new(TcpBalancer *tcp_balancer, const AddressList *address) { return new MemachedStock(*tcp_balancer, *address); } void memcached_stock_free(MemachedStock *stock) { delete stock; } struct MemcachedStockRequest final : public StockGetHandler, Lease { struct pool *pool; StockItem *item; enum memcached_opcode opcode; const void *extras; size_t extras_length; const void *key; size_t key_length; Istream *value; const struct memcached_client_handler *handler; void *handler_ctx; struct async_operation_ref *async_ref; /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(GError *error) override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { item->Put(!reuse); } }; /* * stock callback * */ void MemcachedStockRequest::OnStockItemReady(StockItem &_item) { item = &_item; memcached_client_invoke(pool, tcp_stock_item_get(_item), tcp_stock_item_get_domain(_item) == AF_LOCAL ? FdType::FD_SOCKET : FdType::FD_TCP, *this, opcode, extras, extras_length, key, key_length, value, handler, handler_ctx, async_ref); } void MemcachedStockRequest::OnStockItemError(GError *error) { handler->error(error, handler_ctx); if (value != nullptr) value->CloseUnused(); } void memcached_stock_invoke(struct pool *pool, MemachedStock *stock, enum memcached_opcode opcode, const void *extras, size_t extras_length, const void *key, size_t key_length, Istream *value, const struct memcached_client_handler *handler, void *handler_ctx, struct async_operation_ref *async_ref) { auto request = PoolAlloc<MemcachedStockRequest>(*pool); assert(extras_length <= MEMCACHED_EXTRAS_MAX); assert(key_length <= MEMCACHED_KEY_MAX); request->pool = pool; request->opcode = opcode; request->extras = extras; request->extras_length = extras_length; request->key = key; request->key_length = key_length; request->value = value; request->handler = handler; request->handler_ctx = handler_ctx; request->async_ref = async_ref; tcp_balancer_get(stock->tcp_balancer, *pool, false, SocketAddress::Null(), 0, stock->address, 10, *request, *async_ref); } <commit_msg>memcached/stock: add MemcachedStockRequest constructor<commit_after>/* * Stock of connections to a memcached server. * * author: Max Kellermann <mk@cm4all.com> */ #include "memcached_stock.hxx" #include "memcached_client.hxx" #include "stock/GetHandler.hxx" #include "stock/Item.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "address_list.hxx" #include "lease.hxx" #include "pool.hxx" #include "istream/istream.hxx" #include "net/SocketAddress.hxx" #include <glib.h> #include <assert.h> #include <string.h> #include <sys/socket.h> struct MemachedStock { TcpBalancer &tcp_balancer; const AddressList &address; MemachedStock(TcpBalancer &_tcp_balancer, const AddressList &_address) :tcp_balancer(_tcp_balancer), address(_address) {} }; MemachedStock * memcached_stock_new(TcpBalancer *tcp_balancer, const AddressList *address) { return new MemachedStock(*tcp_balancer, *address); } void memcached_stock_free(MemachedStock *stock) { delete stock; } struct MemcachedStockRequest final : public StockGetHandler, Lease { struct pool &pool; StockItem *item; const enum memcached_opcode opcode; const void *const extras; const size_t extras_length; const void *const key; const size_t key_length; Istream *const value; const struct memcached_client_handler &handler; void *const handler_ctx; struct async_operation_ref &async_ref; MemcachedStockRequest(struct pool &_pool, enum memcached_opcode _opcode, const void *_extras, size_t _extras_length, const void *_key, size_t _key_length, Istream *_value, const struct memcached_client_handler &_handler, void *_handler_ctx, struct async_operation_ref &_async_ref) :pool(_pool), opcode(_opcode), extras(_extras), extras_length(_extras_length), key(_key), key_length(_key_length), value(_value), handler(_handler), handler_ctx(_handler_ctx), async_ref(_async_ref) {} /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(GError *error) override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { item->Put(!reuse); } }; /* * stock callback * */ void MemcachedStockRequest::OnStockItemReady(StockItem &_item) { item = &_item; memcached_client_invoke(&pool, tcp_stock_item_get(_item), tcp_stock_item_get_domain(_item) == AF_LOCAL ? FdType::FD_SOCKET : FdType::FD_TCP, *this, opcode, extras, extras_length, key, key_length, value, &handler, handler_ctx, &async_ref); } void MemcachedStockRequest::OnStockItemError(GError *error) { handler.error(error, handler_ctx); if (value != nullptr) value->CloseUnused(); } void memcached_stock_invoke(struct pool *pool, MemachedStock *stock, enum memcached_opcode opcode, const void *extras, size_t extras_length, const void *key, size_t key_length, Istream *value, const struct memcached_client_handler *handler, void *handler_ctx, struct async_operation_ref *async_ref) { assert(extras_length <= MEMCACHED_EXTRAS_MAX); assert(key_length <= MEMCACHED_KEY_MAX); auto request = NewFromPool<MemcachedStockRequest>(*pool, *pool, opcode, extras, extras_length, key, key_length, value, *handler, handler_ctx, *async_ref); tcp_balancer_get(stock->tcp_balancer, *pool, false, SocketAddress::Null(), 0, stock->address, 10, *request, *async_ref); } <|endoftext|>
<commit_before>#pragma once #include <string> #include <vector> #include "config.hpp" #include "span.hpp" namespace utki{ /** * @brief Format string. * @param format - printf-like string format. * @return formatted string. */ #if M_COMPILER != M_COMPILER_MSVC __attribute__((format(printf, 1, 2))) #endif std::string make_string(const char* format, ...); /** * @brief Format string. * va_list version of make_string(). * @param format - printf-like string format. * @param args - va_list of string arguments. * @return formatted string. */ std::string make_string_va_list(const char* format, va_list args); /** * @brief Make string out of char buffer. * @param buf - char buffer to make the string from. * @return string representing the contents of the char buffer. */ std::string make_string(const utki::span<char> buf){ return std::string(buf.data(), buf.size()); } /** * @brief Split string using give delimiter. * @param str - string to split. * @param delimiter - delimiter character to use as a splitter. * @return vector of splitted strings. */ std::vector<std::string> split(const std::string& str, char delimiter); /** * @brief Word wrap string. * @param str - string to word wrap. * @param width - maximum number of characters per line. * @return list of word wrapped lines. */ std::vector<std::string> word_wrap(const std::string& str, unsigned width); } <commit_msg>build fix<commit_after>#pragma once #include <string> #include <vector> #include "config.hpp" #include "span.hpp" namespace utki{ /** * @brief Format string. * @param format - printf-like string format. * @return formatted string. */ #if M_COMPILER != M_COMPILER_MSVC __attribute__((format(printf, 1, 2))) #endif std::string make_string(const char* format, ...); /** * @brief Format string. * va_list version of make_string(). * @param format - printf-like string format. * @param args - va_list of string arguments. * @return formatted string. */ std::string make_string_va_list(const char* format, va_list args); /** * @brief Make string out of char buffer. * @param buf - char buffer to make the string from. * @return string representing the contents of the char buffer. */ inline std::string make_string(const utki::span<char> buf){ return std::string(buf.data(), buf.size()); } /** * @brief Split string using give delimiter. * @param str - string to split. * @param delimiter - delimiter character to use as a splitter. * @return vector of splitted strings. */ std::vector<std::string> split(const std::string& str, char delimiter); /** * @brief Word wrap string. * @param str - string to word wrap. * @param width - maximum number of characters per line. * @return list of word wrapped lines. */ std::vector<std::string> word_wrap(const std::string& str, unsigned width); } <|endoftext|>
<commit_before>/* * madgwick.cpp * Copyright (c) 2018, Robot Mitya. * 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 Robot Mitya nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Created on: Feb 17, 2018 * Author: Dmitry Dzakhov * Based on: Implementation of Madgwick's IMU and AHRS algorithms. * See: http://www.x-io.co.uk/node/8#open_source_ahrs_and_imu_algorithms */ #include <math.h> #include "madgwick.h" static tf2::Matrix3x3 m_; static tf2::Quaternion eulerQuaternion_; static tf2::Quaternion rotationZMinus90_(tf2::Vector3(0, 0, 1), -MadgwickImu::PI / 2.0f); MadgwickImu::MadgwickImu() { qSource_.setValue(0, 0, 0, 1); qCenter_.setValue(0, 0, 0, 1); qResult_ = qSource_ * qCenter_; tf2::Vector3 z(0, 0, 1); rotationZMinus90_.setRotation(z, -PI / 2.0f); } void MadgwickImu::center() { qCenter_ = qSource_.inverse(); } void MadgwickImu::update(float deltaTime, float gx, float gy, float gz, float ax, float ay, float az) { float q1 = qSource_.w(); float q2 = qSource_.x(); float q3 = qSource_.y(); float q4 = qSource_.z(); float norm; float s1, s2, s3, s4; float qDot1, qDot2, qDot3, qDot4; // Auxiliary variables to avoid repeated arithmetic float _2q1 = 2.0f * q1; float _2q2 = 2.0f * q2; float _2q3 = 2.0f * q3; float _2q4 = 2.0f * q4; float _4q1 = 4.0f * q1; float _4q2 = 4.0f * q2; float _4q3 = 4.0f * q3; float _8q2 = 8.0f * q2; float _8q3 = 8.0f * q3; float q1q1 = q1 * q1; float q2q2 = q2 * q2; float q3q3 = q3 * q3; float q4q4 = q4 * q4; // Normalize accelerometer measurement norm = (float) sqrt(ax * ax + ay * ay + az * az); if (norm < 0.0001f) return; // handle NaN norm = 1.0f / norm; // use reciprocal for division ax *= norm; ay *= norm; az *= norm; // Gradient decent algorithm corrective step s1 = _4q1 * q3q3 + _2q3 * ax + _4q1 * q2q2 - _2q2 * ay; s2 = _4q2 * q4q4 - _2q4 * ax + 4.0f * q1q1 * q2 - _2q1 * ay - _4q2 + _8q2 * q2q2 + _8q2 * q3q3 + _4q2 * az; s3 = 4.0f * q1q1 * q3 + _2q1 * ax + _4q3 * q4q4 - _2q4 * ay - _4q3 + _8q3 * q2q2 + _8q3 * q3q3 + _4q3 * az; s4 = 4.0f * q2q2 * q4 - _2q2 * ax + 4.0f * q3q3 * q4 - _2q3 * ay; norm = 1.0f / (float) sqrt(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4); // normalize step magnitude s1 *= norm; s2 *= norm; s3 *= norm; s4 *= norm; // Compute rate of change of quaternion qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - BETA * s1; qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - BETA * s2; qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - BETA * s3; qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - BETA * s4; // Integrate to yield quaternion q1 += qDot1 * deltaTime; q2 += qDot2 * deltaTime; q3 += qDot3 * deltaTime; q4 += qDot4 * deltaTime; norm = 1.0f / (float) sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalize quaternion q1 *= norm; q2 *= norm; q3 *= norm; q4 *= norm; qSource_.setValue(q2, q3, q4, q1); qResult_ = qSource_ * qCenter_; } void MadgwickImu::getQuaternion(tf2Scalar& x, tf2Scalar& y, tf2Scalar& z, tf2Scalar& w) { x = qResult_.x(); y = qResult_.y(); z = qResult_.z(); w = qResult_.w(); } void MadgwickImu::getEulerYP(tf2::Quaternion & quaternion, tf2Scalar& yaw, tf2Scalar& pitch) { // tf2::Vector3 z(0, 0, 1); // tf2::Quaternion rotationZMinus90_(z, -MadgwickImu::PI / 2.0f); eulerQuaternion_ = quaternion * rotationZMinus90_; m_.setRotation(eulerQuaternion_); tf2Scalar temp; m_.getEulerYPR(yaw, temp, pitch, 1); yaw *= TO_DEG; yaw += 90; if (yaw > 180) yaw -= 360; pitch *= TO_DEG; } void MadgwickImu::getEulerYP(tf2Scalar& yaw, tf2Scalar& pitch) { MadgwickImu::getEulerYP(qResult_, yaw, pitch); } /** * Fast inverse square-root * See: http://en.wikipedia.org/wiki/Fast_inverse_square_root */ float MadgwickImu::invSqrt(float x) { float halfx = 0.5f * x; float y = x; long i = *(long*)&y; i = 0x5f3759df - (i >> 1); y = *(float*)&i; y = y * (1.5f - (halfx * y * y)); return y; // return 1.0f / sqrt(x); } <commit_msg>#15 Madgwick center<commit_after>/* * madgwick.cpp * Copyright (c) 2018, Robot Mitya. * 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 Robot Mitya nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Created on: Feb 17, 2018 * Author: Dmitry Dzakhov * Based on: Implementation of Madgwick's IMU and AHRS algorithms. * See: http://www.x-io.co.uk/node/8#open_source_ahrs_and_imu_algorithms */ #include <math.h> #include "madgwick.h" static tf2::Matrix3x3 m_; static tf2::Quaternion eulerQuaternion_; static tf2::Quaternion rotationZMinus90_(tf2::Vector3(0, 0, 1), -MadgwickImu::PI / 2.0f); MadgwickImu::MadgwickImu() { qSource_.setValue(0, 0, 0, 1); qCenter_.setValue(0, 0, 0, 1); qResult_ = qSource_ * qCenter_; tf2::Vector3 z(0, 0, 1); rotationZMinus90_.setRotation(z, -PI / 2.0f); } void MadgwickImu::center() { tf2::Matrix3x3 matrix; matrix.setRotation(qSource_); tf2Scalar yaw, pitch, roll; matrix.getEulerYPR(yaw, pitch, roll); matrix.setEulerYPR(yaw, 0, 0); matrix.getRotation(qCenter_); qCenter_ = qCenter_.inverse(); //qCenter_ = qSource_.inverse(); } void MadgwickImu::update(float deltaTime, float gx, float gy, float gz, float ax, float ay, float az) { float q1 = qSource_.w(); float q2 = qSource_.x(); float q3 = qSource_.y(); float q4 = qSource_.z(); float norm; float s1, s2, s3, s4; float qDot1, qDot2, qDot3, qDot4; // Auxiliary variables to avoid repeated arithmetic float _2q1 = 2.0f * q1; float _2q2 = 2.0f * q2; float _2q3 = 2.0f * q3; float _2q4 = 2.0f * q4; float _4q1 = 4.0f * q1; float _4q2 = 4.0f * q2; float _4q3 = 4.0f * q3; float _8q2 = 8.0f * q2; float _8q3 = 8.0f * q3; float q1q1 = q1 * q1; float q2q2 = q2 * q2; float q3q3 = q3 * q3; float q4q4 = q4 * q4; // Normalize accelerometer measurement norm = (float) sqrt(ax * ax + ay * ay + az * az); if (norm < 0.0001f) return; // handle NaN norm = 1.0f / norm; // use reciprocal for division ax *= norm; ay *= norm; az *= norm; // Gradient decent algorithm corrective step s1 = _4q1 * q3q3 + _2q3 * ax + _4q1 * q2q2 - _2q2 * ay; s2 = _4q2 * q4q4 - _2q4 * ax + 4.0f * q1q1 * q2 - _2q1 * ay - _4q2 + _8q2 * q2q2 + _8q2 * q3q3 + _4q2 * az; s3 = 4.0f * q1q1 * q3 + _2q1 * ax + _4q3 * q4q4 - _2q4 * ay - _4q3 + _8q3 * q2q2 + _8q3 * q3q3 + _4q3 * az; s4 = 4.0f * q2q2 * q4 - _2q2 * ax + 4.0f * q3q3 * q4 - _2q3 * ay; norm = 1.0f / (float) sqrt(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4); // normalize step magnitude s1 *= norm; s2 *= norm; s3 *= norm; s4 *= norm; // Compute rate of change of quaternion qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - BETA * s1; qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - BETA * s2; qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - BETA * s3; qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - BETA * s4; // Integrate to yield quaternion q1 += qDot1 * deltaTime; q2 += qDot2 * deltaTime; q3 += qDot3 * deltaTime; q4 += qDot4 * deltaTime; norm = 1.0f / (float) sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalize quaternion q1 *= norm; q2 *= norm; q3 *= norm; q4 *= norm; qSource_.setValue(q2, q3, q4, q1); qResult_ = qSource_ * qCenter_; } void MadgwickImu::getQuaternion(tf2Scalar& x, tf2Scalar& y, tf2Scalar& z, tf2Scalar& w) { x = qResult_.x(); y = qResult_.y(); z = qResult_.z(); w = qResult_.w(); } void MadgwickImu::getEulerYP(tf2::Quaternion & quaternion, tf2Scalar& yaw, tf2Scalar& pitch) { // tf2::Vector3 z(0, 0, 1); // tf2::Quaternion rotationZMinus90_(z, -MadgwickImu::PI / 2.0f); eulerQuaternion_ = quaternion * rotationZMinus90_; m_.setRotation(eulerQuaternion_); tf2Scalar temp; m_.getEulerYPR(yaw, temp, pitch, 1); yaw *= TO_DEG; yaw += 90; if (yaw > 180) yaw -= 360; pitch *= TO_DEG; } void MadgwickImu::getEulerYP(tf2Scalar& yaw, tf2Scalar& pitch) { MadgwickImu::getEulerYP(qResult_, yaw, pitch); } /** * Fast inverse square-root * See: http://en.wikipedia.org/wiki/Fast_inverse_square_root */ float MadgwickImu::invSqrt(float x) { float halfx = 0.5f * x; float y = x; long i = *(long*)&y; i = 0x5f3759df - (i >> 1); y = *(float*)&i; y = y * (1.5f - (halfx * y * y)); return y; // return 1.0f / sqrt(x); } <|endoftext|>
<commit_before>// // IsingTest.cpp // jdemon // // Created by Mark Larus on 3/4/13. // Copyright (c) 2013 Kenyon College. All rights reserved. // #include <boost/test/unit_test.hpp> #include <set> #include <algorithm> #include <stack> #include "Ising.h" #include "Utilities.h" #include "TestFixtures.h" #include "MockObjects.h" class TransitionRuleTestFixture : \ public DefaultTransitionRuleTestFixture, \ public ValidStatesTestFixture \ {}; BOOST_FIXTURE_TEST_SUITE(TransitionRuleTest, TransitionRuleTestFixture); BOOST_AUTO_TEST_CASE ( testTableSize ) { for (TransitionRule::iterator it = defaultRule.begin(); it!=defaultRule.end(); ++it) { BOOST_REQUIRE(it->second.size() == 8 && "Transition table size should be 8"); } } BOOST_AUTO_TEST_CASE ( testTableDeadEnds ) { typedef TransitionRule::iterator RuleIterator; typedef TransitionTable::iterator TableIterator; for (RuleIterator currentRuleIterator = defaultRule.begin(); \ currentRuleIterator!=defaultRule.end(); ++currentRuleIterator) { TransitionTable currentRule = currentRuleIterator->second; for (TableIterator currentTableIterator = currentRule.begin();\ currentTableIterator != currentRule.end(); ++currentTableIterator) { BOOST_CHECK(currentTableIterator->second); } } } BOOST_AUTO_TEST_CASE ( testValidTargetStates ) { typedef TransitionRule::iterator RuleIterator; typedef TransitionTable::iterator TableIterator; for (RuleIterator currentRuleIterator = defaultRule.begin(); \ currentRuleIterator!=defaultRule.end(); ++currentRuleIterator) { TransitionTable currentRule = currentRuleIterator->second; for (TableIterator currentTableIterator = currentRule.begin();\ currentTableIterator != currentRule.end(); ++currentTableIterator) { SystemState *targetState = currentTableIterator->second; BOOST_CHECK(validStates.count(targetState)); } } } BOOST_AUTO_TEST_SUITE_END() class IsingReservoirTestFixture : \ public RandomNumberTestFixture, public ConstantsTestFixture, public ValidStatesTestFixture {}; BOOST_FIXTURE_TEST_SUITE(IsingReservoirTest, IsingReservoirTestFixture); BOOST_AUTO_TEST_CASE ( testWheelStep ) { IsingReservoir reservoir(rng,c,6,6); Reservoir::InteractionResult result; BOOST_REQUIRE_NO_THROW(reservoir.wheelStep(result)); } BOOST_AUTO_TEST_CASE ( testEmptyTransitionRule ) { TransitionRule emptyRule; IsingReservoir reservoir(rng,c,6,6,emptyRule); Reservoir::InteractionResult result; BOOST_REQUIRE_THROW(reservoir.wheelStep(result), EmptyTransitionRuleError); } BOOST_AUTO_TEST_CASE ( testDeadEndTransitionRule ) { TransitionRule deadEndRule; TransitionTable emptyTable; for (char k=0; k<8; k++) { emptyTable[k] = NULL; } Reservoir::InteractionResult result; for (StateSet::iterator it = validStates.begin(); it!=validStates.end(); ++it) { deadEndRule[*it] = emptyTable; } IsingReservoir reservoir(rng,c,6,6,deadEndRule); BOOST_REQUIRE_THROW(reservoir.wheelStep(result),TransitionDeadEndError); } BOOST_AUTO_TEST_CASE ( testTooSmallTransitionTable ) { TransitionRule invalidRule; TransitionTable tooSmallTable; for (char k=0; k<3; k++) { tooSmallTable[k] = NULL; } for (StateSet::iterator it = validStates.begin(); it!=validStates.end(); ++it) { invalidRule[*it] = tooSmallTable; } IsingReservoir reservoir(rng,c,6,6,invalidRule); Reservoir::InteractionResult result; BOOST_REQUIRE_THROW(reservoir.wheelStep(result),InvalidTableSizeError); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(IsingUtilityTest) BOOST_AUTO_TEST_CASE( testNonbinaryParity ) { int inputState = Ising::s(0,0,157); BOOST_REQUIRE(inputState == 1); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(ClusterMethodTest, GridOperationTestFixture) BOOST_AUTO_TEST_CASE( includeNoCells ) { Ising::Cell *startingPoint = grid[5]; MockRandomnessDelegate delegate(false,0); ClusterMethodAgent agent(&delegate,1); agent.performMethodAtCell(startingPoint); std::set<Ising::Cell *> expectedCells; expectedCells.insert(startingPoint); std::set<Ising::Cell *> actualCells = changedCells(); BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end()); } BOOST_AUTO_TEST_CASE( includeAllCells ) { // This breaks if the default cell value is non-zero. Ising::Cell *startingPoint = grid[5]; MockRandomnessDelegate delegate(true,0); ClusterMethodAgent agent(&delegate,1); agent.performMethodAtCell(startingPoint); std::set<Ising::Cell *> expectedCells; expectedCells.insert(grid.begin(),grid.end()); std::set<Ising::Cell *> actualCells = changedCells(); BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end()); } BOOST_AUTO_TEST_CASE( includeSomeCells ) { Ising::Cell *startingPoint = grid[5]; std::set<Ising::Cell *> expectedCells; std::stack<Ising::Cell *> stack; stack.push(startingPoint); size_t size = 12; while (expectedCells.size()!=size) { if (stack.empty()) { BOOST_FAIL("Stack should not be empty."); } Ising::Cell *currentCell = stack.top(); stack.pop(); Ising::Cell::Neighbors neighbors = currentCell->getNeighbors(); for (Ising::Cell::Neighbors::iterator it = neighbors.begin(); it!=neighbors.end(); ++it) { if (!expectedCells.count(*it)) { stack.push(*it); } } expectedCells.insert(currentCell); } BOOST_REQUIRE_EQUAL(expectedCells.size(),size); for (Ising::Grid::iterator it = grid.begin(); it!=grid.end(); ++it) { if (expectedCells.count(*it)) { (*it)->setValue(1); } else { (*it)->setValue(0); } } resetInitialValues(); MockRandomnessDelegate delegate(true,0); ClusterMethodAgent agent(&delegate,1); agent.performMethodAtCell(startingPoint); std::set<Ising::Cell *> actualCells = changedCells(); BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end()); } BOOST_AUTO_TEST_CASE( testInclusionProbability ) { BOOST_CHECK_THROW(ClusterMethodAgent(NULL,-0.01), InvalidProbabilityError); BOOST_CHECK_THROW(ClusterMethodAgent(NULL,1.01), InvalidProbabilityError); } BOOST_AUTO_TEST_SUITE_END()<commit_msg>Include all cells no longer fails if the default cell value is non-zero.<commit_after>// // IsingTest.cpp // jdemon // // Created by Mark Larus on 3/4/13. // Copyright (c) 2013 Kenyon College. All rights reserved. // #include <boost/test/unit_test.hpp> #include <set> #include <algorithm> #include <stack> #include "Ising.h" #include "Utilities.h" #include "TestFixtures.h" #include "MockObjects.h" class TransitionRuleTestFixture : \ public DefaultTransitionRuleTestFixture, \ public ValidStatesTestFixture \ {}; BOOST_FIXTURE_TEST_SUITE(TransitionRuleTest, TransitionRuleTestFixture); BOOST_AUTO_TEST_CASE ( testTableSize ) { for (TransitionRule::iterator it = defaultRule.begin(); it!=defaultRule.end(); ++it) { BOOST_REQUIRE(it->second.size() == 8 && "Transition table size should be 8"); } } BOOST_AUTO_TEST_CASE ( testTableDeadEnds ) { typedef TransitionRule::iterator RuleIterator; typedef TransitionTable::iterator TableIterator; for (RuleIterator currentRuleIterator = defaultRule.begin(); \ currentRuleIterator!=defaultRule.end(); ++currentRuleIterator) { TransitionTable currentRule = currentRuleIterator->second; for (TableIterator currentTableIterator = currentRule.begin();\ currentTableIterator != currentRule.end(); ++currentTableIterator) { BOOST_CHECK(currentTableIterator->second); } } } BOOST_AUTO_TEST_CASE ( testValidTargetStates ) { typedef TransitionRule::iterator RuleIterator; typedef TransitionTable::iterator TableIterator; for (RuleIterator currentRuleIterator = defaultRule.begin(); \ currentRuleIterator!=defaultRule.end(); ++currentRuleIterator) { TransitionTable currentRule = currentRuleIterator->second; for (TableIterator currentTableIterator = currentRule.begin();\ currentTableIterator != currentRule.end(); ++currentTableIterator) { SystemState *targetState = currentTableIterator->second; BOOST_CHECK(validStates.count(targetState)); } } } BOOST_AUTO_TEST_SUITE_END() class IsingReservoirTestFixture : \ public RandomNumberTestFixture, public ConstantsTestFixture, public ValidStatesTestFixture {}; BOOST_FIXTURE_TEST_SUITE(IsingReservoirTest, IsingReservoirTestFixture); BOOST_AUTO_TEST_CASE ( testWheelStep ) { IsingReservoir reservoir(rng,c,6,6); Reservoir::InteractionResult result; BOOST_REQUIRE_NO_THROW(reservoir.wheelStep(result)); } BOOST_AUTO_TEST_CASE ( testEmptyTransitionRule ) { TransitionRule emptyRule; IsingReservoir reservoir(rng,c,6,6,emptyRule); Reservoir::InteractionResult result; BOOST_REQUIRE_THROW(reservoir.wheelStep(result), EmptyTransitionRuleError); } BOOST_AUTO_TEST_CASE ( testDeadEndTransitionRule ) { TransitionRule deadEndRule; TransitionTable emptyTable; for (char k=0; k<8; k++) { emptyTable[k] = NULL; } Reservoir::InteractionResult result; for (StateSet::iterator it = validStates.begin(); it!=validStates.end(); ++it) { deadEndRule[*it] = emptyTable; } IsingReservoir reservoir(rng,c,6,6,deadEndRule); BOOST_REQUIRE_THROW(reservoir.wheelStep(result),TransitionDeadEndError); } BOOST_AUTO_TEST_CASE ( testTooSmallTransitionTable ) { TransitionRule invalidRule; TransitionTable tooSmallTable; for (char k=0; k<3; k++) { tooSmallTable[k] = NULL; } for (StateSet::iterator it = validStates.begin(); it!=validStates.end(); ++it) { invalidRule[*it] = tooSmallTable; } IsingReservoir reservoir(rng,c,6,6,invalidRule); Reservoir::InteractionResult result; BOOST_REQUIRE_THROW(reservoir.wheelStep(result),InvalidTableSizeError); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(IsingUtilityTest) BOOST_AUTO_TEST_CASE( testNonbinaryParity ) { int inputState = Ising::s(0,0,157); BOOST_REQUIRE(inputState == 1); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(ClusterMethodTest, GridOperationTestFixture) BOOST_AUTO_TEST_CASE( includeNoCells ) { Ising::Cell *startingPoint = grid[5]; MockRandomnessDelegate delegate(false,0); ClusterMethodAgent agent(&delegate,1); agent.performMethodAtCell(startingPoint); std::set<Ising::Cell *> expectedCells; expectedCells.insert(startingPoint); std::set<Ising::Cell *> actualCells = changedCells(); BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end()); } BOOST_AUTO_TEST_CASE( includeAllCells ) { for (Ising::Grid::iterator it = grid.begin(); it!=grid.end(); ++it) { (*it)->setValue(0); } Ising::Cell *startingPoint = grid[5]; MockRandomnessDelegate delegate(true,0); ClusterMethodAgent agent(&delegate,1); agent.performMethodAtCell(startingPoint); std::set<Ising::Cell *> expectedCells; expectedCells.insert(grid.begin(),grid.end()); std::set<Ising::Cell *> actualCells = changedCells(); BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end()); } BOOST_AUTO_TEST_CASE( includeSomeCells ) { Ising::Cell *startingPoint = grid[5]; std::set<Ising::Cell *> expectedCells; std::stack<Ising::Cell *> stack; stack.push(startingPoint); size_t size = 12; while (expectedCells.size()!=size) { if (stack.empty()) { BOOST_FAIL("Stack should not be empty."); } Ising::Cell *currentCell = stack.top(); stack.pop(); Ising::Cell::Neighbors neighbors = currentCell->getNeighbors(); for (Ising::Cell::Neighbors::iterator it = neighbors.begin(); it!=neighbors.end(); ++it) { if (!expectedCells.count(*it)) { stack.push(*it); } } expectedCells.insert(currentCell); } BOOST_REQUIRE_EQUAL(expectedCells.size(),size); for (Ising::Grid::iterator it = grid.begin(); it!=grid.end(); ++it) { if (expectedCells.count(*it)) { (*it)->setValue(1); } else { (*it)->setValue(0); } } resetInitialValues(); MockRandomnessDelegate delegate(true,0); ClusterMethodAgent agent(&delegate,1); agent.performMethodAtCell(startingPoint); std::set<Ising::Cell *> actualCells = changedCells(); BOOST_REQUIRE_EQUAL_COLLECTIONS(expectedCells.begin(), expectedCells.end(), actualCells.begin(), actualCells.end()); } BOOST_AUTO_TEST_CASE( testInclusionProbability ) { BOOST_CHECK_THROW(ClusterMethodAgent(NULL,-0.01), InvalidProbabilityError); BOOST_CHECK_THROW(ClusterMethodAgent(NULL,1.01), InvalidProbabilityError); } BOOST_AUTO_TEST_SUITE_END()<|endoftext|>
<commit_before>#include "mssqlclrgeo.hpp" #include <cstring> namespace mssqlclr { const std::vector<Figure> Geometry::getFiguresFromShape(int shapeIdx) const { std::vector<Figure> figures_list; if (Figures.empty()) { return figures_list; } int32_t offset = Shapes[shapeIdx].FigureOffset; if (Shapes.size() > shapeIdx + 1) { int32_t offsetEnd = Shapes[shapeIdx + 1].FigureOffset; figures_list = std::vector<Figure>(Figures.cbegin() + offset, Figures.cbegin() + offsetEnd); } else { figures_list = std::vector<Figure>(Figures.cbegin() + offset, Figures.cend()); } return figures_list; } const std::vector<Point> Geometry::getPointsFromFigure(int figureIdx) const { std::vector<Point> points_list; if (Points.empty()) { return points_list; } int32_t offset = Figures[figureIdx].Offset; if (Figures.size() > figureIdx + 1) { int32_t offsetEnd = Figures[figureIdx + 1].Offset; points_list = std::vector<Point>(Points.cbegin() + offset, Points.cbegin() + offsetEnd); } else { points_list = std::vector<Point>(Points.cbegin() + offset, Points.cend()); } return points_list; } sqlgeo_reader::sqlgeo_reader(const char* data, std::size_t size) : data_(data), size_(size), pos_(0) { } uint32_t sqlgeo_reader::read_uint32() { std::uint32_t val; if (pos_ + 4 > size_) { return 0; } auto data = data_ + pos_; std::memcpy(&val, data, 4); pos_ += 4; return val; } uint16_t sqlgeo_reader::read_uint16() { std::uint16_t val; if (pos_ + 2 > size_) { return 0; } auto data = data_ + pos_; std::memcpy(&val, data, 2); pos_ += 2; return val; } uint8_t sqlgeo_reader::read_uint8() { std::uint8_t val; if (pos_ + 1 > size_) { return 0; } auto data = data_ + pos_; std::memcpy(&val, data, 1); pos_ += 1; return val; } double sqlgeo_reader::read_double() { double val; if (pos_ + 8 > size_) { return 0; } auto data = data_ + pos_; std::memcpy(&val, &data[0], 8); pos_ += 8; return val; } void sqlgeo_reader::readPointsZ(std::vector<Point> points) { if (points.empty()) { return; } for (auto point : points) { point.Z = read_double(); } } void sqlgeo_reader::readPointsM(std::vector<Point> points) { if (points.empty()) { return; } for (auto point : points) { point.M = read_double(); } } std::vector<Point> sqlgeo_reader::readPoints(uint32_t count, bool isGeography) { std::vector<Point> points; if (count < 1) { return std::vector<Point>(); } for (uint32_t i = 0; i < count; i++) { if (isGeography) { double y = read_double(); double x = read_double(); points.emplace_back(x, y); } else { double x = read_double(); double y = read_double(); points.emplace_back(x, y); } } return points; } std::vector<Figure> sqlgeo_reader::readFigures(uint32_t count, SerializationProperties properties) { std::vector<Figure> figures; if (count == 0) { return figures; } if (properties.P || properties.L) { figures.emplace_back(FIGURE_STROKE, 0); } else { for (int i = 0; i < count; i++) { Figure f; f.Attribute = (FIGURE)read_uint8(); f.Offset = read_uint32(); figures.push_back(f); } } return figures; } std::vector<Shape> sqlgeo_reader::readShapes(uint32_t count, SerializationProperties properties) { std::vector<Shape> shapes; if (count < 1) { return shapes; } if (properties.P) { shapes.emplace_back(-1, 0, SHAPE_POINT); } else if (properties.L) { shapes.emplace_back(-1, 0, SHAPE_LINESTRING); } else { for (int i = 0; i < int(count); i++) { uint32_t parent_offset = read_uint32(); uint32_t figure_offset = read_uint32(); SHAPE type = (SHAPE)read_uint8(); shapes.emplace_back(parent_offset, figure_offset, type); } } return shapes; } std::vector<Segment> sqlgeo_reader::readSegments(uint32_t count) { std::vector<Segment> segments; if (count < 1) { return segments; } for (int i = 0; i < int(count); i++) { Segment s; s.Type = (SEGMENT)read_uint8(); segments.push_back(s); } return segments; } Geometry sqlgeo_reader::parseGeography() { return parseGeometry(true); } Geometry sqlgeo_reader::parseGeometry(bool isGeography) { Geometry g = {}; uint32_t numberOfPoints; uint32_t numberOfFigures; uint32_t numberOfShapes; uint32_t numberOfSegments; g.SRID = read_uint32(); if (isGeography == true) { if (g.SRID == -1) { return g; } else if (g.SRID < 4210 || g.SRID > 4999) { g.Properties.V = false; return g; //("Invalid SRID for geography"); } } //version g.Version = read_uint8(); if (g.Version > 2) { g.Properties.V = false; return g; //("Version %d is not supported", g.Version); } //flags uint8_t flags = 0; flags = read_uint8(); g.Properties.Z = (flags & (1 << 0)) != 0; g.Properties.M = (flags & (1 << 1)) != 0; g.Properties.V = (flags & (1 << 2)) != 0; g.Properties.P = (flags & (1 << 3)) != 0; g.Properties.L = (flags & (1 << 4)) != 0; if (g.Version == 2) { g.Properties.H = (flags & (1 << 5)) != 0; } if (g.Properties.P && g.Properties.L) { g.Properties.V = false; return g; //("geometry data is invalid"); } //points if (g.Properties.P) { numberOfPoints = 1; } else if (g.Properties.L) { numberOfPoints = 2; } else { numberOfPoints = read_uint32(); } g.Points = readPoints(numberOfPoints, isGeography); if (g.Properties.Z) { readPointsZ(g.Points); } if (g.Properties.M) { readPointsM(g.Points); } //figures if (g.Properties.P || g.Properties.L) { numberOfFigures = 1; } else { numberOfFigures = read_uint32(); } g.Figures = readFigures(numberOfFigures, g.Properties); //shapes if (g.Properties.P || g.Properties.L) { numberOfShapes = 1; } else { numberOfShapes = read_uint32(); } g.Shapes = readShapes(numberOfShapes, g.Properties); //segments if (g.Version == 2) { numberOfSegments = read_uint32(); g.Segments = readSegments(numberOfSegments); } return g; } }<commit_msg>call reserve() on vector<commit_after>#include "mssqlclrgeo.hpp" #include <cstring> namespace mssqlclr { const std::vector<Figure> Geometry::getFiguresFromShape(int shapeIdx) const { std::vector<Figure> figures_list; if (Figures.empty()) { return figures_list; } int32_t offset = Shapes[shapeIdx].FigureOffset; if (Shapes.size() > shapeIdx + 1) { int32_t offsetEnd = Shapes[shapeIdx + 1].FigureOffset; figures_list = std::vector<Figure>(Figures.cbegin() + offset, Figures.cbegin() + offsetEnd); } else { figures_list = std::vector<Figure>(Figures.cbegin() + offset, Figures.cend()); } return figures_list; } const std::vector<Point> Geometry::getPointsFromFigure(int figureIdx) const { std::vector<Point> points_list; if (Points.empty()) { return points_list; } int32_t offset = Figures[figureIdx].Offset; if (Figures.size() > figureIdx + 1) { int32_t offsetEnd = Figures[figureIdx + 1].Offset; points_list = std::vector<Point>(Points.cbegin() + offset, Points.cbegin() + offsetEnd); } else { points_list = std::vector<Point>(Points.cbegin() + offset, Points.cend()); } return points_list; } sqlgeo_reader::sqlgeo_reader(const char* data, std::size_t size) : data_(data), size_(size), pos_(0) { } inline uint32_t sqlgeo_reader::read_uint32() { std::uint32_t val; if (pos_ + 4 > size_) { return 0; } auto data = data_ + pos_; std::memcpy(&val, data, 4); pos_ += 4; return val; } inline uint16_t sqlgeo_reader::read_uint16() { std::uint16_t val; if (pos_ + 2 > size_) { return 0; } auto data = data_ + pos_; std::memcpy(&val, data, 2); pos_ += 2; return val; } inline uint8_t sqlgeo_reader::read_uint8() { std::uint8_t val; if (pos_ + 1 > size_) { return 0; } auto data = data_ + pos_; std::memcpy(&val, data, 1); pos_ += 1; return val; } inline double sqlgeo_reader::read_double() { double val; if (pos_ + 8 > size_) { return 0; } auto data = data_ + pos_; std::memcpy(&val, &data[0], 8); pos_ += 8; return val; } void sqlgeo_reader::readPointsZ(std::vector<Point> points) { if (points.empty()) { return; } for (auto& point : points) { point.Z = read_double(); } } void sqlgeo_reader::readPointsM(std::vector<Point> points) { if (points.empty()) { return; } for (auto& point : points) { point.M = read_double(); } } std::vector<Point> sqlgeo_reader::readPoints(uint32_t count, bool isGeography) { std::vector<Point> points; points.reserve(count); if (count < 1) { return std::vector<Point>(); } for (uint32_t i = 0; i < count; i++) { if (isGeography) { double y = read_double(); double x = read_double(); points.emplace_back(x, y); } else { double x = read_double(); double y = read_double(); points.emplace_back(x, y); } } return points; } std::vector<Figure> sqlgeo_reader::readFigures(uint32_t count, SerializationProperties properties) { std::vector<Figure> figures; figures.reserve(count); if (count == 0) { return figures; } if (properties.P || properties.L) { figures.emplace_back(FIGURE_STROKE, 0); } else { for (int i = 0; i < count; i++) { Figure f; f.Attribute = (FIGURE)read_uint8(); f.Offset = read_uint32(); figures.push_back(f); } } return figures; } std::vector<Shape> sqlgeo_reader::readShapes(uint32_t count, SerializationProperties properties) { std::vector<Shape> shapes; shapes.reserve(count); if (count < 1) { return shapes; } if (properties.P) { shapes.emplace_back(-1, 0, SHAPE_POINT); } else if (properties.L) { shapes.emplace_back(-1, 0, SHAPE_LINESTRING); } else { for (int i = 0; i < int(count); i++) { uint32_t parent_offset = read_uint32(); uint32_t figure_offset = read_uint32(); SHAPE type = (SHAPE)read_uint8(); shapes.emplace_back(parent_offset, figure_offset, type); } } return shapes; } std::vector<Segment> sqlgeo_reader::readSegments(uint32_t count) { std::vector<Segment> segments; if (count < 1) { return segments; } for (int i = 0; i < int(count); i++) { Segment s; s.Type = (SEGMENT)read_uint8(); segments.push_back(s); } return segments; } Geometry sqlgeo_reader::parseGeography() { return parseGeometry(true); } Geometry sqlgeo_reader::parseGeometry(bool isGeography) { Geometry g = {}; uint32_t numberOfPoints; uint32_t numberOfFigures; uint32_t numberOfShapes; uint32_t numberOfSegments; g.SRID = read_uint32(); if (isGeography == true) { if (g.SRID == -1) { return g; } else if (g.SRID < 4210 || g.SRID > 4999) { g.Properties.V = false; return g; //("Invalid SRID for geography"); } } //version g.Version = read_uint8(); if (g.Version > 2) { g.Properties.V = false; return g; //("Version %d is not supported", g.Version); } //flags uint8_t flags = 0; flags = read_uint8(); g.Properties.Z = (flags & (1 << 0)) != 0; g.Properties.M = (flags & (1 << 1)) != 0; g.Properties.V = (flags & (1 << 2)) != 0; g.Properties.P = (flags & (1 << 3)) != 0; g.Properties.L = (flags & (1 << 4)) != 0; if (g.Version == 2) { g.Properties.H = (flags & (1 << 5)) != 0; } if (g.Properties.P && g.Properties.L) { g.Properties.V = false; return g; //("geometry data is invalid"); } //points if (g.Properties.P) { numberOfPoints = 1; } else if (g.Properties.L) { numberOfPoints = 2; } else { numberOfPoints = read_uint32(); } g.Points = readPoints(numberOfPoints, isGeography); if (g.Properties.Z) { readPointsZ(g.Points); } if (g.Properties.M) { readPointsM(g.Points); } //figures if (g.Properties.P || g.Properties.L) { numberOfFigures = 1; } else { numberOfFigures = read_uint32(); } g.Figures = readFigures(numberOfFigures, g.Properties); //shapes if (g.Properties.P || g.Properties.L) { numberOfShapes = 1; } else { numberOfShapes = read_uint32(); } g.Shapes = readShapes(numberOfShapes, g.Properties); //segments if (g.Version == 2) { numberOfSegments = read_uint32(); g.Segments = readSegments(numberOfSegments); } return g; } }<|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // 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 "product.h" void test_product_large() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( product(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_2( product(MatrixXd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_3( product(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_4( product(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2), internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2))) ); CALL_SUBTEST_5( product(Matrix<float,Dynamic,Dynamic,RowMajor>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); } #if defined EIGEN_TEST_PART_6 { // test a specific issue in DiagonalProduct int N = 1000000; VectorXf v = VectorXf::Ones(N); MatrixXf m = MatrixXf::Ones(N,3); m = (v+v).asDiagonal() * m; VERIFY_IS_APPROX(m, MatrixXf::Constant(N,3,2)); } { // test deferred resizing in Matrix::operator= MatrixXf a = MatrixXf::Random(10,4), b = MatrixXf::Random(4,10), c = a; VERIFY_IS_APPROX((a = a * b), (c * b).eval()); } { // check the functions to setup blocking sizes compile and do not segfault // FIXME check they do what they are supposed to do !! std::ptrdiff_t l1 = internal::random<int>(10000,20000); std::ptrdiff_t l2 = internal::random<int>(1000000,2000000); setCpuCacheSizes(l1,l2); VERIFY(l1==l1CacheSize()); VERIFY(l2==l2CacheSize()); std::ptrdiff_t k1 = internal::random<int>(10,100)*16; std::ptrdiff_t m1 = internal::random<int>(10,100)*16; std::ptrdiff_t n1 = internal::random<int>(10,100)*16; // only makes sure it compiles fine internal::computeProductBlockingSizes<float,float>(k1,m1,n1); } { // test regression in row-vector by matrix (bad Map type) MatrixXf mat1(10,32); mat1.setRandom(); MatrixXf mat2(32,32); mat2.setRandom(); MatrixXf r1 = mat1.row(2)*mat2.transpose(); VERIFY_IS_APPROX(r1, (mat1.row(2)*mat2.transpose()).eval()); MatrixXf r2 = mat1.row(2)*mat2; VERIFY_IS_APPROX(r2, (mat1.row(2)*mat2).eval()); } #endif } <commit_msg>Regression test for bug 714. Note that the bug only occurs on some compilers and is not fixed yet<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // 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 "product.h" void test_product_large() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( product(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_2( product(MatrixXd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_3( product(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); CALL_SUBTEST_4( product(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2), internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2))) ); CALL_SUBTEST_5( product(Matrix<float,Dynamic,Dynamic,RowMajor>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); } #if defined EIGEN_TEST_PART_6 { // test a specific issue in DiagonalProduct int N = 1000000; VectorXf v = VectorXf::Ones(N); MatrixXf m = MatrixXf::Ones(N,3); m = (v+v).asDiagonal() * m; VERIFY_IS_APPROX(m, MatrixXf::Constant(N,3,2)); } { // test deferred resizing in Matrix::operator= MatrixXf a = MatrixXf::Random(10,4), b = MatrixXf::Random(4,10), c = a; VERIFY_IS_APPROX((a = a * b), (c * b).eval()); } { // check the functions to setup blocking sizes compile and do not segfault // FIXME check they do what they are supposed to do !! std::ptrdiff_t l1 = internal::random<int>(10000,20000); std::ptrdiff_t l2 = internal::random<int>(1000000,2000000); setCpuCacheSizes(l1,l2); VERIFY(l1==l1CacheSize()); VERIFY(l2==l2CacheSize()); std::ptrdiff_t k1 = internal::random<int>(10,100)*16; std::ptrdiff_t m1 = internal::random<int>(10,100)*16; std::ptrdiff_t n1 = internal::random<int>(10,100)*16; // only makes sure it compiles fine internal::computeProductBlockingSizes<float,float>(k1,m1,n1); } { // test regression in row-vector by matrix (bad Map type) MatrixXf mat1(10,32); mat1.setRandom(); MatrixXf mat2(32,32); mat2.setRandom(); MatrixXf r1 = mat1.row(2)*mat2.transpose(); VERIFY_IS_APPROX(r1, (mat1.row(2)*mat2.transpose()).eval()); MatrixXf r2 = mat1.row(2)*mat2; VERIFY_IS_APPROX(r2, (mat1.row(2)*mat2).eval()); } #endif // Regression test for bug 714: #ifdef EIGEN_HAS_OPENMP std::cout << "Testing omp_set_dynamic(1)\n"; omp_set_dynamic(1); for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_6( product(Matrix<float,Dynamic,Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) ); } #endif } <|endoftext|>
<commit_before>/* * This file is part of TelepathyQt4 * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2010 Nokia Corporation * * 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 */ #include <TelepathyQt4/ChannelClassSpec> #include "TelepathyQt4/debug-internal.h" namespace Tp { struct TELEPATHY_QT4_NO_EXPORT ChannelClassSpec::Private : public QSharedData { Private(const QVariantMap &props = QVariantMap()) : props(props) {} QVariantMap props; }; ChannelClassSpec::ChannelClassSpec() { } ChannelClassSpec::ChannelClassSpec(const ChannelClass &cc) : mPriv(new Private) { foreach (QString key, cc.keys()) { setProperty(key, cc.value(key).variant()); } } ChannelClassSpec::ChannelClassSpec(const QString &channelType, uint targetHandleType, const QVariantMap &otherProperties) : mPriv(new Private(otherProperties)) { setChannelType(channelType); setTargetHandleType(targetHandleType); } ChannelClassSpec::ChannelClassSpec(const QString &channelType, uint targetHandleType, bool requested, const QVariantMap &otherProperties) : mPriv(new Private(otherProperties)) { setChannelType(channelType); setTargetHandleType(targetHandleType); setRequested(requested); } ChannelClassSpec::ChannelClassSpec(const ChannelClassSpec &other, const QVariantMap &additionalProperties) : mPriv(other.mPriv) { foreach (QString key, additionalProperties.keys()) { setProperty(key, additionalProperties.value(key)); } } ChannelClassSpec::~ChannelClassSpec() { } bool ChannelClassSpec::isValid() const { return mPriv.constData() != 0 && !(qdbus_cast<QString>( mPriv->props.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"))) .isEmpty()) && mPriv->props.contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")); } ChannelClassSpec &ChannelClassSpec::operator=(const ChannelClassSpec &other) { if (this == &other) { return *this; } this->mPriv = other.mPriv; return *this; } bool ChannelClassSpec::isSubsetOf(const ChannelClassSpec &other) const { if (!isValid() || !other.isValid()) { warning() << "ChannelClassSpec comparison attempted for an invalid ChannelClassSpec"; return false; } foreach (QString propName, mPriv->props.keys()) { if (!other.hasProperty(propName)) { return false; } else if (property(propName) != other.property(propName)) { return false; } } // other had all of the properties we have and they all had the same values return true; } bool ChannelClassSpec::matches(const QVariantMap &immutableProperties) const { // We construct a ChannelClassSpec for comparison so the StreamedMedia props are normalized // consistently etc ChannelClassSpec other; foreach (QString propName, immutableProperties.keys()) { other.setProperty(propName, immutableProperties.value(propName)); } return this->isSubsetOf(other); } bool ChannelClassSpec::hasProperty(const QString &qualifiedName) const { return mPriv.constData() != 0 ? mPriv->props.contains(qualifiedName) : false; } QVariant ChannelClassSpec::property(const QString &qualifiedName) const { return mPriv.constData() != 0 ? mPriv->props.value(qualifiedName) : QVariant(); } void ChannelClassSpec::setProperty(const QString &qualifiedName, const QVariant &value) { if (mPriv.constData() == 0) { mPriv = new Private; } // Flatten the InitialAudio/Video properties from the different media interfaces to one // namespace - we convert back to the correct interface when this is converted back to a // ChannelClass for use in e.g. client channel filters QString propName = qualifiedName; if (propName == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT.InitialAudio")) { propName.replace(QLatin1String("Call.DRAFT"), QLatin1String("StreamedMedia")); } else if (propName == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT.InitialVideo")) { propName.replace(QLatin1String("Call.DRAFT"), QLatin1String("StreamedMedia")); } // TODO add the corresponding non-draft Call properties when the interface is undrafted mPriv->props.insert(propName, value); } void ChannelClassSpec::unsetProperty(const QString &qualifiedName) { if (mPriv.constData() == 0) { // No properties set for sure, so don't have to unset any return; } QString propName = qualifiedName; if (propName == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT.InitialAudio")) { propName.replace(QLatin1String("Call.DRAFT"), QLatin1String("StreamedMedia")); } else if (propName == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT.InitialVideo")) { propName.replace(QLatin1String("Call.DRAFT"), QLatin1String("StreamedMedia")); } // TODO add the corresponding non-draft Call properties when the interface is undrafted mPriv->props.remove(propName); } QVariantMap ChannelClassSpec::allProperties() const { return mPriv.constData() != 0 ? mPriv->props : QVariantMap(); } ChannelClass ChannelClassSpec::bareClass() const { ChannelClass cc; if (!isValid()) { warning() << "Tried to convert an invalid ChannelClassSpec to a ChannelClass"; return ChannelClass(); } QVariantMap props = mPriv->props; foreach (QString propName, props.keys()) { QVariant value = props.value(propName); if (channelType() == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT")) { if (propName.endsWith(QLatin1String(".InitialAudio")) || propName.endsWith(QLatin1String(".InitialVideo"))) { propName.replace(QLatin1String("StreamedMedia"), QLatin1String("Call.DRAFT")); } } // TODO add the corresponding non-draft Call properties when the interface is undrafted cc.insert(propName, QDBusVariant(value)); } return cc; } ChannelClassSpec ChannelClassSpec::textChat(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT), static_cast<uint>(HandleTypeContact)); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::textChatroom(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT), static_cast<uint>(HandleTypeRoom)); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::mediaCall(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA), static_cast<uint>(HandleTypeContact)); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::mediaCallWithInitialAudio(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA), static_cast<uint>(HandleTypeContact)); spec.setInitialAudio(); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::mediaCallWithInitialVideo(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA), static_cast<uint>(HandleTypeContact)); spec.setInitialVideo(); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::roomList(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_ROOM_LIST), static_cast<uint>(HandleTypeNone)); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::outgoingFileTransfer(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER), static_cast<uint>(HandleTypeContact)); spec.setRequested(true); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::incomingFileTransfer(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER), static_cast<uint>(HandleTypeContact)); spec.setRequested(false); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } } // Tp <commit_msg>Use setProperty for otherProperties too in ChannelClassSpec ctors<commit_after>/* * This file is part of TelepathyQt4 * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2010 Nokia Corporation * * 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 */ #include <TelepathyQt4/ChannelClassSpec> #include "TelepathyQt4/debug-internal.h" namespace Tp { struct TELEPATHY_QT4_NO_EXPORT ChannelClassSpec::Private : public QSharedData { QVariantMap props; }; ChannelClassSpec::ChannelClassSpec() { } ChannelClassSpec::ChannelClassSpec(const ChannelClass &cc) : mPriv(new Private) { foreach (QString key, cc.keys()) { setProperty(key, cc.value(key).variant()); } } ChannelClassSpec::ChannelClassSpec(const QString &channelType, uint targetHandleType, const QVariantMap &otherProperties) : mPriv(new Private) { setChannelType(channelType); setTargetHandleType(targetHandleType); foreach (QString key, otherProperties.keys()) { setProperty(key, otherProperties.value(key)); } } ChannelClassSpec::ChannelClassSpec(const QString &channelType, uint targetHandleType, bool requested, const QVariantMap &otherProperties) : mPriv(new Private) { setChannelType(channelType); setTargetHandleType(targetHandleType); setRequested(requested); foreach (QString key, otherProperties.keys()) { setProperty(key, otherProperties.value(key)); } } ChannelClassSpec::ChannelClassSpec(const ChannelClassSpec &other, const QVariantMap &additionalProperties) : mPriv(other.mPriv) { foreach (QString key, additionalProperties.keys()) { setProperty(key, additionalProperties.value(key)); } } ChannelClassSpec::~ChannelClassSpec() { } bool ChannelClassSpec::isValid() const { return mPriv.constData() != 0 && !(qdbus_cast<QString>( mPriv->props.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"))) .isEmpty()) && mPriv->props.contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")); } ChannelClassSpec &ChannelClassSpec::operator=(const ChannelClassSpec &other) { if (this == &other) { return *this; } this->mPriv = other.mPriv; return *this; } bool ChannelClassSpec::isSubsetOf(const ChannelClassSpec &other) const { if (!isValid() || !other.isValid()) { warning() << "ChannelClassSpec comparison attempted for an invalid ChannelClassSpec"; return false; } foreach (QString propName, mPriv->props.keys()) { if (!other.hasProperty(propName)) { return false; } else if (property(propName) != other.property(propName)) { return false; } } // other had all of the properties we have and they all had the same values return true; } bool ChannelClassSpec::matches(const QVariantMap &immutableProperties) const { // We construct a ChannelClassSpec for comparison so the StreamedMedia props are normalized // consistently etc ChannelClassSpec other; foreach (QString propName, immutableProperties.keys()) { other.setProperty(propName, immutableProperties.value(propName)); } return this->isSubsetOf(other); } bool ChannelClassSpec::hasProperty(const QString &qualifiedName) const { return mPriv.constData() != 0 ? mPriv->props.contains(qualifiedName) : false; } QVariant ChannelClassSpec::property(const QString &qualifiedName) const { return mPriv.constData() != 0 ? mPriv->props.value(qualifiedName) : QVariant(); } void ChannelClassSpec::setProperty(const QString &qualifiedName, const QVariant &value) { if (mPriv.constData() == 0) { mPriv = new Private; } // Flatten the InitialAudio/Video properties from the different media interfaces to one // namespace - we convert back to the correct interface when this is converted back to a // ChannelClass for use in e.g. client channel filters QString propName = qualifiedName; if (propName == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT.InitialAudio")) { propName.replace(QLatin1String("Call.DRAFT"), QLatin1String("StreamedMedia")); } else if (propName == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT.InitialVideo")) { propName.replace(QLatin1String("Call.DRAFT"), QLatin1String("StreamedMedia")); } // TODO add the corresponding non-draft Call properties when the interface is undrafted mPriv->props.insert(propName, value); } void ChannelClassSpec::unsetProperty(const QString &qualifiedName) { if (mPriv.constData() == 0) { // No properties set for sure, so don't have to unset any return; } QString propName = qualifiedName; if (propName == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT.InitialAudio")) { propName.replace(QLatin1String("Call.DRAFT"), QLatin1String("StreamedMedia")); } else if (propName == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT.InitialVideo")) { propName.replace(QLatin1String("Call.DRAFT"), QLatin1String("StreamedMedia")); } // TODO add the corresponding non-draft Call properties when the interface is undrafted mPriv->props.remove(propName); } QVariantMap ChannelClassSpec::allProperties() const { return mPriv.constData() != 0 ? mPriv->props : QVariantMap(); } ChannelClass ChannelClassSpec::bareClass() const { ChannelClass cc; if (!isValid()) { warning() << "Tried to convert an invalid ChannelClassSpec to a ChannelClass"; return ChannelClass(); } QVariantMap props = mPriv->props; foreach (QString propName, props.keys()) { QVariant value = props.value(propName); if (channelType() == QLatin1String("org.freedesktop.Telepathy.Channel.Type.Call.DRAFT")) { if (propName.endsWith(QLatin1String(".InitialAudio")) || propName.endsWith(QLatin1String(".InitialVideo"))) { propName.replace(QLatin1String("StreamedMedia"), QLatin1String("Call.DRAFT")); } } // TODO add the corresponding non-draft Call properties when the interface is undrafted cc.insert(propName, QDBusVariant(value)); } return cc; } ChannelClassSpec ChannelClassSpec::textChat(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT), static_cast<uint>(HandleTypeContact)); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::textChatroom(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT), static_cast<uint>(HandleTypeRoom)); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::mediaCall(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA), static_cast<uint>(HandleTypeContact)); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::mediaCallWithInitialAudio(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA), static_cast<uint>(HandleTypeContact)); spec.setInitialAudio(); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::mediaCallWithInitialVideo(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA), static_cast<uint>(HandleTypeContact)); spec.setInitialVideo(); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::roomList(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_ROOM_LIST), static_cast<uint>(HandleTypeNone)); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::outgoingFileTransfer(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER), static_cast<uint>(HandleTypeContact)); spec.setRequested(true); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } ChannelClassSpec ChannelClassSpec::incomingFileTransfer(const QVariantMap &additionalProperties) { static ChannelClassSpec spec; if (!spec.isValid()) { spec = ChannelClassSpec(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER), static_cast<uint>(HandleTypeContact)); spec.setRequested(false); } if (additionalProperties.isEmpty()) { return spec; } else { return ChannelClassSpec(spec, additionalProperties); } } } // Tp <|endoftext|>
<commit_before>/* Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2017, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ #ifndef NUPIC_UTIL_SLIDING_WINDOW_HPP #define NUPIC_UTIL_SLIDING_WINDOW_HPP #include <vector> #include <algorithm> #include <nupic/types/Types.hpp> #include <nupic/utils/Log.hpp> namespace nupic { namespace util { template<class T> class SlidingWindow { public: SlidingWindow(UInt maxCapacity); SlidingWindow(UInt maxCapacity, std::vector<T> initialData); const UInt maxCapacity; size_t size() const; /** append new value to the end of the buffer and handle the "overflows"-may pop the first element if full. */ void append(T newValue); /** like append, but return the dropped value. isValid indicates if the return value is valid (not while size()< maxCapacity) :param T newValue - new value to append to the sliding window :param bool isValid - a return pass-by-value that indicates validity of the return T value. for first maxCapacity items it is false, later always true. :return T dropped value (past oldest element) if isValid; if not valid, this field holds the oldest value (but still contained in the window!) */ T append(T newValue, bool& isValid); /** * :return unordered content (data ) of this sl. window; call getLinearizedData() if you need them oredered from oldest->newest * This direct access method is fast. */ const std::vector<T>& getData() const; /** linearize method for the internal buffer; this is slower than the pure getData() but ensures that the data are ordered (oldest at the * beginning, newest at the end of the vector * This handles case of |5,6;1,2,3,4| => |1,2,3,4,5,6| * :return new linearized vector */ std::vector<T> getLinearizedData() const; bool operator==(const SlidingWindow& r2) const; bool operator!=(const SlidingWindow& r2) const; T& operator[](UInt index); const T& operator[](UInt index) const; private: std::vector<T> buffer_; UInt idxNext_; size_t size_; }; }} //end ns /// IMPLEMENTATION #include <cmath> using nupic::util::SlidingWindow; template<class T> SlidingWindow<T>::SlidingWindow(nupic::UInt maxCapacity) : maxCapacity(maxCapacity) { NTA_CHECK(maxCapacity > 0); buffer_.reserve(maxCapacity); buffer_.resize(maxCapacity); idxNext_ = 0; size_ = 0; } template<class T> SlidingWindow<T>::SlidingWindow(nupic::UInt maxCapacity, std::vector<T> initialData) : SlidingWindow(maxCapacity) { auto sz = std::min(initialData.size(), (size_t)maxCapacity); buffer_.insert(std::begin(buffer_), std::end(initialData) - sz, std::end(initialData)); buffer_.resize(sz); idxNext_ = sz % maxCapacity; size_ = sz; } template<class T> size_t SlidingWindow<T>::size() const { NTA_ASSERT(buffer_.size() <= maxCapacity); return std::min(size_, (size_t)maxCapacity); } template<class T> void SlidingWindow<T>::append(T newValue) { buffer_[idxNext_] = newValue; idxNext_ = ++idxNext_ %maxCapacity;//the assignment must be out of the [] above -not [idxNext_++%maxCap]- because we want to store the value %maxCap, not only ++ ++size_; } template<class T> T SlidingWindow<T>::append(T newValue, bool& isValid) { T old = buffer_.empty() ? newValue : buffer_[idxNext_]; //handle case of empty buffer (access buff[0]), otherwise return oldest elem isValid = (buffer_.size()==maxCapacity); //only in this case we drop oldest; this happens always after first maxCap steps ; must be checked before append() append(newValue); return old; } template<class T> const std::vector<T>& SlidingWindow<T>::getData() const { return buffer_; //may contain trailing "zeros" } template<class T> std::vector<T> SlidingWindow<T>::getLinearizedData() const { std::vector<T> lin; lin.reserve(buffer_.size()); lin.insert(std::begin(lin), std::begin(buffer_) + idxNext_, std::end(buffer_)); //insert the "older" part at the beginning lin.insert(std::end(lin), std::begin(buffer_), std::begin(buffer_) + idxNext_); //append the "newer" part to the end of the constructed vect return lin; } template<class T> bool SlidingWindow<T>::operator==(const SlidingWindow& r2) const //FIXME review the ==, on my machine it randomly passes/fails the test! { return ((this->size() == r2.size()) && (this->maxCapacity == r2.maxCapacity) && (this->getData()== r2.getData()) ); } template<class T> bool SlidingWindow<T>::operator!=(const SlidingWindow& r2) const { return !operator==(r2); } template<class T> T& SlidingWindow<T>::operator[](nupic::UInt index) { NTA_ASSERT(index <= size()); return &buffer_[index]; } template<class T> const T& SlidingWindow<T>::operator[](nupic::UInt index) const { return this->operator[](index); //call the overloaded operator[] above } #endif //header <commit_msg>SlidingWindow: code fits 80-len lines<commit_after>/* Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2017, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ #ifndef NUPIC_UTIL_SLIDING_WINDOW_HPP #define NUPIC_UTIL_SLIDING_WINDOW_HPP #include <vector> #include <algorithm> #include <nupic/types/Types.hpp> #include <nupic/utils/Log.hpp> namespace nupic { namespace util { template<class T> class SlidingWindow { public: SlidingWindow(UInt maxCapacity); SlidingWindow(UInt maxCapacity, std::vector<T> initialData); const UInt maxCapacity; size_t size() const; /** append new value to the end of the buffer and handle the "overflows"-may pop the first element if full. */ void append(T newValue); /** like append, but return the dropped value. isValid indicates if the return value is valid (not while size()< maxCapacity) :param T newValue - new value to append to the sliding window :param bool isValid - a return pass-by-value that indicates validity of the return T value. for first maxCapacity items it is false, later always true. :return T dropped value (past oldest element) if isValid; if not valid, this field holds the oldest value (but still contained in the window!) */ T append(T newValue, bool& isValid); /** * :return unordered content (data ) of this sl. window; call getLinearizedData() if you need them oredered from oldest->newest * This direct access method is fast. */ const std::vector<T>& getData() const; /** linearize method for the internal buffer; this is slower than the pure getData() but ensures that the data are ordered (oldest at the beginning, newest at the end of the vector * This handles case of |5,6;1,2,3,4| => |1,2,3,4,5,6| * :return new linearized vector */ std::vector<T> getLinearizedData() const; bool operator==(const SlidingWindow& r2) const; bool operator!=(const SlidingWindow& r2) const; T& operator[](UInt index); const T& operator[](UInt index) const; private: std::vector<T> buffer_; UInt idxNext_; size_t size_; }; }} //end ns /// IMPLEMENTATION #include <cmath> using nupic::util::SlidingWindow; template<class T> SlidingWindow<T>::SlidingWindow(nupic::UInt maxCapacity) : maxCapacity(maxCapacity) { NTA_CHECK(maxCapacity > 0); buffer_.reserve(maxCapacity); buffer_.resize(maxCapacity); idxNext_ = 0; size_ = 0; } template<class T> SlidingWindow<T>::SlidingWindow(nupic::UInt maxCapacity, std::vector<T> initialData) : SlidingWindow(maxCapacity) { auto sz = std::min(initialData.size(), (size_t)maxCapacity); buffer_.insert(std::begin(buffer_), std::end(initialData) - sz, std::end(initialData)); buffer_.resize(sz); idxNext_ = sz % maxCapacity; size_ = sz; } template<class T> size_t SlidingWindow<T>::size() const { NTA_ASSERT(buffer_.size() <= maxCapacity); return std::min(size_, (size_t)maxCapacity); } template<class T> void SlidingWindow<T>::append(T newValue) { buffer_[idxNext_] = newValue; //the assignment must be out of the [] above, so not [idxNext_++%maxCap], // because we want to store the value %maxCap, not only ++ idxNext_ = ++idxNext_ %maxCapacity; ++size_; } template<class T> T SlidingWindow<T>::append(T newValue, bool& isValid) { //handle case of empty buffer (access buff[0]), otherwise return oldest elem T old = buffer_.empty() ? newValue : buffer_[idxNext_]; //only in this case we drop oldest; this happens always after //first maxCap steps ; must be checked before append() isValid = (buffer_.size()==maxCapacity); append(newValue); return old; } template<class T> const std::vector<T>& SlidingWindow<T>::getData() const { return buffer_; //may contain trailing "zeros" } template<class T> std::vector<T> SlidingWindow<T>::getLinearizedData() const { std::vector<T> lin; lin.reserve(buffer_.size()); //insert the "older" part at the beginning lin.insert(std::begin(lin), std::begin(buffer_) + idxNext_, std::end(buffer_)); //append the "newer" part to the end of the constructed vect lin.insert(std::end(lin), std::begin(buffer_), std::begin(buffer_) + idxNext_); return lin; } template<class T> bool SlidingWindow<T>::operator==(const SlidingWindow& r2) const { return ((this->size() == r2.size()) && (this->maxCapacity == r2.maxCapacity) && (this->getData()== r2.getData()) ); //FIXME review the ==, on my machine it randomly passes/fails the test! } template<class T> bool SlidingWindow<T>::operator!=(const SlidingWindow& r2) const { return !operator==(r2); } template<class T> T& SlidingWindow<T>::operator[](nupic::UInt index) { NTA_ASSERT(index <= size()); return &buffer_[index]; } template<class T> const T& SlidingWindow<T>::operator[](nupic::UInt index) const { return this->operator[](index); //call the overloaded operator[] above } #endif //header <|endoftext|>
<commit_before> #include "CGUIManager.h" #include <glad/glad.h> namespace ion { // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // If text or lines are blurry when integrating ImGui in your engine: // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) void CGUIManager::DrawCallback(ImDrawData* draw_data) { Window->MakeContextCurrent(); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled GLint last_program, last_texture; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); // Setup orthographic projection matrix const float width = ImGui::GetIO().DisplaySize.x; const float height = ImGui::GetIO().DisplaySize.y; const float ortho_projection[4][4] = { { 2.0f / width, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f / -height, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, { -1.0f, 1.0f, 0.0f, 1.0f }, }; glUseProgram(ShaderHandle); glUniform1i(AttribLocationTex, 0); glUniformMatrix4fv(AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); glBindVertexArray(VaoHandle); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front(); glBindBuffer(GL_ARRAY_BUFFER, VboHandle); int needed_vtx_size = cmd_list->VtxBuffer.size() * sizeof(ImDrawVert); if (VboSize < needed_vtx_size) { // Grow our buffer if needed VboSize = needed_vtx_size + 2000 * sizeof(ImDrawVert); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr) VboSize, NULL, GL_STREAM_DRAW); } unsigned char* vtx_data = (unsigned char*) glMapBufferRange(GL_ARRAY_BUFFER, 0, needed_vtx_size, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); if (!vtx_data) continue; memcpy(vtx_data, &cmd_list->VtxBuffer[0], cmd_list->VtxBuffer.size() * sizeof(ImDrawVert)); glUnmapBuffer(GL_ARRAY_BUFFER); for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { glBindTexture(GL_TEXTURE_2D, (GLuint) (intptr_t) pcmd->TextureId); glScissor((int) pcmd->ClipRect.x, (int) (height - pcmd->ClipRect.w), (int) (pcmd->ClipRect.z - pcmd->ClipRect.x), (int) (pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei) pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer); } idx_buffer += pcmd->ElemCount; } } // Restore modified state glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glUseProgram(last_program); glDisable(GL_SCISSOR_TEST); glEnable(GL_DEPTH_TEST); glBindTexture(GL_TEXTURE_2D, last_texture); } void CGUIManager::OnEvent(IEvent & Event) { ImGuiIO& io = ImGui::GetIO(); if (InstanceOf<SKeyboardEvent>(Event)) { SKeyboardEvent KeyboardEvent = As<SKeyboardEvent>(Event); io.KeysDown[(int) KeyboardEvent.Key] = KeyboardEvent.Pressed; io.KeyCtrl = Window->IsKeyDown(EKey::LeftControl) || Window->IsKeyDown(EKey::RightControl); io.KeyShift = Window->IsKeyDown(EKey::LeftShift) || Window->IsKeyDown(EKey::RightShift); io.KeyAlt = Window->IsKeyDown(EKey::LeftAlt) || Window->IsKeyDown(EKey::RightAlt); } else if (InstanceOf<SMouseEvent>(Event)) { SMouseEvent MouseEvent = As<SMouseEvent>(Event); switch (MouseEvent.Type) { case SMouseEvent::EType::Click: MousePressed[(int) MouseEvent.Button] = MouseEvent.Pressed; break; case SMouseEvent::EType::Move: break; case SMouseEvent::EType::Scroll: MouseWheel += MouseEvent.Movement.Y; break; } } else if (InstanceOf<SCharacterEvent>(Event)) { SCharacterEvent CharacterEvent = As<SCharacterEvent>(Event); if (CharacterEvent.C > 0) io.AddInputCharacter(CharacterEvent.C); } } void CGUIManager::CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader. glGenTextures(1, &FontTexture); glBindTexture(GL_TEXTURE_2D, FontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *) (intptr_t) FontTexture; } void CGUIManager::AddFontFromFile(string const & FileName, float const Size) { ImGuiIO& io = ImGui::GetIO(); ImFont* my_font = io.Fonts->AddFontFromFileTTF(FileName.c_str(), Size); } bool CGUIManager::CreateDeviceObjects() { Window->MakeContextCurrent(); const GLchar *vertex_shader = "#version 330\n" "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* fragment_shader = "#version 330\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" "}\n"; ShaderHandle = glCreateProgram(); VertHandle = glCreateShader(GL_VERTEX_SHADER); FragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(VertHandle, 1, &vertex_shader, 0); glShaderSource(FragHandle, 1, &fragment_shader, 0); glCompileShader(VertHandle); glCompileShader(FragHandle); glAttachShader(ShaderHandle, VertHandle); glAttachShader(ShaderHandle, FragHandle); glLinkProgram(ShaderHandle); AttribLocationTex = glGetUniformLocation(ShaderHandle, "Texture"); AttribLocationProjMtx = glGetUniformLocation(ShaderHandle, "ProjMtx"); AttribLocationPosition = glGetAttribLocation(ShaderHandle, "Position"); AttribLocationUV = glGetAttribLocation(ShaderHandle, "UV"); AttribLocationColor = glGetAttribLocation(ShaderHandle, "Color"); glGenBuffers(1, &VboHandle); glGenVertexArrays(1, &VaoHandle); glBindVertexArray(VaoHandle); glBindBuffer(GL_ARRAY_BUFFER, VboHandle); glEnableVertexAttribArray(AttribLocationPosition); glEnableVertexAttribArray(AttribLocationUV); glEnableVertexAttribArray(AttribLocationColor); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*) OFFSETOF(ImDrawVert, col)); #undef OFFSETOF glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); CreateFontsTexture(); return true; } void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data) { SingletonPointer<CGUIManager> ImGUIManager; ImGUIManager->DrawCallback(draw_data); } char const * ImGui_ImplGlfwGL3_GetClipboardText() { SingletonPointer<CGUIManager> ImGUIManager; return ImGUIManager->Window->GetClipboardText().c_str(); } void ImGui_ImplGlfwGL3_SetClipboardText(const char* text) { SingletonPointer<CGUIManager> ImGUIManager; ImGUIManager->Window->SetClipboardText(text); } bool CGUIManager::Init(CWindow* window) { Window = window; ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = (int) EKey::Tab; io.KeyMap[ImGuiKey_LeftArrow] = (int) EKey::Left; io.KeyMap[ImGuiKey_RightArrow] = (int) EKey::Right; io.KeyMap[ImGuiKey_UpArrow] = (int) EKey::Up; io.KeyMap[ImGuiKey_DownArrow] = (int) EKey::Down; io.KeyMap[ImGuiKey_Home] = (int) EKey::Home; io.KeyMap[ImGuiKey_End] = (int) EKey::End; io.KeyMap[ImGuiKey_Delete] = (int) EKey::Delete; io.KeyMap[ImGuiKey_Backspace] = (int) EKey::Backspace; io.KeyMap[ImGuiKey_Enter] = (int) EKey::Return; io.KeyMap[ImGuiKey_Escape] = (int) EKey::Escape; io.KeyMap[ImGuiKey_A] = (int) EKey::A; io.KeyMap[ImGuiKey_C] = (int) EKey::C; io.KeyMap[ImGuiKey_V] = (int) EKey::V; io.KeyMap[ImGuiKey_X] = (int) EKey::X; io.KeyMap[ImGuiKey_Y] = (int) EKey::Y; io.KeyMap[ImGuiKey_Z] = (int) EKey::Z; io.RenderDrawListsFn = ImGui_ImplGlfwGL3_RenderDrawLists; io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText; io.IniFilename = nullptr; return true; } void CGUIManager::Shutdown() { Window->MakeContextCurrent(); if (VaoHandle) glDeleteVertexArrays(1, &VaoHandle); if (VboHandle) glDeleteBuffers(1, &VboHandle); VaoHandle = 0; VboHandle = 0; glDetachShader(ShaderHandle, VertHandle); glDeleteShader(VertHandle); VertHandle = 0; glDetachShader(ShaderHandle, FragHandle); glDeleteShader(FragHandle); FragHandle = 0; glDeleteProgram(ShaderHandle); ShaderHandle = 0; if (FontTexture) { glDeleteTextures(1, &FontTexture); ImGui::GetIO().Fonts->TexID = 0; FontTexture = 0; } ImGui::Shutdown(); } void CGUIManager::NewFrame() { static int frame = 0; SingletonPointer<CTimeManager> TimeManager; if (! FontTexture) CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) io.DisplaySize = ImVec2((float) Window->GetSize().X, (float) Window->GetSize().Y); // Setup time step double current_time = TimeManager->GetRunTime(); io.DeltaTime = Time > 0.0 ? (float) (current_time - Time) : (float) (1.0f / 60.0f); Time = current_time; // Setup inputs // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents()) if (Window->IsFocused()) { double mouse_x, mouse_y; mouse_x = Window->GetCursorLocation().X; mouse_y = Window->GetCursorLocation().Y; io.MousePos = ImVec2((float) mouse_x, (float) mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) } else { io.MousePos = ImVec2(-1, -1); } for (int i = 0; i < 3; i++) { io.MouseDown[i] = MousePressed[i] || Window->IsMouseDown((SMouseEvent::EButton) i); // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. MousePressed[i] = false; } io.MouseWheel = MouseWheel; MouseWheel = 0; // Start the frame ImGui::NewFrame(); } CGUIManager::CGUIManager() { for (int i = 0; i < 3; ++ i) MousePressed[i] = false; } } <commit_msg>[ionGui] GUIManager blocks click events if mouse is over GUI<commit_after> #include "CGUIManager.h" #include <glad/glad.h> namespace ion { // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // If text or lines are blurry when integrating ImGui in your engine: // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) void CGUIManager::DrawCallback(ImDrawData* draw_data) { Window->MakeContextCurrent(); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled GLint last_program, last_texture; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); // Setup orthographic projection matrix const float width = ImGui::GetIO().DisplaySize.x; const float height = ImGui::GetIO().DisplaySize.y; const float ortho_projection[4][4] = { { 2.0f / width, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f / -height, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, { -1.0f, 1.0f, 0.0f, 1.0f }, }; glUseProgram(ShaderHandle); glUniform1i(AttribLocationTex, 0); glUniformMatrix4fv(AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); glBindVertexArray(VaoHandle); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front(); glBindBuffer(GL_ARRAY_BUFFER, VboHandle); int needed_vtx_size = cmd_list->VtxBuffer.size() * sizeof(ImDrawVert); if (VboSize < needed_vtx_size) { // Grow our buffer if needed VboSize = needed_vtx_size + 2000 * sizeof(ImDrawVert); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr) VboSize, NULL, GL_STREAM_DRAW); } unsigned char* vtx_data = (unsigned char*) glMapBufferRange(GL_ARRAY_BUFFER, 0, needed_vtx_size, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); if (!vtx_data) continue; memcpy(vtx_data, &cmd_list->VtxBuffer[0], cmd_list->VtxBuffer.size() * sizeof(ImDrawVert)); glUnmapBuffer(GL_ARRAY_BUFFER); for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { glBindTexture(GL_TEXTURE_2D, (GLuint) (intptr_t) pcmd->TextureId); glScissor((int) pcmd->ClipRect.x, (int) (height - pcmd->ClipRect.w), (int) (pcmd->ClipRect.z - pcmd->ClipRect.x), (int) (pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei) pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer); } idx_buffer += pcmd->ElemCount; } } // Restore modified state glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glUseProgram(last_program); glDisable(GL_SCISSOR_TEST); glEnable(GL_DEPTH_TEST); glBindTexture(GL_TEXTURE_2D, last_texture); } void CGUIManager::OnEvent(IEvent & Event) { ImGuiIO& io = ImGui::GetIO(); if (InstanceOf<SKeyboardEvent>(Event)) { SKeyboardEvent KeyboardEvent = As<SKeyboardEvent>(Event); io.KeysDown[(int) KeyboardEvent.Key] = KeyboardEvent.Pressed; io.KeyCtrl = Window->IsKeyDown(EKey::LeftControl) || Window->IsKeyDown(EKey::RightControl); io.KeyShift = Window->IsKeyDown(EKey::LeftShift) || Window->IsKeyDown(EKey::RightShift); io.KeyAlt = Window->IsKeyDown(EKey::LeftAlt) || Window->IsKeyDown(EKey::RightAlt); } else if (InstanceOf<SMouseEvent>(Event)) { SMouseEvent MouseEvent = As<SMouseEvent>(Event); switch (MouseEvent.Type) { case SMouseEvent::EType::Click: if (ImGui::IsMouseHoveringAnyWindow()) { Event.Block(); } MousePressed[(int) MouseEvent.Button] = MouseEvent.Pressed; break; case SMouseEvent::EType::Move: break; case SMouseEvent::EType::Scroll: MouseWheel += MouseEvent.Movement.Y; break; } } else if (InstanceOf<SCharacterEvent>(Event)) { SCharacterEvent CharacterEvent = As<SCharacterEvent>(Event); if (CharacterEvent.C > 0) io.AddInputCharacter(CharacterEvent.C); } } void CGUIManager::CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader. glGenTextures(1, &FontTexture); glBindTexture(GL_TEXTURE_2D, FontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *) (intptr_t) FontTexture; } void CGUIManager::AddFontFromFile(string const & FileName, float const Size) { ImGuiIO& io = ImGui::GetIO(); ImFont* my_font = io.Fonts->AddFontFromFileTTF(FileName.c_str(), Size); } bool CGUIManager::CreateDeviceObjects() { Window->MakeContextCurrent(); const GLchar *vertex_shader = "#version 330\n" "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* fragment_shader = "#version 330\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" "}\n"; ShaderHandle = glCreateProgram(); VertHandle = glCreateShader(GL_VERTEX_SHADER); FragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(VertHandle, 1, &vertex_shader, 0); glShaderSource(FragHandle, 1, &fragment_shader, 0); glCompileShader(VertHandle); glCompileShader(FragHandle); glAttachShader(ShaderHandle, VertHandle); glAttachShader(ShaderHandle, FragHandle); glLinkProgram(ShaderHandle); AttribLocationTex = glGetUniformLocation(ShaderHandle, "Texture"); AttribLocationProjMtx = glGetUniformLocation(ShaderHandle, "ProjMtx"); AttribLocationPosition = glGetAttribLocation(ShaderHandle, "Position"); AttribLocationUV = glGetAttribLocation(ShaderHandle, "UV"); AttribLocationColor = glGetAttribLocation(ShaderHandle, "Color"); glGenBuffers(1, &VboHandle); glGenVertexArrays(1, &VaoHandle); glBindVertexArray(VaoHandle); glBindBuffer(GL_ARRAY_BUFFER, VboHandle); glEnableVertexAttribArray(AttribLocationPosition); glEnableVertexAttribArray(AttribLocationUV); glEnableVertexAttribArray(AttribLocationColor); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*) OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*) OFFSETOF(ImDrawVert, col)); #undef OFFSETOF glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); CreateFontsTexture(); return true; } void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data) { SingletonPointer<CGUIManager> ImGUIManager; ImGUIManager->DrawCallback(draw_data); } char const * ImGui_ImplGlfwGL3_GetClipboardText() { SingletonPointer<CGUIManager> ImGUIManager; return ImGUIManager->Window->GetClipboardText().c_str(); } void ImGui_ImplGlfwGL3_SetClipboardText(const char* text) { SingletonPointer<CGUIManager> ImGUIManager; ImGUIManager->Window->SetClipboardText(text); } bool CGUIManager::Init(CWindow* window) { Window = window; ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = (int) EKey::Tab; io.KeyMap[ImGuiKey_LeftArrow] = (int) EKey::Left; io.KeyMap[ImGuiKey_RightArrow] = (int) EKey::Right; io.KeyMap[ImGuiKey_UpArrow] = (int) EKey::Up; io.KeyMap[ImGuiKey_DownArrow] = (int) EKey::Down; io.KeyMap[ImGuiKey_Home] = (int) EKey::Home; io.KeyMap[ImGuiKey_End] = (int) EKey::End; io.KeyMap[ImGuiKey_Delete] = (int) EKey::Delete; io.KeyMap[ImGuiKey_Backspace] = (int) EKey::Backspace; io.KeyMap[ImGuiKey_Enter] = (int) EKey::Return; io.KeyMap[ImGuiKey_Escape] = (int) EKey::Escape; io.KeyMap[ImGuiKey_A] = (int) EKey::A; io.KeyMap[ImGuiKey_C] = (int) EKey::C; io.KeyMap[ImGuiKey_V] = (int) EKey::V; io.KeyMap[ImGuiKey_X] = (int) EKey::X; io.KeyMap[ImGuiKey_Y] = (int) EKey::Y; io.KeyMap[ImGuiKey_Z] = (int) EKey::Z; io.RenderDrawListsFn = ImGui_ImplGlfwGL3_RenderDrawLists; io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText; io.IniFilename = nullptr; return true; } void CGUIManager::Shutdown() { Window->MakeContextCurrent(); if (VaoHandle) glDeleteVertexArrays(1, &VaoHandle); if (VboHandle) glDeleteBuffers(1, &VboHandle); VaoHandle = 0; VboHandle = 0; glDetachShader(ShaderHandle, VertHandle); glDeleteShader(VertHandle); VertHandle = 0; glDetachShader(ShaderHandle, FragHandle); glDeleteShader(FragHandle); FragHandle = 0; glDeleteProgram(ShaderHandle); ShaderHandle = 0; if (FontTexture) { glDeleteTextures(1, &FontTexture); ImGui::GetIO().Fonts->TexID = 0; FontTexture = 0; } ImGui::Shutdown(); } void CGUIManager::NewFrame() { static int frame = 0; SingletonPointer<CTimeManager> TimeManager; if (! FontTexture) CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) io.DisplaySize = ImVec2((float) Window->GetSize().X, (float) Window->GetSize().Y); // Setup time step double current_time = TimeManager->GetRunTime(); io.DeltaTime = Time > 0.0 ? (float) (current_time - Time) : (float) (1.0f / 60.0f); Time = current_time; // Setup inputs // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents()) if (Window->IsFocused()) { double mouse_x, mouse_y; mouse_x = Window->GetCursorLocation().X; mouse_y = Window->GetCursorLocation().Y; io.MousePos = ImVec2((float) mouse_x, (float) mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) } else { io.MousePos = ImVec2(-1, -1); } for (int i = 0; i < 3; i++) { io.MouseDown[i] = MousePressed[i] || Window->IsMouseDown((SMouseEvent::EButton) i); // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. MousePressed[i] = false; } io.MouseWheel = MouseWheel; MouseWheel = 0; // Start the frame ImGui::NewFrame(); } CGUIManager::CGUIManager() { for (int i = 0; i < 3; ++ i) MousePressed[i] = false; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <init.h> #include <net.h> #include <scheduler.h> #include <outputtype.h> #include <util/system.h> #include <util/moneystr.h> #include <validation.h> #include <walletinitinterface.h> #include <wallet/rpcwallet.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> class WalletInit : public WalletInitInterface { public: //! Was the wallet component compiled in. bool HasWalletSupport() const override {return true;} //! Return the wallets help message. void AddWalletOptions() const override; //! Wallets parameter interaction bool ParameterInteraction() const override; //! Register wallet RPCs. void RegisterRPC(CRPCTable &tableRPC) const override; //! Responsible for reading and validating the -wallet arguments and verifying the wallet database. // This function will perform salvage on the wallet if requested, as long as only one wallet is // being loaded (WalletParameterInteraction forbids -salvagewallet, -zapwallettxes or -upgradewallet with multiwallet). bool Verify() const override; //! Load wallet databases. bool Open() const override; //! Complete startup of wallets. void Start(CScheduler& scheduler) const override; //! Flush all wallets in preparation for shutdown. void Flush() const override; //! Stop all wallets. Wallets will be flushed first. void Stop() const override; //! Close all wallets. void Close() const override; }; const WalletInitInterface& g_wallet_init_interface = WalletInit(); void WalletInit::AddWalletOptions() const { gArgs.AddArg("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(DEFAULT_ADDRESS_TYPE)), false, OptionsCategory::WALLET); gArgs.AddArg("-avoidpartialspends", strprintf(_("Group outputs by address, selecting all or none, instead of selecting on a per-output basis. Privacy is improved as an address is only used once (unless someone sends to it after spending from it), but may result in slightly higher fees as suboptimal coin selection may result due to the added limitation (default: %u)"), DEFAULT_AVOIDPARTIALSPENDS), false, OptionsCategory::WALLET); gArgs.AddArg("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)", false, OptionsCategory::WALLET); gArgs.AddArg("-disablewallet", "Do not load the wallet and disable wallet RPC calls", false, OptionsCategory::WALLET); gArgs.AddArg("-discardfee=<amt>", strprintf("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). " "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target", CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-fallbackfee=<amt>", strprintf("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-keypool=<n>", strprintf("Set key pool size to <n> (default: %u)", DEFAULT_KEYPOOL_SIZE), false, OptionsCategory::WALLET); gArgs.AddArg("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-paytxfee=<amt>", strprintf("Fee (in %s/kB) to add to transactions you send (default: %s)", CURRENCY_UNIT, FormatMoney(CFeeRate{DEFAULT_PAY_TX_FEE}.GetFeePerK())), false, OptionsCategory::WALLET); gArgs.AddArg("-rescan", "Rescan the block chain for missing wallet transactions on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-salvagewallet", "Attempt to recover private keys from a corrupt wallet on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-spendzeroconfchange", strprintf("Spend unconfirmed change when sending transactions (default: %u)", DEFAULT_SPEND_ZEROCONF_CHANGE), false, OptionsCategory::WALLET); gArgs.AddArg("-txconfirmtarget=<n>", strprintf("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)", DEFAULT_TX_CONFIRM_TARGET), false, OptionsCategory::WALLET); gArgs.AddArg("-upgradewallet", "Upgrade wallet to latest format on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-wallet=<path>", "Specify wallet database path. Can be specified multiple times to load multiple wallets. Path is interpreted relative to <walletdir> if it is not absolute, and will be created if it does not exist (as a directory containing a wallet.dat file and log files). For backwards compatibility this will also accept names of existing data files in <walletdir>.)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletbroadcast", strprintf("Make the wallet broadcast transactions (default: %u)", DEFAULT_WALLETBROADCAST), false, OptionsCategory::WALLET); gArgs.AddArg("-walletdir=<dir>", "Specify directory to hold wallets (default: <datadir>/wallets if it exists, otherwise <datadir>)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletnotify=<cmd>", "Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletrbf", strprintf("Send transactions with full-RBF opt-in enabled (RPC only, default: %u)", DEFAULT_WALLET_RBF), false, OptionsCategory::WALLET); gArgs.AddArg("-zapwallettxes=<mode>", "Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup" " (1 = keep tx meta data e.g. payment request information, 2 = drop tx meta data)", false, OptionsCategory::WALLET); gArgs.AddArg("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-walletrejectlongchains", strprintf("Wallet will not create transactions that violate mempool chain limits (default: %u)", DEFAULT_WALLET_REJECT_LONG_CHAINS), true, OptionsCategory::WALLET_DEBUG_TEST); } bool WalletInit::ParameterInteraction() const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { for (const std::string& wallet : gArgs.GetArgs("-wallet")) { LogPrintf("%s: parameter interaction: -disablewallet -> ignoring -wallet=%s\n", __func__, wallet); } return true; } gArgs.SoftSetArg("-wallet", ""); const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1; if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) { LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__); } if (gArgs.GetBoolArg("-salvagewallet", false)) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet")); } // Rewrite just private keys: rescan to find transactions if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__); } } bool zapwallettxes = gArgs.GetBoolArg("-zapwallettxes", false); // -zapwallettxes implies dropping the mempool on startup if (zapwallettxes && gArgs.SoftSetBoolArg("-persistmempool", false)) { LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -persistmempool=0\n", __func__); } // -zapwallettxes implies a rescan if (zapwallettxes) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes")); } if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -rescan=1\n", __func__); } } if (is_multiwallet) { if (gArgs.GetBoolArg("-upgradewallet", false)) { return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet")); } } if (gArgs.GetBoolArg("-sysperms", false)) return InitError("-sysperms is not allowed in combination with enabled wallet functionality"); if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false)) return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.")); if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB) InitWarning(AmountHighWarn("-minrelaytxfee") + " " + _("The wallet will avoid paying less than the minimum relay fee.")); if (gArgs.IsArgSet("-maxtxfee")) { CAmount nMaxFee = 0; if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""))); if (nMaxFee > HIGH_MAX_TX_FEE) InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction.")); maxTxFee = nMaxFee; if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee) { return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"), gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString())); } } return true; } void WalletInit::RegisterRPC(CRPCTable &t) const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { return; } RegisterWalletRPCCommands(t); } bool WalletInit::Verify() const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { return true; } if (gArgs.IsArgSet("-walletdir")) { fs::path wallet_dir = gArgs.GetArg("-walletdir", ""); boost::system::error_code error; // The canonical path cleans the path, preventing >1 Berkeley environment instances for the same directory fs::path canonical_wallet_dir = fs::canonical(wallet_dir, error); if (error || !fs::exists(wallet_dir)) { return InitError(strprintf(_("Specified -walletdir \"%s\" does not exist"), wallet_dir.string())); } else if (!fs::is_directory(wallet_dir)) { return InitError(strprintf(_("Specified -walletdir \"%s\" is not a directory"), wallet_dir.string())); // The canonical path transforms relative paths into absolute ones, so we check the non-canonical version } else if (!wallet_dir.is_absolute()) { return InitError(strprintf(_("Specified -walletdir \"%s\" is a relative path"), wallet_dir.string())); } gArgs.ForceSetArg("-walletdir", canonical_wallet_dir.string()); } LogPrintf("Using wallet directory %s\n", GetWalletDir().string()); uiInterface.InitMessage(_("Verifying wallet(s)...")); std::vector<std::string> wallet_files = gArgs.GetArgs("-wallet"); // Parameter interaction code should have thrown an error if -salvagewallet // was enabled with more than wallet file, so the wallet_files size check // here should have no effect. bool salvage_wallet = gArgs.GetBoolArg("-salvagewallet", false) && wallet_files.size() <= 1; // Keep track of each wallet absolute path to detect duplicates. std::set<fs::path> wallet_paths; for (const auto& wallet_file : wallet_files) { WalletLocation location(wallet_file); if (!wallet_paths.insert(location.GetPath()).second) { return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), wallet_file)); } std::string error_string; std::string warning_string; bool verify_success = CWallet::Verify(location, salvage_wallet, error_string, warning_string); if (!error_string.empty()) InitError(error_string); if (!warning_string.empty()) InitWarning(warning_string); if (!verify_success) return false; } return true; } bool WalletInit::Open() const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { LogPrintf("Wallet disabled!\n"); return true; } for (const std::string& walletFile : gArgs.GetArgs("-wallet")) { std::shared_ptr<CWallet> pwallet = CWallet::CreateWalletFromFile(WalletLocation(walletFile)); if (!pwallet) { return false; } AddWallet(pwallet); } return true; } void WalletInit::Start(CScheduler& scheduler) const { for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) { pwallet->postInitProcess(); } // Run a thread to flush wallet periodically scheduler.scheduleEvery(MaybeCompactWalletDB, 500); } void WalletInit::Flush() const { for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) { pwallet->Flush(false); } } void WalletInit::Stop() const { for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) { pwallet->Flush(true); } } void WalletInit::Close() const { for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) { RemoveWallet(pwallet); } } <commit_msg>trivial: Don't translate in help text<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <init.h> #include <net.h> #include <scheduler.h> #include <outputtype.h> #include <util/system.h> #include <util/moneystr.h> #include <validation.h> #include <walletinitinterface.h> #include <wallet/rpcwallet.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> class WalletInit : public WalletInitInterface { public: //! Was the wallet component compiled in. bool HasWalletSupport() const override {return true;} //! Return the wallets help message. void AddWalletOptions() const override; //! Wallets parameter interaction bool ParameterInteraction() const override; //! Register wallet RPCs. void RegisterRPC(CRPCTable &tableRPC) const override; //! Responsible for reading and validating the -wallet arguments and verifying the wallet database. // This function will perform salvage on the wallet if requested, as long as only one wallet is // being loaded (WalletParameterInteraction forbids -salvagewallet, -zapwallettxes or -upgradewallet with multiwallet). bool Verify() const override; //! Load wallet databases. bool Open() const override; //! Complete startup of wallets. void Start(CScheduler& scheduler) const override; //! Flush all wallets in preparation for shutdown. void Flush() const override; //! Stop all wallets. Wallets will be flushed first. void Stop() const override; //! Close all wallets. void Close() const override; }; const WalletInitInterface& g_wallet_init_interface = WalletInit(); void WalletInit::AddWalletOptions() const { gArgs.AddArg("-addresstype", strprintf("What type of addresses to use (\"legacy\", \"p2sh-segwit\", or \"bech32\", default: \"%s\")", FormatOutputType(DEFAULT_ADDRESS_TYPE)), false, OptionsCategory::WALLET); gArgs.AddArg("-avoidpartialspends", strprintf("Group outputs by address, selecting all or none, instead of selecting on a per-output basis. Privacy is improved as an address is only used once (unless someone sends to it after spending from it), but may result in slightly higher fees as suboptimal coin selection may result due to the added limitation (default: %u)", DEFAULT_AVOIDPARTIALSPENDS), false, OptionsCategory::WALLET); gArgs.AddArg("-changetype", "What type of change to use (\"legacy\", \"p2sh-segwit\", or \"bech32\"). Default is same as -addresstype, except when -addresstype=p2sh-segwit a native segwit output is used when sending to a native segwit address)", false, OptionsCategory::WALLET); gArgs.AddArg("-disablewallet", "Do not load the wallet and disable wallet RPC calls", false, OptionsCategory::WALLET); gArgs.AddArg("-discardfee=<amt>", strprintf("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). " "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target", CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-fallbackfee=<amt>", strprintf("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-keypool=<n>", strprintf("Set key pool size to <n> (default: %u)", DEFAULT_KEYPOOL_SIZE), false, OptionsCategory::WALLET); gArgs.AddArg("-mintxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)), false, OptionsCategory::WALLET); gArgs.AddArg("-paytxfee=<amt>", strprintf("Fee (in %s/kB) to add to transactions you send (default: %s)", CURRENCY_UNIT, FormatMoney(CFeeRate{DEFAULT_PAY_TX_FEE}.GetFeePerK())), false, OptionsCategory::WALLET); gArgs.AddArg("-rescan", "Rescan the block chain for missing wallet transactions on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-salvagewallet", "Attempt to recover private keys from a corrupt wallet on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-spendzeroconfchange", strprintf("Spend unconfirmed change when sending transactions (default: %u)", DEFAULT_SPEND_ZEROCONF_CHANGE), false, OptionsCategory::WALLET); gArgs.AddArg("-txconfirmtarget=<n>", strprintf("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)", DEFAULT_TX_CONFIRM_TARGET), false, OptionsCategory::WALLET); gArgs.AddArg("-upgradewallet", "Upgrade wallet to latest format on startup", false, OptionsCategory::WALLET); gArgs.AddArg("-wallet=<path>", "Specify wallet database path. Can be specified multiple times to load multiple wallets. Path is interpreted relative to <walletdir> if it is not absolute, and will be created if it does not exist (as a directory containing a wallet.dat file and log files). For backwards compatibility this will also accept names of existing data files in <walletdir>.)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletbroadcast", strprintf("Make the wallet broadcast transactions (default: %u)", DEFAULT_WALLETBROADCAST), false, OptionsCategory::WALLET); gArgs.AddArg("-walletdir=<dir>", "Specify directory to hold wallets (default: <datadir>/wallets if it exists, otherwise <datadir>)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletnotify=<cmd>", "Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)", false, OptionsCategory::WALLET); gArgs.AddArg("-walletrbf", strprintf("Send transactions with full-RBF opt-in enabled (RPC only, default: %u)", DEFAULT_WALLET_RBF), false, OptionsCategory::WALLET); gArgs.AddArg("-zapwallettxes=<mode>", "Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup" " (1 = keep tx meta data e.g. payment request information, 2 = drop tx meta data)", false, OptionsCategory::WALLET); gArgs.AddArg("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB), true, OptionsCategory::WALLET_DEBUG_TEST); gArgs.AddArg("-walletrejectlongchains", strprintf("Wallet will not create transactions that violate mempool chain limits (default: %u)", DEFAULT_WALLET_REJECT_LONG_CHAINS), true, OptionsCategory::WALLET_DEBUG_TEST); } bool WalletInit::ParameterInteraction() const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { for (const std::string& wallet : gArgs.GetArgs("-wallet")) { LogPrintf("%s: parameter interaction: -disablewallet -> ignoring -wallet=%s\n", __func__, wallet); } return true; } gArgs.SoftSetArg("-wallet", ""); const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1; if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) { LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__); } if (gArgs.GetBoolArg("-salvagewallet", false)) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet")); } // Rewrite just private keys: rescan to find transactions if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__); } } bool zapwallettxes = gArgs.GetBoolArg("-zapwallettxes", false); // -zapwallettxes implies dropping the mempool on startup if (zapwallettxes && gArgs.SoftSetBoolArg("-persistmempool", false)) { LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -persistmempool=0\n", __func__); } // -zapwallettxes implies a rescan if (zapwallettxes) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes")); } if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -rescan=1\n", __func__); } } if (is_multiwallet) { if (gArgs.GetBoolArg("-upgradewallet", false)) { return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet")); } } if (gArgs.GetBoolArg("-sysperms", false)) return InitError("-sysperms is not allowed in combination with enabled wallet functionality"); if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false)) return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.")); if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB) InitWarning(AmountHighWarn("-minrelaytxfee") + " " + _("The wallet will avoid paying less than the minimum relay fee.")); if (gArgs.IsArgSet("-maxtxfee")) { CAmount nMaxFee = 0; if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""))); if (nMaxFee > HIGH_MAX_TX_FEE) InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction.")); maxTxFee = nMaxFee; if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee) { return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"), gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString())); } } return true; } void WalletInit::RegisterRPC(CRPCTable &t) const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { return; } RegisterWalletRPCCommands(t); } bool WalletInit::Verify() const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { return true; } if (gArgs.IsArgSet("-walletdir")) { fs::path wallet_dir = gArgs.GetArg("-walletdir", ""); boost::system::error_code error; // The canonical path cleans the path, preventing >1 Berkeley environment instances for the same directory fs::path canonical_wallet_dir = fs::canonical(wallet_dir, error); if (error || !fs::exists(wallet_dir)) { return InitError(strprintf(_("Specified -walletdir \"%s\" does not exist"), wallet_dir.string())); } else if (!fs::is_directory(wallet_dir)) { return InitError(strprintf(_("Specified -walletdir \"%s\" is not a directory"), wallet_dir.string())); // The canonical path transforms relative paths into absolute ones, so we check the non-canonical version } else if (!wallet_dir.is_absolute()) { return InitError(strprintf(_("Specified -walletdir \"%s\" is a relative path"), wallet_dir.string())); } gArgs.ForceSetArg("-walletdir", canonical_wallet_dir.string()); } LogPrintf("Using wallet directory %s\n", GetWalletDir().string()); uiInterface.InitMessage(_("Verifying wallet(s)...")); std::vector<std::string> wallet_files = gArgs.GetArgs("-wallet"); // Parameter interaction code should have thrown an error if -salvagewallet // was enabled with more than wallet file, so the wallet_files size check // here should have no effect. bool salvage_wallet = gArgs.GetBoolArg("-salvagewallet", false) && wallet_files.size() <= 1; // Keep track of each wallet absolute path to detect duplicates. std::set<fs::path> wallet_paths; for (const auto& wallet_file : wallet_files) { WalletLocation location(wallet_file); if (!wallet_paths.insert(location.GetPath()).second) { return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), wallet_file)); } std::string error_string; std::string warning_string; bool verify_success = CWallet::Verify(location, salvage_wallet, error_string, warning_string); if (!error_string.empty()) InitError(error_string); if (!warning_string.empty()) InitWarning(warning_string); if (!verify_success) return false; } return true; } bool WalletInit::Open() const { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { LogPrintf("Wallet disabled!\n"); return true; } for (const std::string& walletFile : gArgs.GetArgs("-wallet")) { std::shared_ptr<CWallet> pwallet = CWallet::CreateWalletFromFile(WalletLocation(walletFile)); if (!pwallet) { return false; } AddWallet(pwallet); } return true; } void WalletInit::Start(CScheduler& scheduler) const { for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) { pwallet->postInitProcess(); } // Run a thread to flush wallet periodically scheduler.scheduleEvery(MaybeCompactWalletDB, 500); } void WalletInit::Flush() const { for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) { pwallet->Flush(false); } } void WalletInit::Stop() const { for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) { pwallet->Flush(true); } } void WalletInit::Close() const { for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) { RemoveWallet(pwallet); } } <|endoftext|>
<commit_before>// // SceneOSG.cpp // // Implementation of vtScene for the OSG library // // Copyright (c) 2001-2004 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "ProjectedShadows.h" #include <osg/LightSource> #include <osg/PolygonMode> #include <osg/Switch> #include <osg/Fog> #include <osgDB/Registry> #include <time.h> // clock() & CLOCKS_PER_SEC #ifdef __FreeBSD__ # include <sys/types.h> # include <sys/time.h> # include <sys/resource.h> #endif #include <iostream> #include "vtdata/vtLog.h" using namespace osg; /////////////////////////////////////////////////////////////// // Trap for OSG messages // class OsgMsgTrap : public std::streambuf { public: inline virtual int_type overflow(int_type c = std::streambuf::traits_type::eof()) { if (c == std::streambuf::traits_type::eof()) return std::streambuf::traits_type::not_eof(c); g_Log._Log((char) c); return c; } } g_Trap; /////////////////////////////////////////////////////////////// // There is always and only one global vtScene object vtScene g_Scene; vtScene::vtScene() : vtSceneBase() { m_bInitialized = false; m_bWireframe = false; m_bWinInfo = false; } vtScene::~vtScene() { // Do not release camera, that is left for the application. } vtScene *vtGetScene() { return &g_Scene; } float vtGetTime() { return g_Scene.GetTime(); } float vtGetFrameTime() { return g_Scene.GetFrameTime(); } void vtScene::SetBgColor(RGBf color) { Vec4 color2; v2s(color, color2); m_pOsgSceneView->setClearColor(color2); } bool vtScene::Init() { // Redirect cout messages (where OSG sends its messages) to our own log std::cout.rdbuf(&g_Trap); std::cerr.rdbuf(&g_Trap); SetCamera(new vtCamera()); m_pOsgSceneView = new osgUtil::SceneView(); m_pOsgSceneView->setDefaults(); // OSG 0.9.0 and newer m_pOsgSceneView->setComputeNearFarMode(osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR); m_pOsgSceneView->setLightingMode(osgUtil::SceneView::NO_SCENEVIEW_LIGHT); // OSG 0.9.2 and newer: turn off "small feature culling" m_pOsgSceneView->setCullingMode( m_pOsgSceneView->getCullingMode() & ~osg::CullStack::SMALL_FEATURE_CULLING); m_bInitialized = true; _initialTick = _timer.tick(); _frameTick = _initialTick; return true; } void vtScene::Shutdown() { vtNode::ClearOsgModelCache(); osgDB::Registry::instance()->clearObjectCache(); } void vtScene::DoUpdate() { if (!m_bInitialized) return; _lastFrameTick = _frameTick; _frameTick = _timer.tick(); DoEngines(); // As of OSG 0.9.5, we need to store our own camera params and recreate // the projection matrix each frame. float aspect; if (m_WindowSize.x == 0 || m_WindowSize.y == 0) // safety aspect = 1.0; else aspect = (float) m_WindowSize.x / m_WindowSize.y; if (m_pCamera->IsOrtho()) { // Arguments are left, right, bottom, top, zNear, zFar float w2 = m_pCamera->GetWidth() /2; float h2 = w2 / aspect; m_pOsgSceneView->setProjectionMatrixAsOrtho(-w2, w2, -h2, h2, m_pCamera->GetHither(), m_pCamera->GetYon()); } else { float fov_x = m_pCamera->GetFOV(); float a = tan (fov_x/2); float b = a / aspect; float fov_y_div2 = atan(b); float fov_y_deg = RadiansToDegrees(fov_y_div2 * 2); m_pOsgSceneView->setProjectionMatrixAsPerspective(fov_y_deg, aspect, m_pCamera->GetHither(), m_pCamera->GetYon()); } // And apply the rotation and translation of the camera itself osg::Matrix &mat2 = m_pCamera->m_pTransform->getMatrix(); osg::Matrix imat; imat.invert(mat2); m_pOsgSceneView->setViewMatrix(imat); CalcCullPlanes(); m_pOsgSceneView->setViewport(0, 0, m_WindowSize.x, m_WindowSize.y); m_pOsgSceneView->cull(); m_pOsgSceneView->draw(); } void vtScene::SetRoot(vtGroup *pRoot) { if (pRoot) m_pOsgSceneRoot = pRoot->GetOsgGroup(); else m_pOsgSceneRoot = NULL; if (m_pOsgSceneView != NULL) m_pOsgSceneView->setSceneData(m_pOsgSceneRoot.get()); m_pRoot = pRoot; } /** * Convert window coordinates (in pixels) to a ray from the camera * in world coordinates. */ bool vtScene::CameraRay(const IPoint2 &win, FPoint3 &pos, FPoint3 &dir) { Vec3 near_point, far_point, diff; // call the handy OSG function m_pOsgSceneView->projectWindowXYIntoObject(win.x, m_WindowSize.y-win.y, near_point, far_point); diff = far_point - near_point; diff.normalize(); s2v(near_point, pos); s2v(diff, dir); return true; } // Debugging helper void LogCullPlanes(FPlane *planes) { for (int i = 0; i < 4; i++) VTLOG(" plane %d: %.3f %.3f %.3f %.3f\n", i, planes[i].x, planes[i].y, planes[i].z, planes[i].w); VTLOG("\n"); } void vtScene::CalcCullPlanes() { #if 0 // Non-API-Specific code - will work correctly as long as the Camera // methods are fully functional. FMatrix4 mat; m_pCamera->GetTransform1(mat); assert(( m_WindowSize.x > 0 ) && ( m_WindowSize.y > 0 )); double fov = m_pCamera->GetFOV(); double aspect = (float)m_WindowSize.y / m_WindowSize.x; double hither = m_pCamera->GetHither(); double a = hither * tan(fov / 2); double b = a * aspect; FPoint3 vec_l(-a, 0, -hither); FPoint3 vec_r(a, 0, -hither); FPoint3 vec_t(0, b, -hither); FPoint3 vec_b(0, -b, -hither); vec_l.Normalize(); vec_r.Normalize(); vec_t.Normalize(); vec_b.Normalize(); FPoint3 up(0.0f, 1.0f, 0.0f); FPoint3 right(1.0f, 0.0f, 0.0f); FPoint3 temp; FPoint3 center; FPoint3 norm_l, norm_r, norm_t, norm_b; temp = up.Cross(vec_l); mat.TransformVector(temp, norm_l); temp = vec_r.Cross(up); mat.TransformVector(temp, norm_r); temp = right.Cross(vec_t); mat.TransformVector(temp, norm_t); temp = vec_b.Cross(right); mat.TransformVector(temp, norm_b); mat.Transform(FPoint3(0.0f, 0.0f, 0.0f), center); // set up m_cullPlanes in world coordinates! m_cullPlanes[0].Set(center, norm_l); m_cullPlanes[1].Set(center, norm_r); m_cullPlanes[2].Set(center, norm_t); m_cullPlanes[3].Set(center, norm_b); #else // Get the view frustum clipping planes directly from OSG // OSG 0.8.44 // const ClippingVolume &clipvol = pCam->m_pOsgCamera->getClippingVolume(); // OSG 0.8.45 // const ClippingVolume &clipvol = hack_global_state->getClippingVolume(); // OSG 0.9.0 // clipvol1 is the global camera frustum (in world coordinates) // const Polytope &clipvol1 = pCam->m_pOsgCamera->getViewFrustum(); // OSG 0.9.6 // clipvol2 is the camera's frustum after it's been transformed to the // local coordinates. // const Polytope &clipvol2 = hack_global_state->getViewFrustum(); // const Polytope::PlaneList &planes = clipvol2.getPlaneList(); // Actually no - we can't get the planes from the state, because // the state includes the funny modelview matrix used to scale // the heightfield. We must get it from the 'scene' instead. osg::Matrixd &_projection = m_pOsgSceneView->getProjectionMatrix(); osg::Matrixd &_modelView = m_pOsgSceneView->getViewMatrix(); Polytope tope; tope.setToUnitFrustum(); tope.transformProvidingInverse((_modelView)*(_projection)); const Polytope::PlaneList &planes = tope.getPlaneList(); int i = 0; for (Polytope::PlaneList::const_iterator itr=planes.begin(); itr!=planes.end(); ++itr) { // make a copy of the clipping plane Plane plane = *itr; // extract the OSG plane to our own structure Vec4 pvec = plane.asVec4(); m_cullPlanes[i++].Set(-pvec.x(), -pvec.y(), -pvec.z(), -pvec.w()); } #endif // For debugging // LogCullPlanes(m_cullPlanes); } void vtScene::DrawFrameRateChart() { static float fps[100]; static int s = 0; fps[s] = GetFrameRate(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // glMatrixMode(GL_PROJECTION); // glLoadIdentity(); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glColor3f(1.0f, 1.0f, 0.0f); glBegin(GL_LINE_STRIP); for (int i = 1; i <= 100; i++) { glVertex3f(-1.0 + i/200.0f, -1.0f + fps[(s+i)%100]/200.0f, 0.0f); } glEnd(); s++; if (s == 100) s = 0; } void vtScene::SetGlobalWireframe(bool bWire) { m_bWireframe = bWire; // Set the scene's global PolygonMode attribute, which will affect all // other materials in the scene, except those which explicitly override // the attribute themselves. StateSet *global_state = m_pOsgSceneView->getGlobalStateSet(); PolygonMode *npm = new PolygonMode(); if (m_bWireframe) npm->setMode(PolygonMode::FRONT_AND_BACK, PolygonMode::LINE); else npm->setMode(PolygonMode::FRONT_AND_BACK, PolygonMode::FILL); global_state->setAttributeAndModes(npm, StateAttribute::ON); } bool vtScene::GetGlobalWireframe() { return m_bWireframe; } void printnode(osg::Node *node, int tab) { for (int i = 0; i < tab*2; i++) { osg::notify(osg::WARN) << " "; } osg::notify(osg::WARN) << node->className() << " - " << node->getName() << " @ " << node << std::endl; osg::Group *group = node->asGroup(); if (group) { for (int i = 0; i < group->getNumChildren(); i++) { printnode(group->getChild(i), tab+1); } } } void vtScene::ShadowVisibleNode(vtNode *node, bool bVis) { if (!bVis) { m_pShadowVisitor->shadow_ignore_nodes->Append(node->GetOsgNode()); } else { int i = m_pShadowVisitor->shadow_ignore_nodes->Find(node->GetOsgNode()); if (i != -1) { m_pShadowVisitor->shadow_ignore_nodes->RemoveAt(i); } } m_pShadowVisitor->RecomputeShadows(); } void vtScene::SetShadowedNode(vtTransform *pLight, vtNode *pShadowNode, vtTransform *pTransform, int iRez) { if (!m_pShadowVisitor.valid()) m_pShadowVisitor = new CreateProjectedShadowTextureCullCallback(pShadowNode->GetOsgNode(), iRez); else m_pShadowVisitor->SetShadower(pShadowNode->GetOsgNode()); m_pShadowVisitor->SetInitialLightPosition(v2s(-(pLight->GetDirection()) * 10000)); pTransform->GetOsgNode()->setCullCallback(m_pShadowVisitor.get()); m_pShadowVisitor->SetEnabled(true); osg::Node *node = pShadowNode->GetOsgNode(); #ifdef _DEBUG { osg::Group *pGroup = (osg::Group*)pTransform->GetOsgNode(); osg::Geode *pGeode = (osg::Geode*)pGroup->getChild(0); osg::Drawable* pDrawable = pGeode->getDrawable(0); pDrawable->setDrawCallback(new MyDrawCallback); } #endif } void vtScene::UnsetShadowedNode(vtTransform *pTransform) { pTransform->GetOsgNode()->setCullCallback(NULL); #ifdef _DEBUG { osg::Group *pGroup = (osg::Group*)pTransform->GetOsgNode(); osg::Geode *pGeode = (osg::Geode*)pGroup->getChild(0); osg::Drawable* pDrawable = pGeode->getDrawable(0); pDrawable->setDrawCallback(NULL); } #endif } void vtScene::UpdateShadowLightDirection(vtTransform *pLight) { if (m_pShadowVisitor.valid()) { m_pShadowVisitor.get()->SetLightPosition(v2s(-(pLight->GetDirection()) * 10000)); } } //////////////////////////////////////// <commit_msg>fix warning<commit_after>// // SceneOSG.cpp // // Implementation of vtScene for the OSG library // // Copyright (c) 2001-2004 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "ProjectedShadows.h" #include <osg/LightSource> #include <osg/PolygonMode> #include <osg/Switch> #include <osg/Fog> #include <osgDB/Registry> #include <time.h> // clock() & CLOCKS_PER_SEC #ifdef __FreeBSD__ # include <sys/types.h> # include <sys/time.h> # include <sys/resource.h> #endif #include <iostream> #include "vtdata/vtLog.h" using namespace osg; /////////////////////////////////////////////////////////////// // Trap for OSG messages // class OsgMsgTrap : public std::streambuf { public: inline virtual int_type overflow(int_type c = std::streambuf::traits_type::eof()) { if (c == std::streambuf::traits_type::eof()) return std::streambuf::traits_type::not_eof(c); g_Log._Log((char) c); return c; } } g_Trap; /////////////////////////////////////////////////////////////// // There is always and only one global vtScene object vtScene g_Scene; vtScene::vtScene() : vtSceneBase() { m_bInitialized = false; m_bWireframe = false; m_bWinInfo = false; } vtScene::~vtScene() { // Do not release camera, that is left for the application. } vtScene *vtGetScene() { return &g_Scene; } float vtGetTime() { return g_Scene.GetTime(); } float vtGetFrameTime() { return g_Scene.GetFrameTime(); } void vtScene::SetBgColor(RGBf color) { Vec4 color2; v2s(color, color2); m_pOsgSceneView->setClearColor(color2); } bool vtScene::Init() { // Redirect cout messages (where OSG sends its messages) to our own log std::cout.rdbuf(&g_Trap); std::cerr.rdbuf(&g_Trap); SetCamera(new vtCamera()); m_pOsgSceneView = new osgUtil::SceneView(); m_pOsgSceneView->setDefaults(); // OSG 0.9.0 and newer m_pOsgSceneView->setComputeNearFarMode(osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR); m_pOsgSceneView->setLightingMode(osgUtil::SceneView::NO_SCENEVIEW_LIGHT); // OSG 0.9.2 and newer: turn off "small feature culling" m_pOsgSceneView->setCullingMode( m_pOsgSceneView->getCullingMode() & ~osg::CullStack::SMALL_FEATURE_CULLING); m_bInitialized = true; _initialTick = _timer.tick(); _frameTick = _initialTick; return true; } void vtScene::Shutdown() { vtNode::ClearOsgModelCache(); osgDB::Registry::instance()->clearObjectCache(); } void vtScene::DoUpdate() { if (!m_bInitialized) return; _lastFrameTick = _frameTick; _frameTick = _timer.tick(); DoEngines(); // As of OSG 0.9.5, we need to store our own camera params and recreate // the projection matrix each frame. float aspect; if (m_WindowSize.x == 0 || m_WindowSize.y == 0) // safety aspect = 1.0; else aspect = (float) m_WindowSize.x / m_WindowSize.y; if (m_pCamera->IsOrtho()) { // Arguments are left, right, bottom, top, zNear, zFar float w2 = m_pCamera->GetWidth() /2; float h2 = w2 / aspect; m_pOsgSceneView->setProjectionMatrixAsOrtho(-w2, w2, -h2, h2, m_pCamera->GetHither(), m_pCamera->GetYon()); } else { float fov_x = m_pCamera->GetFOV(); float a = tan (fov_x/2); float b = a / aspect; float fov_y_div2 = atan(b); float fov_y_deg = RadiansToDegrees(fov_y_div2 * 2); m_pOsgSceneView->setProjectionMatrixAsPerspective(fov_y_deg, aspect, m_pCamera->GetHither(), m_pCamera->GetYon()); } // And apply the rotation and translation of the camera itself osg::Matrix &mat2 = m_pCamera->m_pTransform->getMatrix(); osg::Matrix imat; imat.invert(mat2); m_pOsgSceneView->setViewMatrix(imat); CalcCullPlanes(); m_pOsgSceneView->setViewport(0, 0, m_WindowSize.x, m_WindowSize.y); m_pOsgSceneView->cull(); m_pOsgSceneView->draw(); } void vtScene::SetRoot(vtGroup *pRoot) { if (pRoot) m_pOsgSceneRoot = pRoot->GetOsgGroup(); else m_pOsgSceneRoot = NULL; if (m_pOsgSceneView != NULL) m_pOsgSceneView->setSceneData(m_pOsgSceneRoot.get()); m_pRoot = pRoot; } /** * Convert window coordinates (in pixels) to a ray from the camera * in world coordinates. */ bool vtScene::CameraRay(const IPoint2 &win, FPoint3 &pos, FPoint3 &dir) { Vec3 near_point, far_point, diff; // call the handy OSG function m_pOsgSceneView->projectWindowXYIntoObject(win.x, m_WindowSize.y-win.y, near_point, far_point); diff = far_point - near_point; diff.normalize(); s2v(near_point, pos); s2v(diff, dir); return true; } // Debugging helper void LogCullPlanes(FPlane *planes) { for (int i = 0; i < 4; i++) VTLOG(" plane %d: %.3f %.3f %.3f %.3f\n", i, planes[i].x, planes[i].y, planes[i].z, planes[i].w); VTLOG("\n"); } void vtScene::CalcCullPlanes() { #if 0 // Non-API-Specific code - will work correctly as long as the Camera // methods are fully functional. FMatrix4 mat; m_pCamera->GetTransform1(mat); assert(( m_WindowSize.x > 0 ) && ( m_WindowSize.y > 0 )); double fov = m_pCamera->GetFOV(); double aspect = (float)m_WindowSize.y / m_WindowSize.x; double hither = m_pCamera->GetHither(); double a = hither * tan(fov / 2); double b = a * aspect; FPoint3 vec_l(-a, 0, -hither); FPoint3 vec_r(a, 0, -hither); FPoint3 vec_t(0, b, -hither); FPoint3 vec_b(0, -b, -hither); vec_l.Normalize(); vec_r.Normalize(); vec_t.Normalize(); vec_b.Normalize(); FPoint3 up(0.0f, 1.0f, 0.0f); FPoint3 right(1.0f, 0.0f, 0.0f); FPoint3 temp; FPoint3 center; FPoint3 norm_l, norm_r, norm_t, norm_b; temp = up.Cross(vec_l); mat.TransformVector(temp, norm_l); temp = vec_r.Cross(up); mat.TransformVector(temp, norm_r); temp = right.Cross(vec_t); mat.TransformVector(temp, norm_t); temp = vec_b.Cross(right); mat.TransformVector(temp, norm_b); mat.Transform(FPoint3(0.0f, 0.0f, 0.0f), center); // set up m_cullPlanes in world coordinates! m_cullPlanes[0].Set(center, norm_l); m_cullPlanes[1].Set(center, norm_r); m_cullPlanes[2].Set(center, norm_t); m_cullPlanes[3].Set(center, norm_b); #else // Get the view frustum clipping planes directly from OSG // OSG 0.8.44 // const ClippingVolume &clipvol = pCam->m_pOsgCamera->getClippingVolume(); // OSG 0.8.45 // const ClippingVolume &clipvol = hack_global_state->getClippingVolume(); // OSG 0.9.0 // clipvol1 is the global camera frustum (in world coordinates) // const Polytope &clipvol1 = pCam->m_pOsgCamera->getViewFrustum(); // OSG 0.9.6 // clipvol2 is the camera's frustum after it's been transformed to the // local coordinates. // const Polytope &clipvol2 = hack_global_state->getViewFrustum(); // const Polytope::PlaneList &planes = clipvol2.getPlaneList(); // Actually no - we can't get the planes from the state, because // the state includes the funny modelview matrix used to scale // the heightfield. We must get it from the 'scene' instead. osg::Matrixd &_projection = m_pOsgSceneView->getProjectionMatrix(); osg::Matrixd &_modelView = m_pOsgSceneView->getViewMatrix(); Polytope tope; tope.setToUnitFrustum(); tope.transformProvidingInverse((_modelView)*(_projection)); const Polytope::PlaneList &planes = tope.getPlaneList(); int i = 0; for (Polytope::PlaneList::const_iterator itr=planes.begin(); itr!=planes.end(); ++itr) { // make a copy of the clipping plane Plane plane = *itr; // extract the OSG plane to our own structure Vec4 pvec = plane.asVec4(); m_cullPlanes[i++].Set(-pvec.x(), -pvec.y(), -pvec.z(), -pvec.w()); } #endif // For debugging // LogCullPlanes(m_cullPlanes); } void vtScene::DrawFrameRateChart() { static float fps[100]; static int s = 0; fps[s] = GetFrameRate(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // glMatrixMode(GL_PROJECTION); // glLoadIdentity(); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glColor3f(1.0f, 1.0f, 0.0f); glBegin(GL_LINE_STRIP); for (int i = 1; i <= 100; i++) { glVertex3f(-1.0 + i/200.0f, -1.0f + fps[(s+i)%100]/200.0f, 0.0f); } glEnd(); s++; if (s == 100) s = 0; } void vtScene::SetGlobalWireframe(bool bWire) { m_bWireframe = bWire; // Set the scene's global PolygonMode attribute, which will affect all // other materials in the scene, except those which explicitly override // the attribute themselves. StateSet *global_state = m_pOsgSceneView->getGlobalStateSet(); PolygonMode *npm = new PolygonMode(); if (m_bWireframe) npm->setMode(PolygonMode::FRONT_AND_BACK, PolygonMode::LINE); else npm->setMode(PolygonMode::FRONT_AND_BACK, PolygonMode::FILL); global_state->setAttributeAndModes(npm, StateAttribute::ON); } bool vtScene::GetGlobalWireframe() { return m_bWireframe; } void printnode(osg::Node *node, int tab) { for (int i = 0; i < tab*2; i++) { osg::notify(osg::WARN) << " "; } osg::notify(osg::WARN) << node->className() << " - " << node->getName() << " @ " << node << std::endl; osg::Group *group = node->asGroup(); if (group) { for (unsigned int i = 0; i < group->getNumChildren(); i++) { printnode(group->getChild(i), tab+1); } } } void vtScene::ShadowVisibleNode(vtNode *node, bool bVis) { if (!bVis) { m_pShadowVisitor->shadow_ignore_nodes->Append(node->GetOsgNode()); } else { int i = m_pShadowVisitor->shadow_ignore_nodes->Find(node->GetOsgNode()); if (i != -1) { m_pShadowVisitor->shadow_ignore_nodes->RemoveAt(i); } } m_pShadowVisitor->RecomputeShadows(); } void vtScene::SetShadowedNode(vtTransform *pLight, vtNode *pShadowNode, vtTransform *pTransform, int iRez) { if (!m_pShadowVisitor.valid()) m_pShadowVisitor = new CreateProjectedShadowTextureCullCallback(pShadowNode->GetOsgNode(), iRez); else m_pShadowVisitor->SetShadower(pShadowNode->GetOsgNode()); m_pShadowVisitor->SetInitialLightPosition(v2s(-(pLight->GetDirection()) * 10000)); pTransform->GetOsgNode()->setCullCallback(m_pShadowVisitor.get()); m_pShadowVisitor->SetEnabled(true); osg::Node *node = pShadowNode->GetOsgNode(); #ifdef _DEBUG { osg::Group *pGroup = (osg::Group*)pTransform->GetOsgNode(); osg::Geode *pGeode = (osg::Geode*)pGroup->getChild(0); osg::Drawable* pDrawable = pGeode->getDrawable(0); pDrawable->setDrawCallback(new MyDrawCallback); } #endif } void vtScene::UnsetShadowedNode(vtTransform *pTransform) { pTransform->GetOsgNode()->setCullCallback(NULL); #ifdef _DEBUG { osg::Group *pGroup = (osg::Group*)pTransform->GetOsgNode(); osg::Geode *pGeode = (osg::Geode*)pGroup->getChild(0); osg::Drawable* pDrawable = pGeode->getDrawable(0); pDrawable->setDrawCallback(NULL); } #endif } void vtScene::UpdateShadowLightDirection(vtTransform *pLight) { if (m_pShadowVisitor.valid()) { m_pShadowVisitor.get()->SetLightPosition(v2s(-(pLight->GetDirection()) * 10000)); } } //////////////////////////////////////// <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 13308 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "vtkSphereSource.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkRenderWindowInteractor.h" #include "vtkProperty.h" #include <mitkPicFileReader.h> #include <mitkImage.h> #include <mitkDataTree.h> //#include <mitkImageMapper2D.h> #include <mitkLevelWindow.h> #include <mitkLevelWindowProperty.h> #include <mitkVtkPropRenderer.h> #include <vtkMitkRenderProp.h> #include <mitkVtkLayerController.h> #include <mitkNativeRenderWindowInteractor.h> #include <fstream> int mitkVtkPropRendererTest(int argc, char* argv[]) { //Read pic-Image from file std::cout << "Reading image: "; mitk::PicFileReader::Pointer reader = mitk::PicFileReader::New(); reader->SetFileName(argv[1]); reader->Update(); std::cout<<"[PASSED]"<<std::endl; mitk::Image::Pointer image = reader->GetOutput(); std::cout << "Creating node: "; mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating tree: "; mitk::DataTree* tree; (tree=mitk::DataTree::New())->Register(); //@FIXME: da DataTreeIteratorClone keinen Smartpointer auf DataTree hlt, wird tree sonst gelscht. std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating iterator on tree: "; mitk::DataTreePreOrderIterator it(tree); std::cout<<"[PASSED]"<<std::endl; std::cout << "Adding node via iterator: "; it.Add(node); std::cout<<"[PASSED]"<<std::endl; std::cout << "Adding level-window property: "; mitk::LevelWindowProperty::Pointer levWinProp = new mitk::LevelWindowProperty(); mitk::LevelWindow levelwindow; levelwindow.SetAuto( image ); levWinProp->SetLevelWindow( levelwindow ); node->GetPropertyList()->SetProperty( "levelwindow", levWinProp ); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating a vtk sphere: "; vtkSphereSource *sphere = vtkSphereSource::New(); sphere->SetRadius(1.0); sphere->SetThetaResolution(18); sphere->SetPhiResolution(18); vtkPolyDataMapper *map = vtkPolyDataMapper::New(); map->SetInput(sphere->GetOutput()); vtkActor *aSphere = vtkActor::New(); aSphere->SetMapper(map); aSphere->GetProperty()->SetColor(0,0,1); // sphere color blue std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating a renderer for the sphere: "; vtkRenderer *sphereRenderer = vtkRenderer::New(); sphereRenderer->AddActor(aSphere); //sphereRenderer->SetBackground(1,1,1); // Background color white std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating vtkRenderWindow and VtkPropRenderer: "; vtkRenderWindow *renderWindow = vtkRenderWindow::New(); mitk::VtkPropRenderer *propRenderer = new mitk::VtkPropRenderer( "the renderer", renderWindow ); //propRenderer->SetMapperID(2); std::cout<<"[PASSED]"<<std::endl; //renderWindow->AddRenderer(sphereRenderer); //renderWindow->SetErase(0); std::cout << "BaseRenderer::SetData(iterator): "; propRenderer->SetData(&it); std::cout<<"[PASSED]"<<std::endl; //std::cout << "Testing if an mitk::ImageMapper2D was created: "; //if(dynamic_cast<mitk::ImageMapper2D*>(node->GetMapper(1))==NULL) //{ // std::cout<<"[FAILED]"<<std::endl; // return EXIT_FAILURE; //} //std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating vtkMitkRenderProp and connecting it to the VtkPropRenderer: "; vtkMitkRenderProp* renderProp = vtkMitkRenderProp::New(); renderProp->SetPropRenderer(propRenderer); propRenderer->GetVtkRenderer()->AddViewProp(renderProp); std::cout<<"[PASSED]"<<std::endl; std::cout << "Inserting the sphere into the foreground of the VtkLayerController: "; mitk::VtkLayerController::GetInstance(renderWindow)->InsertForegroundRenderer(sphereRenderer,true); std::cout<<"[PASSED]"<<std::endl; std::cout << "Do the rendering: "; renderWindow->Render(); std::cout<<"[PASSED]"<<std::endl; // mouse interaction for debugging //vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); //iren->SetRenderWindow(renderWindow); //iren->Start(); renderWindow->Delete(); tree = NULL; // As the tree has been registered explicitely, destroy it again. std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <commit_msg>FIX: run test only on pic images<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 13308 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "vtkSphereSource.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkRenderWindowInteractor.h" #include "vtkProperty.h" #include <mitkPicFileReader.h> #include <mitkImage.h> #include <mitkDataTree.h> //#include <mitkImageMapper2D.h> #include <mitkLevelWindow.h> #include <mitkLevelWindowProperty.h> #include <mitkVtkPropRenderer.h> #include <vtkMitkRenderProp.h> #include <mitkVtkLayerController.h> #include <mitkNativeRenderWindowInteractor.h> #include <itksys/SystemTools.hxx> #include <fstream> int mitkVtkPropRendererTest(int argc, char* argv[]) { //independently read header of pic file ipPicDescriptor *picheader=NULL; if(argc>=1) { if(itksys::SystemTools::LowerCase(itksys::SystemTools::GetFilenameExtension(argv[1])).find(".pic")!=std::string::npos) picheader = ipPicGetHeader(argv[1], NULL); } if(picheader==NULL) { std::cout<<"file not found/not a pic-file - test not applied [PASSED]"<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } ipPicGetTags(argv[1], picheader); //Read pic-Image from file std::cout << "Reading image: "; mitk::PicFileReader::Pointer reader = mitk::PicFileReader::New(); reader->SetFileName(argv[1]); reader->Update(); std::cout<<"[PASSED]"<<std::endl; mitk::Image::Pointer image = reader->GetOutput(); std::cout << "Creating node: "; mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating tree: "; mitk::DataTree* tree; (tree=mitk::DataTree::New())->Register(); //@FIXME: da DataTreeIteratorClone keinen Smartpointer auf DataTree hlt, wird tree sonst gelscht. std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating iterator on tree: "; mitk::DataTreePreOrderIterator it(tree); std::cout<<"[PASSED]"<<std::endl; std::cout << "Adding node via iterator: "; it.Add(node); std::cout<<"[PASSED]"<<std::endl; std::cout << "Adding level-window property: "; mitk::LevelWindowProperty::Pointer levWinProp = new mitk::LevelWindowProperty(); mitk::LevelWindow levelwindow; levelwindow.SetAuto( image ); levWinProp->SetLevelWindow( levelwindow ); node->GetPropertyList()->SetProperty( "levelwindow", levWinProp ); std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating a vtk sphere: "; vtkSphereSource *sphere = vtkSphereSource::New(); sphere->SetRadius(1.0); sphere->SetThetaResolution(18); sphere->SetPhiResolution(18); vtkPolyDataMapper *map = vtkPolyDataMapper::New(); map->SetInput(sphere->GetOutput()); vtkActor *aSphere = vtkActor::New(); aSphere->SetMapper(map); aSphere->GetProperty()->SetColor(0,0,1); // sphere color blue std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating a renderer for the sphere: "; vtkRenderer *sphereRenderer = vtkRenderer::New(); sphereRenderer->AddActor(aSphere); //sphereRenderer->SetBackground(1,1,1); // Background color white std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating vtkRenderWindow and VtkPropRenderer: "; vtkRenderWindow *renderWindow = vtkRenderWindow::New(); mitk::VtkPropRenderer *propRenderer = new mitk::VtkPropRenderer( "the renderer", renderWindow ); //propRenderer->SetMapperID(2); std::cout<<"[PASSED]"<<std::endl; //renderWindow->AddRenderer(sphereRenderer); //renderWindow->SetErase(0); std::cout << "BaseRenderer::SetData(iterator): "; propRenderer->SetData(&it); std::cout<<"[PASSED]"<<std::endl; //std::cout << "Testing if an mitk::ImageMapper2D was created: "; //if(dynamic_cast<mitk::ImageMapper2D*>(node->GetMapper(1))==NULL) //{ // std::cout<<"[FAILED]"<<std::endl; // return EXIT_FAILURE; //} //std::cout<<"[PASSED]"<<std::endl; std::cout << "Creating vtkMitkRenderProp and connecting it to the VtkPropRenderer: "; vtkMitkRenderProp* renderProp = vtkMitkRenderProp::New(); renderProp->SetPropRenderer(propRenderer); propRenderer->GetVtkRenderer()->AddViewProp(renderProp); std::cout<<"[PASSED]"<<std::endl; std::cout << "Inserting the sphere into the foreground of the VtkLayerController: "; mitk::VtkLayerController::GetInstance(renderWindow)->InsertForegroundRenderer(sphereRenderer,true); std::cout<<"[PASSED]"<<std::endl; std::cout << "Do the rendering: "; renderWindow->Render(); std::cout<<"[PASSED]"<<std::endl; // mouse interaction for debugging //vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); //iren->SetRenderWindow(renderWindow); //iren->Start(); renderWindow->Delete(); tree = NULL; // As the tree has been registered explicitely, destroy it again. std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <webkit2/webkit-web-extension.h> #include <JavaScriptCore/JavaScript.h> #include <string.h> #include <soup.h> #include "utils.h" static WebKitWebExtension* extension; static guint idLogHandler = 0; static guint idSendRequestHandler = 0; static guint idPageCreatedHandler = 0; static gboolean DEBUG = FALSE; static gchar* JSValueToStr(JSGlobalContextRef context, JSValueRef val) { JSStringRef js_str_value = JSValueToStringCopy(context, val, NULL); gsize str_length = JSStringGetMaximumUTF8CStringSize(js_str_value); gchar* str_value = (gchar*)g_malloc(str_length); JSStringGetUTF8CString(js_str_value, str_value, str_length); JSStringRelease(js_str_value); return str_value; } static gboolean web_page_send_request(WebKitWebPage* page, WebKitURIRequest* request, WebKitURIResponse* redirected_response, gpointer data) { gchar* cstamp = (gchar*)data; const char* uri = webkit_uri_request_get_uri(request); // always allow blank and never report it if (uri == NULL || g_strcmp0(uri, "") == 0 || g_strcmp0(uri, "about:blank") == 0) return FALSE; JSValueRef result; JSValueRef exception; gboolean hasHandler = FALSE; JSGlobalContextRef jsContext = webkit_frame_get_javascript_context_for_script_world( webkit_web_page_get_main_frame(page), webkit_script_world_get_default() ); const char* funcStr = g_strconcat("window.request_", cstamp, NULL); JSStringRef funcScript = JSStringCreateWithUTF8CString(g_strconcat("!!(", funcStr, ")", NULL)); exception = NULL; result = JSEvaluateScript( jsContext, funcScript, NULL, // JSObjectRef thisObject NULL, // JSStringRef sourceURL 0, // int startingLineNumber &exception // JSValueRef* exception ); if (exception != NULL) { gchar* exceptionStr = JSValueToStr(jsContext, exception); g_warning("%s, while checking availability of filter function handler", exceptionStr); g_free(exceptionStr); } if (JSValueIsBoolean(jsContext, result)) { hasHandler = JSValueToBoolean(jsContext, result); } else { g_warning("Invalid value returned while checking availability of filter function handler"); } if (hasHandler == FALSE) { g_message("No filter handler available to check %s", uri); return FALSE; } const gchar* redirect = ""; if (redirected_response != NULL) { g_message("request %s is redirected to %s", uri, webkit_uri_response_get_uri(redirected_response)); redirect = webkit_uri_response_get_uri(redirected_response); } const gchar* scriptStr = g_strconcat(funcStr, "(\"", uri, "\", \"", redirect, "\")", NULL); JSStringRef script = JSStringCreateWithUTF8CString(scriptStr); exception = NULL; result = JSEvaluateScript( jsContext, script, NULL, // JSObjectRef thisObject NULL, // JSStringRef sourceURL 0, // int startingLineNumber &exception // JSValueRef* exception ); if (exception != NULL) { gchar* exceptionStr = JSValueToStr(jsContext, exception); g_warning("%s, while running filter function handler", exceptionStr); g_free(exceptionStr); } if (JSValueIsBoolean(jsContext, result)) { if (JSValueToBoolean(jsContext, result)) { // go through g_message("accept %s", uri); } else { g_message("reject %s", uri); webkit_uri_request_set_uri(request, g_strconcat("#", uri, NULL)); } } else if (JSValueIsString(jsContext, result)) { gchar* str_value = JSValueToStr(jsContext, result); g_message("rewrite %s to %s", uri, str_value); webkit_uri_request_set_uri(request, str_value); g_free(str_value); } else { // no return value - meaning ignore the request g_message("ignore %s", uri); } return FALSE; } static void web_page_created_callback(WebKitWebExtension* ext, WebKitWebPage* web_page, gpointer data) { g_message("page created"); if (idSendRequestHandler > 0) { g_signal_handler_disconnect(web_page, idSendRequestHandler); idSendRequestHandler = 0; } idSendRequestHandler = g_signal_connect(web_page, "send-request", G_CALLBACK(web_page_send_request), data); } static void ttyLog(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) { if ((log_level & G_LOG_LEVEL_WARNING) == 0 && DEBUG == FALSE) return; FILE* ftty = fopen("/dev/tty", "a"); if (ftty == NULL) { return; } fprintf(ftty, "%s\n", message); fclose(ftty); } extern "C" { G_MODULE_EXPORT void webkit_web_extension_initialize_with_user_data(WebKitWebExtension* ext, const GVariant* constData) { const gchar* envDebug = g_getenv("DEBUG"); if (envDebug != NULL) { gchar** envStrv = g_strsplit(envDebug, ",", -1); if (g_strv_contains(envStrv, "webkitgtk:extension")) { DEBUG = TRUE; } g_strfreev(envStrv); } extension = ext; idLogHandler = g_log_set_handler( NULL, G_LOG_LEVEL_MASK, ttyLog, NULL ); gchar* cstamp; g_variant_get((GVariant*)constData, "(s)", &cstamp); idPageCreatedHandler = g_signal_connect(extension, "page-created", G_CALLBACK(web_page_created_callback), cstamp); } } static void __attribute__((destructor)) webkit_web_extension_destroy (void) { g_message("extension destroyed"); g_log_remove_handler(NULL, idLogHandler); if (idPageCreatedHandler > 0) { g_signal_handler_disconnect(extension, idPageCreatedHandler); idPageCreatedHandler = 0; } g_object_unref(extension); extension = NULL; } <commit_msg>Improve debug message<commit_after>#include <webkit2/webkit-web-extension.h> #include <JavaScriptCore/JavaScript.h> #include <string.h> #include <soup.h> #include "utils.h" static WebKitWebExtension* extension; static guint idLogHandler = 0; static guint idSendRequestHandler = 0; static guint idPageCreatedHandler = 0; static gboolean DEBUG = FALSE; static gchar* JSValueToStr(JSGlobalContextRef context, JSValueRef val) { JSStringRef js_str_value = JSValueToStringCopy(context, val, NULL); gsize str_length = JSStringGetMaximumUTF8CStringSize(js_str_value); gchar* str_value = (gchar*)g_malloc(str_length); JSStringGetUTF8CString(js_str_value, str_value, str_length); JSStringRelease(js_str_value); return str_value; } static gboolean web_page_send_request(WebKitWebPage* page, WebKitURIRequest* request, WebKitURIResponse* redirected_response, gpointer data) { gchar* cstamp = (gchar*)data; const char* uri = webkit_uri_request_get_uri(request); // always allow blank and never report it if (uri == NULL || g_strcmp0(uri, "") == 0 || g_strcmp0(uri, "about:blank") == 0) return FALSE; JSValueRef result; JSValueRef exception; gboolean hasHandler = FALSE; JSGlobalContextRef jsContext = webkit_frame_get_javascript_context_for_script_world( webkit_web_page_get_main_frame(page), webkit_script_world_get_default() ); const char* funcStr = g_strconcat("window.request_", cstamp, NULL); JSStringRef funcScript = JSStringCreateWithUTF8CString(g_strconcat("!!(", funcStr, ")", NULL)); exception = NULL; result = JSEvaluateScript( jsContext, funcScript, NULL, // JSObjectRef thisObject NULL, // JSStringRef sourceURL 0, // int startingLineNumber &exception // JSValueRef* exception ); if (exception != NULL) { gchar* exceptionStr = JSValueToStr(jsContext, exception); g_warning("%s, while checking availability of filter function handler", exceptionStr); g_free(exceptionStr); } if (JSValueIsBoolean(jsContext, result)) { hasHandler = JSValueToBoolean(jsContext, result); } else { g_warning("Invalid value returned while checking availability of filter function handler"); } if (hasHandler == FALSE) { g_message("No filter handler %s available to check %s", funcStr, uri); return FALSE; } const gchar* redirect = ""; if (redirected_response != NULL) { g_message("request %s is redirected to %s", uri, webkit_uri_response_get_uri(redirected_response)); redirect = webkit_uri_response_get_uri(redirected_response); } const gchar* scriptStr = g_strconcat(funcStr, "(\"", uri, "\", \"", redirect, "\")", NULL); JSStringRef script = JSStringCreateWithUTF8CString(scriptStr); exception = NULL; result = JSEvaluateScript( jsContext, script, NULL, // JSObjectRef thisObject NULL, // JSStringRef sourceURL 0, // int startingLineNumber &exception // JSValueRef* exception ); if (exception != NULL) { gchar* exceptionStr = JSValueToStr(jsContext, exception); g_warning("%s, while running filter function handler", exceptionStr); g_free(exceptionStr); } if (JSValueIsBoolean(jsContext, result)) { if (JSValueToBoolean(jsContext, result)) { // go through g_message("accept %s", uri); } else { g_message("reject %s", uri); webkit_uri_request_set_uri(request, g_strconcat("#", uri, NULL)); } } else if (JSValueIsString(jsContext, result)) { gchar* str_value = JSValueToStr(jsContext, result); g_message("rewrite %s to %s", uri, str_value); webkit_uri_request_set_uri(request, str_value); g_free(str_value); } else { // no return value - meaning ignore the request g_message("ignore %s", uri); } return FALSE; } static void web_page_created_callback(WebKitWebExtension* ext, WebKitWebPage* web_page, gpointer data) { g_message("page created"); if (idSendRequestHandler > 0) { g_signal_handler_disconnect(web_page, idSendRequestHandler); idSendRequestHandler = 0; } idSendRequestHandler = g_signal_connect(web_page, "send-request", G_CALLBACK(web_page_send_request), data); } static void ttyLog(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) { if ((log_level & G_LOG_LEVEL_WARNING) == 0 && DEBUG == FALSE) return; FILE* ftty = fopen("/dev/tty", "a"); if (ftty == NULL) { return; } fprintf(ftty, "%s\n", message); fclose(ftty); } extern "C" { G_MODULE_EXPORT void webkit_web_extension_initialize_with_user_data(WebKitWebExtension* ext, const GVariant* constData) { const gchar* envDebug = g_getenv("DEBUG"); if (envDebug != NULL) { gchar** envStrv = g_strsplit(envDebug, ",", -1); if (g_strv_contains(envStrv, "webkitgtk:extension")) { DEBUG = TRUE; } g_strfreev(envStrv); } extension = ext; idLogHandler = g_log_set_handler( NULL, G_LOG_LEVEL_MASK, ttyLog, NULL ); gchar* cstamp; g_variant_get((GVariant*)constData, "(s)", &cstamp); idPageCreatedHandler = g_signal_connect(extension, "page-created", G_CALLBACK(web_page_created_callback), cstamp); } } static void __attribute__((destructor)) webkit_web_extension_destroy (void) { g_message("extension destroyed"); g_log_remove_handler(NULL, idLogHandler); if (idPageCreatedHandler > 0) { g_signal_handler_disconnect(extension, idPageCreatedHandler); idPageCreatedHandler = 0; } g_object_unref(extension); extension = NULL; } <|endoftext|>
<commit_before>// // CodeGeneratorCPP.cpp // Protocol // // Created by Wahid Tanner on 10/17/14. // #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/fstream.hpp> #include "CodeGeneratorCPP.h" using namespace std; using namespace boost; using namespace MuddledManaged; const std::string Protocol::CodeGeneratorCPP::mHeaderFileExtension = ".protocol.h"; const std::string Protocol::CodeGeneratorCPP::mSourceFileExtension = ".protocol.cpp"; const std::string Protocol::CodeGeneratorCPP::mHeaderFileProlog = "// This file was generated from the Protocol compiler.\n" "// You should not edit this file directly.\n"; const std::string Protocol::CodeGeneratorCPP::mSourceFileProlog = "// This file was generated from the Protocol compiler.\n" "// You should not edit this file directly.\n"; Protocol::CodeGeneratorCPP::CodeGeneratorCPP () { } void Protocol::CodeGeneratorCPP::generateCode (const string & outputFolder, const ProtoModel & model) { filesystem::path outputPath(outputFolder); filesystem::path modelPath(model.fileName()); filesystem::path headerPath(outputPath / filesystem::change_extension(modelPath, mHeaderFileExtension)); filesystem::path sourcePath(outputPath / filesystem::change_extension(modelPath, mSourceFileExtension)); filesystem::create_directory(outputFolder); filesystem::ofstream headerFile(headerPath); filesystem::ofstream sourceFile(sourcePath); headerFile << mHeaderFileProlog << endl; sourceFile << mSourceFileProlog << endl; sourceFile.close(); headerFile.close(); } <commit_msg>Ensure files are opened and truncated and removed explicit close call.<commit_after>// // CodeGeneratorCPP.cpp // Protocol // // Created by Wahid Tanner on 10/17/14. // #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/fstream.hpp> #include "CodeGeneratorCPP.h" using namespace std; using namespace boost; using namespace MuddledManaged; const std::string Protocol::CodeGeneratorCPP::mHeaderFileExtension = ".protocol.h"; const std::string Protocol::CodeGeneratorCPP::mSourceFileExtension = ".protocol.cpp"; const std::string Protocol::CodeGeneratorCPP::mHeaderFileProlog = "// This file was generated from the Protocol compiler.\n" "// You should not edit this file directly.\n"; const std::string Protocol::CodeGeneratorCPP::mSourceFileProlog = "// This file was generated from the Protocol compiler.\n" "// You should not edit this file directly.\n"; Protocol::CodeGeneratorCPP::CodeGeneratorCPP () { } void Protocol::CodeGeneratorCPP::generateCode (const string & outputFolder, const ProtoModel & model) { filesystem::path outputPath(outputFolder); filesystem::path modelPath(model.fileName()); filesystem::path headerPath(outputPath / filesystem::change_extension(modelPath, mHeaderFileExtension)); filesystem::path sourcePath(outputPath / filesystem::change_extension(modelPath, mSourceFileExtension)); filesystem::create_directory(outputFolder); filesystem::ofstream headerFile(headerPath, ios::out | ios::trunc); filesystem::ofstream sourceFile(sourcePath, ios::out | ios::trunc); headerFile << mHeaderFileProlog << endl; sourceFile << mSourceFileProlog << endl; } <|endoftext|>
<commit_before>/* * HashingOverlapper.cpp * * Created on: 31.01.2013 * Author: Christian Staudt (christian.staudt@kit.edu) */ #include "HashingOverlapper.h" namespace NetworKit { HashingOverlapper::HashingOverlapper() { // TODO Auto-generated constructor stub } HashingOverlapper::~HashingOverlapper() { // TODO Auto-generated destructor stub } Clustering HashingOverlapper::run(Graph& G, std::vector<Clustering>& clusterings) { DEBUG("Starting hashing overlapper"); // hash function sdbm auto sdbm = [](int64_t cid) { unsigned char* str = (unsigned char*) &cid; unsigned long h = 0; int c; while ((c = *str++)) { h = c + (h << 6) + (h << 16) - h; } return h; }; auto djb2 = [](int64_t cid) { unsigned char* str = (unsigned char*) &cid; unsigned long hash = 5381; int c; while ((c = *str++)) { hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } return hash; }; count n = G.numberOfNodes(); Clustering core(n); // select hash function auto hash = djb2; core.setAll(0); for (index c = 0; c < clusterings.size(); ++c) { Clustering& zeta = clusterings[c]; zeta.parallelForEntries([&](node v, cluster clv) { core[v] += (hash((c+2) * clv) & 0xffff); }); } core.compact(); return core; } } /* namespace NetworKit */ <commit_msg>modified hashing scheme for two clusterings<commit_after>/* * HashingOverlapper.cpp * * Created on: 31.01.2013 * Author: Christian Staudt (christian.staudt@kit.edu) */ #include "HashingOverlapper.h" namespace NetworKit { HashingOverlapper::HashingOverlapper() { // TODO Auto-generated constructor stub } HashingOverlapper::~HashingOverlapper() { // TODO Auto-generated destructor stub } Clustering HashingOverlapper::run(Graph& G, std::vector<Clustering>& clusterings) { DEBUG("Starting hashing overlapper"); // hash function sdbm auto sdbm = [](int64_t cid) { unsigned char* str = (unsigned char*) &cid; unsigned long h = 0; int c; while ((c = *str++)) { h = c + (h << 6) + (h << 16) - h; } return h; }; auto djb2 = [](int64_t cid) { unsigned char* str = (unsigned char*) &cid; unsigned long hash = 5381; int c; while ((c = *str++)) { hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } return hash; }; count n = G.numberOfNodes(); Clustering core(n); // select hash function auto hash = djb2; core.setAll(0); const count numC = clusterings.size(); const count upperId = clusterings.back().upperBound(); if (numC > 2) { for (index c = 0; c < numC; ++c) { Clustering& zeta = clusterings[c]; zeta.parallelForEntries([&](node v, cluster clv) { core[v] += (hash((c+2) * clv) & 0xffff); }); } } else { Clustering& first = clusterings[0]; Clustering& second = clusterings[1]; // Assumption: second has at least as many nodes as first G.parallelForNodes([&](node v) { if (v >= first.numberOfEntries()) { core[v] = none; } else { if (first[v] == none || second[v] == none) { core[v] = none; } else { count key = ((first[v] & 0xffff) << 16) | (second[v] & 0xffff); core[v] = hash(key); } } }); } core.compact(); return core; } } /* namespace NetworKit */ <|endoftext|>
<commit_before>/* Copyright (c) 2013-2022 Jeffrey Pfau * * 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 "ForwarderView.h" #include <QMessageBox> #include <QResizeEvent> #include "ForwarderGenerator.h" #include "GBAApp.h" #include "utils.h" using namespace QGBA; ForwarderView::ForwarderView(QWidget* parent) : QDialog(parent) { m_ui.setupUi(this); connectBrowseButton(m_ui.romBrowse, m_ui.romFilename, tr("Select ROM file"), false, romFilters()); connectBrowseButton(m_ui.outputBrowse, m_ui.outputFilename, tr("Select output filename"), true); connectBrowseButton(m_ui.baseBrowse, m_ui.baseFilename, tr("Select base file")); connect(m_ui.romFilename, &QLineEdit::textChanged, this, &ForwarderView::validate); connect(m_ui.outputFilename, &QLineEdit::textChanged, this, &ForwarderView::validate); connect(m_ui.baseFilename, &QLineEdit::textChanged, this, &ForwarderView::validate); connect(m_ui.title, &QLineEdit::textChanged, this, &ForwarderView::validate); connect(m_ui.baseType, qOverload<int>(&QComboBox::currentIndexChanged), this, &ForwarderView::validate); connect(m_ui.imageSelect, qOverload<int>(&QComboBox::currentIndexChanged), this, &ForwarderView::setActiveImage); connect(m_ui.imageBrowse, &QAbstractButton::clicked, this, &ForwarderView::selectImage); connect(&m_controller, &ForwarderController::buildComplete, this, &QDialog::accept); connect(&m_controller, &ForwarderController::buildFailed, this, [this]() { QMessageBox* error = new QMessageBox(QMessageBox::Critical, tr("Build failed"), tr("Failed to build forwarder"), QMessageBox::Ok, this, Qt::Sheet); error->setAttribute(Qt::WA_DeleteOnClose); error->show(); }); connect(m_ui.system3DS, &QAbstractButton::clicked, this, [this]() { setSystem(ForwarderGenerator::System::N3DS); }); connect(m_ui.systemVita, &QAbstractButton::clicked, this, [this]() { setSystem(ForwarderGenerator::System::VITA); }); m_ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); connect(m_ui.buttonBox->button(QDialogButtonBox::Ok), &QAbstractButton::clicked, [this]() { m_controller.generator()->setRom(m_ui.romFilename->text()); m_controller.startBuild(m_ui.outputFilename->text()); }); } void ForwarderView::build() { if (!m_controller.generator()) { return; } m_controller.generator()->setTitle(m_ui.title->text()); m_controller.generator()->setRom(m_ui.romFilename->text()); m_controller.startBuild(m_ui.outputFilename->text()); } void ForwarderView::validate() { bool valid = true; if (m_ui.romFilename->text().isEmpty()) { valid = false; } else if (!QFileInfo(m_ui.romFilename->text()).exists()) { valid = false; } if (m_ui.outputFilename->text().isEmpty()) { valid = false; } if (m_ui.title->text().isEmpty()) { valid = false; } if (!m_ui.system->checkedButton()) { valid = false; } if (m_ui.baseType->currentIndex() != 1) { valid = false; } m_ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid); } void ForwarderView::setSystem(ForwarderGenerator::System system) { m_controller.setGenerator(ForwarderGenerator::createForSystem(system)); auto types = m_controller.generator()->imageTypes(); m_images.clear(); m_images.resize(types.count()); m_ui.imageSelect->clear(); for (const auto& pair : types) { m_ui.imageSelect->addItem(pair.first); } m_ui.imageSelect->setEnabled(true); m_ui.imagePreview->setEnabled(true); m_ui.imageBrowse->setEnabled(true); m_ui.imagesLabel->setEnabled(true); m_ui.preferredLabel->setEnabled(true); m_ui.preferredWidth->setEnabled(true); m_ui.preferredX->setEnabled(true); m_ui.preferredHeight->setEnabled(true); } void ForwarderView::connectBrowseButton(QAbstractButton* button, QLineEdit* lineEdit, const QString& title, bool save, const QString& filter) { connect(button, &QAbstractButton::clicked, lineEdit, [this, lineEdit, save, title, filter]() { QString filename; if (save) { filename = GBAApp::app()->getSaveFileName(this, title, filter); } else { filename = GBAApp::app()->getOpenFileName(this, title, filter); } if (filename.isEmpty()) { return; } lineEdit->setText(filename); }); } void ForwarderView::selectImage() { QString filename = GBAApp::app()->getOpenFileName(this, tr("Select an image"), {}); if (filename.isEmpty()) { return; } QImage image(filename); if (image.isNull()) { return; } image = image.scaled(m_activeSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); m_ui.imagePreview->setPixmap(QPixmap::fromImage(image)); m_ui.useDefaultImage->setChecked(false); m_controller.generator()->setImage(m_currentImage, image); } void ForwarderView::setActiveImage(int index) { if (index < 0) { m_currentImage = -1; m_activeSize = QSize(); return; } if (!m_controller.generator()) { return; } auto types = m_controller.generator()->imageTypes(); if (index >= types.count()) { return; } m_currentImage = index; m_activeSize = types[index].second; m_ui.preferredWidth->setText(QString::number(m_activeSize.width())); m_ui.preferredHeight->setText(QString::number(m_activeSize.height())); m_ui.imagePreview->setMaximumSize(m_activeSize); m_ui.imagePreview->setPixmap(QPixmap::fromImage(m_controller.generator()->image(index))); } <commit_msg>Qt: I wrote a function for this...<commit_after>/* Copyright (c) 2013-2022 Jeffrey Pfau * * 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 "ForwarderView.h" #include <QMessageBox> #include <QResizeEvent> #include "ForwarderGenerator.h" #include "GBAApp.h" #include "utils.h" using namespace QGBA; ForwarderView::ForwarderView(QWidget* parent) : QDialog(parent) { m_ui.setupUi(this); connectBrowseButton(m_ui.romBrowse, m_ui.romFilename, tr("Select ROM file"), false, romFilters()); connectBrowseButton(m_ui.outputBrowse, m_ui.outputFilename, tr("Select output filename"), true); connectBrowseButton(m_ui.baseBrowse, m_ui.baseFilename, tr("Select base file")); connect(m_ui.romFilename, &QLineEdit::textChanged, this, &ForwarderView::validate); connect(m_ui.outputFilename, &QLineEdit::textChanged, this, &ForwarderView::validate); connect(m_ui.baseFilename, &QLineEdit::textChanged, this, &ForwarderView::validate); connect(m_ui.title, &QLineEdit::textChanged, this, &ForwarderView::validate); connect(m_ui.baseType, qOverload<int>(&QComboBox::currentIndexChanged), this, &ForwarderView::validate); connect(m_ui.imageSelect, qOverload<int>(&QComboBox::currentIndexChanged), this, &ForwarderView::setActiveImage); connect(m_ui.imageBrowse, &QAbstractButton::clicked, this, &ForwarderView::selectImage); connect(&m_controller, &ForwarderController::buildComplete, this, &QDialog::accept); connect(&m_controller, &ForwarderController::buildFailed, this, [this]() { QMessageBox* error = new QMessageBox(QMessageBox::Critical, tr("Build failed"), tr("Failed to build forwarder"), QMessageBox::Ok, this, Qt::Sheet); error->setAttribute(Qt::WA_DeleteOnClose); error->show(); }); connect(m_ui.system3DS, &QAbstractButton::clicked, this, [this]() { setSystem(ForwarderGenerator::System::N3DS); }); connect(m_ui.systemVita, &QAbstractButton::clicked, this, [this]() { setSystem(ForwarderGenerator::System::VITA); }); m_ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); connect(m_ui.buttonBox->button(QDialogButtonBox::Ok), &QAbstractButton::clicked, this, &ForwarderView::build); } void ForwarderView::build() { if (!m_controller.generator()) { return; } m_controller.generator()->setTitle(m_ui.title->text()); m_controller.generator()->setRom(m_ui.romFilename->text()); m_controller.startBuild(m_ui.outputFilename->text()); } void ForwarderView::validate() { bool valid = true; if (m_ui.romFilename->text().isEmpty()) { valid = false; } else if (!QFileInfo(m_ui.romFilename->text()).exists()) { valid = false; } if (m_ui.outputFilename->text().isEmpty()) { valid = false; } if (m_ui.title->text().isEmpty()) { valid = false; } if (!m_ui.system->checkedButton()) { valid = false; } if (m_ui.baseType->currentIndex() != 1) { valid = false; } m_ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid); } void ForwarderView::setSystem(ForwarderGenerator::System system) { m_controller.setGenerator(ForwarderGenerator::createForSystem(system)); auto types = m_controller.generator()->imageTypes(); m_images.clear(); m_images.resize(types.count()); m_ui.imageSelect->clear(); for (const auto& pair : types) { m_ui.imageSelect->addItem(pair.first); } m_ui.imageSelect->setEnabled(true); m_ui.imagePreview->setEnabled(true); m_ui.imageBrowse->setEnabled(true); m_ui.imagesLabel->setEnabled(true); m_ui.preferredLabel->setEnabled(true); m_ui.preferredWidth->setEnabled(true); m_ui.preferredX->setEnabled(true); m_ui.preferredHeight->setEnabled(true); } void ForwarderView::connectBrowseButton(QAbstractButton* button, QLineEdit* lineEdit, const QString& title, bool save, const QString& filter) { connect(button, &QAbstractButton::clicked, lineEdit, [this, lineEdit, save, title, filter]() { QString filename; if (save) { filename = GBAApp::app()->getSaveFileName(this, title, filter); } else { filename = GBAApp::app()->getOpenFileName(this, title, filter); } if (filename.isEmpty()) { return; } lineEdit->setText(filename); }); } void ForwarderView::selectImage() { QString filename = GBAApp::app()->getOpenFileName(this, tr("Select an image"), {}); if (filename.isEmpty()) { return; } QImage image(filename); if (image.isNull()) { return; } image = image.scaled(m_activeSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); m_ui.imagePreview->setPixmap(QPixmap::fromImage(image)); m_ui.useDefaultImage->setChecked(false); m_controller.generator()->setImage(m_currentImage, image); } void ForwarderView::setActiveImage(int index) { if (index < 0) { m_currentImage = -1; m_activeSize = QSize(); return; } if (!m_controller.generator()) { return; } auto types = m_controller.generator()->imageTypes(); if (index >= types.count()) { return; } m_currentImage = index; m_activeSize = types[index].second; m_ui.preferredWidth->setText(QString::number(m_activeSize.width())); m_ui.preferredHeight->setText(QString::number(m_activeSize.height())); m_ui.imagePreview->setMaximumSize(m_activeSize); m_ui.imagePreview->setPixmap(QPixmap::fromImage(m_controller.generator()->image(index))); } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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 "tensorflow/lite/micro/examples/hello_world/output_handler.h" #include "am_bsp.h" // NOLINT /* This function uses the device's LEDs to visually indicate the current y value. The y value is in the range -1 <= y <= 1. The LEDs (red, green, blue, and yellow) are physically lined up in the following order: [ R G B Y ] The following table represents how we will light the LEDs for different values: | Range | LEDs lit | | 0.75 <= y <= 1 | [ 0 0 1 1 ] | | 0 < y < 0.75 | [ 0 0 1 0 ] | | y = 0 | [ 0 0 0 0 ] | | -0.75 < y < 0 | [ 0 1 0 0 ] | | -1 <= y <= 0.75 | [ 1 1 0 0 ] | */ void HandleOutput(tflite::ErrorReporter* error_reporter, float x_value, float y_value) { // The first time this method runs, set up our LEDs correctly static bool is_initialized = false; if (!is_initialized) { // Setup LED's as outputs #ifdef AM_BSP_NUM_LEDS am_devices_led_array_init(am_bsp_psLEDs, AM_BSP_NUM_LEDS); am_devices_led_array_out(am_bsp_psLEDs, AM_BSP_NUM_LEDS, 0x00000000); #endif is_initialized = true; } // Set the LEDs to represent negative values if (y_value < 0) { // Clear unnecessary LEDs am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_GREEN); am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_YELLOW); // The blue LED is lit for all negative values am_devices_led_on(am_bsp_psLEDs, AM_BSP_LED_BLUE); // The red LED is lit in only some cases if (y_value <= -0.75) { am_devices_led_on(am_bsp_psLEDs, AM_BSP_LED_RED); } else { am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_RED); } // Set the LEDs to represent positive values } else if (y_value > 0) { // Clear unnecessary LEDs am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_RED); am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_BLUE); // The green LED is lit for all positive values am_devices_led_on(am_bsp_psLEDs, AM_BSP_LED_GREEN); // The yellow LED is lit in only some cases if (y_value >= 0.75) { am_devices_led_on(am_bsp_psLEDs, AM_BSP_LED_YELLOW); } else { am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_YELLOW); } } // Log the current X and Y values TF_LITE_REPORT_ERROR(error_reporter, "x_value: %f, y_value: %f\n", x_value, y_value); } <commit_msg>Update output_handler.cc<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may 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 "tensorflow/lite/micro/examples/hello_world/output_handler.h" #include "am_bsp.h" // NOLINT /* This function uses the device's LEDs to visually indicate the current y value. The y value is in the range -1 <= y <= 1. The LEDs (red, green, blue, and yellow) are physically lined up in the following order: [ R B G Y ] The following table represents how we will light the LEDs for different values: | Range | LEDs lit | | 0.75 <= y <= 1 | [ 0 0 1 1 ] | | 0 < y < 0.75 | [ 0 0 1 0 ] | | y = 0 | [ 0 0 0 0 ] | | -0.75 < y < 0 | [ 0 1 0 0 ] | | -1 <= y <= 0.75 | [ 1 1 0 0 ] | */ void HandleOutput(tflite::ErrorReporter* error_reporter, float x_value, float y_value) { // The first time this method runs, set up our LEDs correctly static bool is_initialized = false; if (!is_initialized) { // Setup LED's as outputs #ifdef AM_BSP_NUM_LEDS am_devices_led_array_init(am_bsp_psLEDs, AM_BSP_NUM_LEDS); am_devices_led_array_out(am_bsp_psLEDs, AM_BSP_NUM_LEDS, 0x00000000); #endif is_initialized = true; } // Set the LEDs to represent negative values if (y_value < 0) { // Clear unnecessary LEDs am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_GREEN); am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_YELLOW); // The blue LED is lit for all negative values am_devices_led_on(am_bsp_psLEDs, AM_BSP_LED_BLUE); // The red LED is lit in only some cases if (y_value <= -0.75) { am_devices_led_on(am_bsp_psLEDs, AM_BSP_LED_RED); } else { am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_RED); } // Set the LEDs to represent positive values } else if (y_value > 0) { // Clear unnecessary LEDs am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_RED); am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_BLUE); // The green LED is lit for all positive values am_devices_led_on(am_bsp_psLEDs, AM_BSP_LED_GREEN); // The yellow LED is lit in only some cases if (y_value >= 0.75) { am_devices_led_on(am_bsp_psLEDs, AM_BSP_LED_YELLOW); } else { am_devices_led_off(am_bsp_psLEDs, AM_BSP_LED_YELLOW); } } // Log the current X and Y values TF_LITE_REPORT_ERROR(error_reporter, "x_value: %f, y_value: %f\n", x_value, y_value); } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright(C) 2014 Naoya Murakami <naoya@createfield.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 <string.h> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include <stdexcept> #include <vector> #include <unicode/normlzr.h> #include <mecab.h> #include <re2/re2.h> #include <wn.h> #include <google/gflags.h> DEFINE_string(input, "", "Input file path"); DEFINE_string(pre_filter, "(<[^>]*>)|\\\\n|\\\\r|\\\\t|([\\\\,.;:&^/\\-\\#'\"\\(\\)\\[\\]{}])", "Regular expresion pattern to input string"); DEFINE_bool(no_normalize, false, "Don't use NFKC normalize"); DEFINE_bool(no_tokenize, false, "Don't use tokenize"); DEFINE_string(mecab_dic, "", "Specifying mecab dictionary path"); DEFINE_bool(use_baseform, false, "Use baseform by MeCab dictionary"); DEFINE_string(token_filter, "", "Regular expresion pattern to token string"); DEFINE_bool(use_wordnet, false, "Use baseform by WordNet"); DEFINE_bool(cut_prolong, false, "Cut prolong if token have over 3 characters"); DEFINE_bool(h, false, "Help message"); #define MECAB_LIMIT 900000 using namespace std; string normalize(const string str) { icu::UnicodeString src; icu::UnicodeString dest; src = str.c_str(); UErrorCode status; status = U_ZERO_ERROR; Normalizer::normalize(src, UNORM_NFKC, 0, dest, status); if(U_FAILURE(status)) { throw runtime_error("Unicode normalization failed"); } string result; dest.toUTF8String(result); transform(result.begin(), result.end(), result.begin(), ::tolower); return result; } static char * right_trim(char *s, char del) { int i; int count = 0; if ( s == NULL ) { return NULL; } i = strlen(s); while ( --i >= 0 && s[i] == del ) count++; if (i == 0) { s[i] = '\0'; } else { s[i+1] = '\0'; } return s; } /* utf8_fix_pos utf8文字列じゃなければ、3バイト以内にutf8があるか判定する */ unsigned int utf8_fix_pos(const string str, unsigned int start, unsigned int end) { unsigned int pos; unsigned char lead; int char_size; for (pos = end; pos > start && pos > end - 3; pos--) { lead = str[pos]; if (lead < 0x80) { char_size = 1; } else if (lead < 0xE0) { char_size = 2; } else if (lead < 0xF0) { char_size = 3; } else { char_size = 4; } if(char_size == 1 || char_size == 3){ return pos; } } return end; } /* range_rfind_punct utf8文字列の範囲内を末尾から区切り文字、半角スペース、改行コード、 日本語区切り文字を探す。 見つかればその位置。見つからなければ、末尾の位置。 */ int range_rfind_punct(const string str, unsigned int start, unsigned int end) { unsigned int pos; unsigned char lead; int char_size; for (pos = end; pos > start; pos -= char_size) { lead = str[pos]; if (lead < 0x80) { char_size = 1; } else if (lead < 0xE0) { char_size = 2; } else if (lead < 0xF0) { char_size = 3; } else { char_size = 4; } if ((lead >= 0x20 && lead < 0x2f) || (lead >= 0x3a && lead <= 0x40) || (lead >= 0x5b && lead <= 0x60) || (lead >= 0x7b && lead <= 0x7d) || (lead >= 0x0a && lead <= 0x0d) || str.substr(pos, char_size) == "。" || str.substr(pos, char_size) == "、" || str.substr(pos, char_size) == "「" || str.substr(pos, char_size) == "」" || str.substr(pos, char_size) == "・" ) { return pos; } } lead = str[end]; if (lead < 0x80) { char_size = 1; } else if (lead < 0xE0) { char_size = 2; } else if (lead < 0xF0) { char_size = 3; } else { char_size = 4; } if(char_size == 2 || char_size == 4){ pos = utf8_fix_pos(str, start, end); return pos; } return end; } string tokenize(const string str, const string mecab_dic, bool baseform) { mecab_t *mecab = NULL; string mecab_option; if(baseform){ mecab_option = "-F%f[6]\\s -E\\n"; } else { mecab_option = "-Owakati"; } if(mecab_dic.length() > 0){ mecab_option += " -d " + mecab_dic; } mecab = mecab_new2(mecab_option.c_str()); string result; if(str.length() < MECAB_LIMIT) { result = mecab_sparse_tostr2(mecab, str.c_str(), str.length()); result = right_trim((char *)result.c_str(), '\n'); } else { unsigned int punct_pos = 0; unsigned int start = 0; unsigned int end = MECAB_LIMIT; unsigned int split_len; while(end < str.length()){ punct_pos = range_rfind_punct(str, start, end); split_len = punct_pos - start; result += mecab_sparse_tostr2(mecab, str.c_str() + start, split_len); result = right_trim((char *)result.c_str(), '\n'); start = punct_pos; end = start + MECAB_LIMIT; } split_len = str.length() - start; result += mecab_sparse_tostr2(mecab, str.c_str() + start, split_len); } mecab_destroy(mecab); return result; } string string_filter(string str, const char *pattern) { if(strcmp(pattern, "") != 0){ re2::RE2::GlobalReplace(&str, pattern, ""); } return str; } vector<string> split(const string &str, char delim){ vector<string> res; size_t current = 0, found; while((found = str.find_first_of(delim, current)) != string::npos){ res.push_back(string(str, current, found - current)); current = found + 1; } res.push_back(string(str, current, str.size() - current)); return res; } string token_filter(const string str, const char *pattern, bool wordnet, bool prolong) { vector<string> result_array; result_array = split(str, ' '); string result; for(unsigned int i = 0; i < result_array.size(); ++i ) { char *buf; buf = (char *)result_array[i].c_str(); if(wordnet){ int pos; char *morph; if (wninit() == -1){ return str; } //pos 1:NOUN 2:VERB 3:ADJECTIVE 4:ADVERB 5:ADJECTIVE_SATELITE for(pos = 5; pos >= 1; pos--){ morph = morphstr(buf, pos); if(morph){ buf = morph; break; } } } bool ret = false; string string_buf = buf; if(prolong) { if(string_buf.length() >= 12 ){ string tail_buf = string_buf.substr(string_buf.length()-3, 3); if(tail_buf == "ー" || tail_buf == "ー"){ string_buf = string_buf.substr(0, string_buf.length()-3); } } } if(strcmp(pattern, "") != 0){ ret = re2::RE2::GlobalReplace(&string_buf, pattern, ""); } result += string_buf; if(i < result_array.size() && ret == false){ result += " "; } } return result; } int string-splitter(string str) { str = string_filter(str, FLAGS_pre_filter.c_str()); if (!FLAGS_no_normalize) { str = normalize(str); } if (!FLAGS_no_tokenize) { str = tokenize(str, FLAGS_mecab_dic, FLAGS_use_baseform); } str = token_filter(str, FLAGS_token_filter.c_str(), FLAGS_use_wordnet, FLAGS_cut_prolong); cout << str.c_str() << endl; return 0; } int main(int argc,char **argv) { google::ParseCommandLineFlags(&argc, &argv, true); if(FLAGS_h == true){ printf(" --iuput : Input file path\n"); printf(" --pre_filter : Regular expresion pattern to input string\n"); printf(" --no_normalize : Don't use NFKC normalize\n"); printf(" --no_tokenize : Don't use tokenize\n"); printf(" --mecab_dic : Specifying mecab dictionary path\n"); printf(" --use_baseform : Convert baseform by MeCab dictionary\n"); printf(" --token_filter : Regular expresion pattern to token string\n"); printf(" --use_wordndet : Convert baseform by WordNet\n"); printf(" --cut_prolong : Cut prolong if token have over 3 characters\n"); exit(0); } string str; if(FLAGS_input == ""){ while(getline(cin, str)){ if(str == "EOS"){ break; } string-splitter(str); } } else { ifstream ifs(FLAGS_input.c_str()); if(ifs.fail()) { cerr << "File do not exist.\n"; exit(0); } while(getline(ifs, str)){ string-splitter(str); } } return 0; } <commit_msg>fix function includes hyphen<commit_after>/* The MIT License (MIT) Copyright(C) 2014 Naoya Murakami <naoya@createfield.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 <string.h> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include <stdexcept> #include <vector> #include <unicode/normlzr.h> #include <mecab.h> #include <re2/re2.h> #include <wn.h> #include <google/gflags.h> DEFINE_string(input, "", "Input file path"); DEFINE_string(pre_filter, "(<[^>]*>)|\\\\n|\\\\r|\\\\t|([\\\\,.;:&^/\\-\\#'\"\\(\\)\\[\\]{}])", "Regular expresion pattern to input string"); DEFINE_bool(no_normalize, false, "Don't use NFKC normalize"); DEFINE_bool(no_tokenize, false, "Don't use tokenize"); DEFINE_string(mecab_dic, "", "Specifying mecab dictionary path"); DEFINE_bool(use_baseform, false, "Use baseform by MeCab dictionary"); DEFINE_string(token_filter, "", "Regular expresion pattern to token string"); DEFINE_bool(use_wordnet, false, "Use baseform by WordNet"); DEFINE_bool(cut_prolong, false, "Cut prolong if token have over 3 characters"); DEFINE_bool(h, false, "Help message"); #define MECAB_LIMIT 900000 using namespace std; string normalize(const string str) { icu::UnicodeString src; icu::UnicodeString dest; src = str.c_str(); UErrorCode status; status = U_ZERO_ERROR; Normalizer::normalize(src, UNORM_NFKC, 0, dest, status); if(U_FAILURE(status)) { throw runtime_error("Unicode normalization failed"); } string result; dest.toUTF8String(result); transform(result.begin(), result.end(), result.begin(), ::tolower); return result; } static char * right_trim(char *s, char del) { int i; int count = 0; if ( s == NULL ) { return NULL; } i = strlen(s); while ( --i >= 0 && s[i] == del ) count++; if (i == 0) { s[i] = '\0'; } else { s[i+1] = '\0'; } return s; } /* utf8_fix_pos utf8文字列じゃなければ、3バイト以内にutf8があるか判定する */ unsigned int utf8_fix_pos(const string str, unsigned int start, unsigned int end) { unsigned int pos; unsigned char lead; int char_size; for (pos = end; pos > start && pos > end - 3; pos--) { lead = str[pos]; if (lead < 0x80) { char_size = 1; } else if (lead < 0xE0) { char_size = 2; } else if (lead < 0xF0) { char_size = 3; } else { char_size = 4; } if(char_size == 1 || char_size == 3){ return pos; } } return end; } /* range_rfind_punct utf8文字列の範囲内を末尾から区切り文字、半角スペース、改行コード、 日本語区切り文字を探す。 見つかればその位置。見つからなければ、末尾の位置。 */ int range_rfind_punct(const string str, unsigned int start, unsigned int end) { unsigned int pos; unsigned char lead; int char_size; for (pos = end; pos > start; pos -= char_size) { lead = str[pos]; if (lead < 0x80) { char_size = 1; } else if (lead < 0xE0) { char_size = 2; } else if (lead < 0xF0) { char_size = 3; } else { char_size = 4; } if ((lead >= 0x20 && lead < 0x2f) || (lead >= 0x3a && lead <= 0x40) || (lead >= 0x5b && lead <= 0x60) || (lead >= 0x7b && lead <= 0x7d) || (lead >= 0x0a && lead <= 0x0d) || str.substr(pos, char_size) == "。" || str.substr(pos, char_size) == "、" || str.substr(pos, char_size) == "「" || str.substr(pos, char_size) == "」" || str.substr(pos, char_size) == "・" ) { return pos; } } lead = str[end]; if (lead < 0x80) { char_size = 1; } else if (lead < 0xE0) { char_size = 2; } else if (lead < 0xF0) { char_size = 3; } else { char_size = 4; } if(char_size == 2 || char_size == 4){ pos = utf8_fix_pos(str, start, end); return pos; } return end; } string tokenize(const string str, const string mecab_dic, bool baseform) { mecab_t *mecab = NULL; string mecab_option; if(baseform){ mecab_option = "-F%f[6]\\s -E\\n"; } else { mecab_option = "-Owakati"; } if(mecab_dic.length() > 0){ mecab_option += " -d " + mecab_dic; } mecab = mecab_new2(mecab_option.c_str()); string result; if(str.length() < MECAB_LIMIT) { result = mecab_sparse_tostr2(mecab, str.c_str(), str.length()); result = right_trim((char *)result.c_str(), '\n'); } else { unsigned int punct_pos = 0; unsigned int start = 0; unsigned int end = MECAB_LIMIT; unsigned int split_len; while(end < str.length()){ punct_pos = range_rfind_punct(str, start, end); split_len = punct_pos - start; result += mecab_sparse_tostr2(mecab, str.c_str() + start, split_len); result = right_trim((char *)result.c_str(), '\n'); start = punct_pos; end = start + MECAB_LIMIT; } split_len = str.length() - start; result += mecab_sparse_tostr2(mecab, str.c_str() + start, split_len); } mecab_destroy(mecab); return result; } string string_filter(string str, const char *pattern) { if(strcmp(pattern, "") != 0){ re2::RE2::GlobalReplace(&str, pattern, ""); } return str; } vector<string> split(const string &str, char delim){ vector<string> res; size_t current = 0, found; while((found = str.find_first_of(delim, current)) != string::npos){ res.push_back(string(str, current, found - current)); current = found + 1; } res.push_back(string(str, current, str.size() - current)); return res; } string token_filter(const string str, const char *pattern, bool wordnet, bool prolong) { vector<string> result_array; result_array = split(str, ' '); string result; for(unsigned int i = 0; i < result_array.size(); ++i ) { char *buf; buf = (char *)result_array[i].c_str(); if(wordnet){ int pos; char *morph; if (wninit() == -1){ return str; } //pos 1:NOUN 2:VERB 3:ADJECTIVE 4:ADVERB 5:ADJECTIVE_SATELITE for(pos = 5; pos >= 1; pos--){ morph = morphstr(buf, pos); if(morph){ buf = morph; break; } } } bool ret = false; string string_buf = buf; if(prolong) { if(string_buf.length() >= 12 ){ string tail_buf = string_buf.substr(string_buf.length()-3, 3); if(tail_buf == "ー" || tail_buf == "ー"){ string_buf = string_buf.substr(0, string_buf.length()-3); } } } if(strcmp(pattern, "") != 0){ ret = re2::RE2::GlobalReplace(&string_buf, pattern, ""); } result += string_buf; if(i < result_array.size() && ret == false){ result += " "; } } return result; } int string_splitter(string str) { str = string_filter(str, FLAGS_pre_filter.c_str()); if (!FLAGS_no_normalize) { str = normalize(str); } if (!FLAGS_no_tokenize) { str = tokenize(str, FLAGS_mecab_dic, FLAGS_use_baseform); } str = token_filter(str, FLAGS_token_filter.c_str(), FLAGS_use_wordnet, FLAGS_cut_prolong); cout << str.c_str() << endl; return 0; } int main(int argc,char **argv) { google::ParseCommandLineFlags(&argc, &argv, true); if(FLAGS_h == true){ printf(" --iuput : Input file path\n"); printf(" --pre_filter : Regular expresion pattern to input string\n"); printf(" --no_normalize : Don't use NFKC normalize\n"); printf(" --no_tokenize : Don't use tokenize\n"); printf(" --mecab_dic : Specifying mecab dictionary path\n"); printf(" --use_baseform : Convert baseform by MeCab dictionary\n"); printf(" --token_filter : Regular expresion pattern to token string\n"); printf(" --use_wordndet : Convert baseform by WordNet\n"); printf(" --cut_prolong : Cut prolong if token have over 3 characters\n"); exit(0); } string str; if(FLAGS_input == ""){ while(getline(cin, str)){ if(str == "EOS"){ break; } string_splitter(str); } } else { ifstream ifs(FLAGS_input.c_str()); if(ifs.fail()) { cerr << "File do not exist.\n"; exit(0); } while(getline(ifs, str)){ string_splitter(str); } } return 0; } <|endoftext|>
<commit_before>#include "strings.h" BOOST_AUTO_TEST_CASE(std_string_literals) { using namespace std::string_literals; auto s1{"Hello, world!"s}; auto s2{L"Hello, world!"s}; auto s3{u"Hello, world!"s}; auto s4{U"Hello, world!"s}; BOOST_REQUIRE((std::is_same_v<decltype(s1), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s2), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s3), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s4), XXX>)); } BOOST_AUTO_TEST_CASE(std_string_variants) { BOOST_REQUIRE((std::is_same_v<std::basic_string<char>, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string, std::basic_string<XXX>>)); BOOST_REQUIRE((std::is_same_v<std::wstring, std::basic_string<XXX>>)); BOOST_REQUIRE((std::is_same_v<std::u16string, std::basic_string<XXX>>)); BOOST_REQUIRE((std::is_same_v<std::u32string, std::basic_string<XXX>>)); } BOOST_AUTO_TEST_CASE(std_string_related_types) { BOOST_REQUIRE((std::is_same_v<std::string::traits_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::value_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::reference, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::const_reference, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::reverse_iterator, std::reverse_iterator<XXX>>)); BOOST_REQUIRE((std::is_same_v<std::string::const_reverse_iterator, std::reverse_iterator<XXX>>)); } BOOST_AUTO_TEST_CASE(std_string_constructors) { std::string const s1; BOOST_REQUIRE_EQUAL(xxx, s1.length()); std::string const s2{5, 'E'}; BOOST_REQUIRE_EQUAL(xxx, s2.length()); std::string const s3{s2}; BOOST_REQUIRE_EQUAL(xxx, s3.length()); std::string const s4{s2, 1}; BOOST_REQUIRE_EQUAL(xxx, s4.length()); std::string const hw{"Hello, world!"}; std::string const s5{hw, 1, 4}; BOOST_REQUIRE_EQUAL(xxx, s5); std::string const s6{"Hello, world!"}; BOOST_REQUIRE_EQUAL(xxx, s6.length()); std::string const s7{"Hello, world!", 5}; BOOST_REQUIRE_EQUAL(xxx, s7); std::string const s8{s7.begin(), s7.begin() + 1}; BOOST_REQUIRE_EQUAL(xxx, s8); std::string const s9{'H', 'e', 'l', 'l', 'o'}; BOOST_REQUIRE_EQUAL(xxx, s9); } BOOST_AUTO_TEST_CASE(std_string_accessors) { std::string const s{"Hello, world!"}; BOOST_REQUIRE_EQUAL(xxx, s[0]); BOOST_REQUIRE_EQUAL('w', s.at(xxx)); BOOST_REQUIRE_THROW(s.at(1000), XXX); BOOST_REQUIRE_EQUAL(xxx, s.front()); BOOST_REQUIRE_EQUAL(xxx, s.back()); BOOST_REQUIRE((std::is_same_v<decltype(s.data()), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s.c_str()), XXX>)); } BOOST_AUTO_TEST_CASE(string_iterators) { std::string const s{"Hello, world!"}; BOOST_REQUIRE((std::is_same_v<decltype(s.begin()), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s.cbegin()), XXX>)); BOOST_REQUIRE_EQUAL(xxx, *s.begin()); BOOST_REQUIRE_EQUAL(xxx, *(s.end() - 1)); BOOST_REQUIRE_EQUAL(xxx, *s.rbegin()); BOOST_REQUIRE_EQUAL(xxx, *(s.rend() - 1)); } BOOST_AUTO_TEST_CASE(std_string_capacity) { std::string s{"Hello, world!"}; BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_EQUAL(xxx, s.empty()); BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity()); s += s; s = "Hello, world!"; BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity()); s.shrink_to_fit(); BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity()); s.reserve(1024); BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_EQUAL(xxx, s.capacity()); } BOOST_AUTO_TEST_CASE(std_string_clear) { std::string s{"Hello, world!"}; s.clear(); BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_EQUAL(xxx, s.empty()); BOOST_REQUIRE_GE(s.capacity(), static_cast<std::string::size_type>(xxx)); } BOOST_AUTO_TEST_CASE(std_string_insert) { using namespace std::string_literals; std::string s2{"Bob"}; auto res1 = s2.insert(1, "illy B"); BOOST_REQUIRE((std::is_same_v<decltype(res1), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s2); auto res2 = s2.insert(0, 2, '-'); BOOST_REQUIRE((std::is_same_v<decltype(res2), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s2); auto res3 = s2.insert(2, "Hello, world!", 7); BOOST_REQUIRE((std::is_same_v<decltype(res3), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s2); std::string s3{"Hello, world!"}; std::string s4{"big, fat "}; auto res4 = s3.insert(7, s4); BOOST_REQUIRE((std::is_same_v<decltype(res4), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s3); std::string s5{"Hello, world!"}; auto res5 = s5.insert(7, s4, xxx, 3); BOOST_REQUIRE((std::is_same_v<decltype(res5), XXX>)); BOOST_REQUIRE_EQUAL("Hello, fat world!"s, s5); std::string s6{"Hello? "}; auto res6 = s5.insert<std::string::iterator>(s5.begin(), s6.begin(), xxx); BOOST_REQUIRE((std::is_same_v<decltype(res6), XXX>)); BOOST_REQUIRE_EQUAL("Hello? Hello, fat world!"s, s5); BOOST_REQUIRE_EQUAL(xxx, *res6); std::string s7{", world"}; auto res7 = s7.insert(0, {'H', 'e', 'l', 'l', 'o'}); BOOST_REQUIRE((std::is_same_v<decltype(res7), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s7); } BOOST_AUTO_TEST_CASE(std_string_erase) { using namespace std::string_literals; std::string s1{"Hello, world!"}; s1.erase(5); BOOST_REQUIRE_EQUAL(xxx, s1); std::string s2{"Hello, world!"}; s2.erase(5, 1); BOOST_REQUIRE_EQUAL(xxx, s2); std::string s3{"Hello, world!"}; s3.erase(s3.end() - 1); BOOST_REQUIRE_EQUAL(xxx, s3); std::string s4{"Hello, world!"}; s4.erase(xxx, s4.end() - 1); BOOST_REQUIRE_EQUAL("H!"s, s4); } BOOST_AUTO_TEST_CASE(std_string_push_back) { using namespace std::string_literals; std::string s{"<"}; s.push_back(xxx); BOOST_REQUIRE_EQUAL("<>", s); } BOOST_AUTO_TEST_CASE(std_string_pop_back) { using namespace std::string_literals; std::string s{"[]"}; s.pop_back(); BOOST_REQUIRE_EQUAL(xxx, s); } BOOST_AUTO_TEST_CASE(std_string_append) { } BOOST_AUTO_TEST_CASE(std_string_operators) { } BOOST_AUTO_TEST_CASE(std_string_compare) { } BOOST_AUTO_TEST_CASE(std_string_replace) { } BOOST_AUTO_TEST_CASE(std_string_substr) { } BOOST_AUTO_TEST_CASE(std_string_copy) { } BOOST_AUTO_TEST_CASE(std_string_resize) { } BOOST_AUTO_TEST_CASE(std_string_swap) { } BOOST_AUTO_TEST_CASE(std_string_find) { } BOOST_AUTO_TEST_CASE(std_string_rfind) { } BOOST_AUTO_TEST_CASE(std_string_find_first_of) { } BOOST_AUTO_TEST_CASE(std_string_find_first_not_of) { } BOOST_AUTO_TEST_CASE(std_string_find_last_of) { } BOOST_AUTO_TEST_CASE(std_string_find_last_not_of) { } BOOST_AUTO_TEST_CASE(std_string_conversions) { } BOOST_AUTO_TEST_CASE(std_string_allocators) { BOOST_REQUIRE((std::is_same_v<std::string::allocator_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::size_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::difference_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::pointer, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::const_pointer, XXX>)); } <commit_msg>Add std::string::append test case<commit_after>#include "strings.h" BOOST_AUTO_TEST_CASE(std_string_literals) { using namespace std::string_literals; auto s1{"Hello, world!"s}; auto s2{L"Hello, world!"s}; auto s3{u"Hello, world!"s}; auto s4{U"Hello, world!"s}; BOOST_REQUIRE((std::is_same_v<decltype(s1), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s2), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s3), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s4), XXX>)); } BOOST_AUTO_TEST_CASE(std_string_variants) { BOOST_REQUIRE((std::is_same_v<std::basic_string<char>, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string, std::basic_string<XXX>>)); BOOST_REQUIRE((std::is_same_v<std::wstring, std::basic_string<XXX>>)); BOOST_REQUIRE((std::is_same_v<std::u16string, std::basic_string<XXX>>)); BOOST_REQUIRE((std::is_same_v<std::u32string, std::basic_string<XXX>>)); } BOOST_AUTO_TEST_CASE(std_string_related_types) { BOOST_REQUIRE((std::is_same_v<std::string::traits_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::value_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::reference, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::const_reference, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::reverse_iterator, std::reverse_iterator<XXX>>)); BOOST_REQUIRE((std::is_same_v<std::string::const_reverse_iterator, std::reverse_iterator<XXX>>)); } BOOST_AUTO_TEST_CASE(std_string_constructors) { std::string const s1; BOOST_REQUIRE_EQUAL(xxx, s1.length()); std::string const s2{5, 'E'}; BOOST_REQUIRE_EQUAL(xxx, s2.length()); std::string const s3{s2}; BOOST_REQUIRE_EQUAL(xxx, s3.length()); std::string const s4{s2, 1}; BOOST_REQUIRE_EQUAL(xxx, s4.length()); std::string const hw{"Hello, world!"}; std::string const s5{hw, 1, 4}; BOOST_REQUIRE_EQUAL(xxx, s5); std::string const s6{"Hello, world!"}; BOOST_REQUIRE_EQUAL(xxx, s6.length()); std::string const s7{"Hello, world!", 5}; BOOST_REQUIRE_EQUAL(xxx, s7); std::string const s8{s7.begin(), s7.begin() + 1}; BOOST_REQUIRE_EQUAL(xxx, s8); std::string const s9{'H', 'e', 'l', 'l', 'o'}; BOOST_REQUIRE_EQUAL(xxx, s9); } BOOST_AUTO_TEST_CASE(std_string_accessors) { std::string const s{"Hello, world!"}; BOOST_REQUIRE_EQUAL(xxx, s[0]); BOOST_REQUIRE_EQUAL('w', s.at(xxx)); BOOST_REQUIRE_THROW(s.at(1000), XXX); BOOST_REQUIRE_EQUAL(xxx, s.front()); BOOST_REQUIRE_EQUAL(xxx, s.back()); BOOST_REQUIRE((std::is_same_v<decltype(s.data()), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s.c_str()), XXX>)); } BOOST_AUTO_TEST_CASE(string_iterators) { std::string const s{"Hello, world!"}; BOOST_REQUIRE((std::is_same_v<decltype(s.begin()), XXX>)); BOOST_REQUIRE((std::is_same_v<decltype(s.cbegin()), XXX>)); BOOST_REQUIRE_EQUAL(xxx, *s.begin()); BOOST_REQUIRE_EQUAL(xxx, *(s.end() - 1)); BOOST_REQUIRE_EQUAL(xxx, *s.rbegin()); BOOST_REQUIRE_EQUAL(xxx, *(s.rend() - 1)); } BOOST_AUTO_TEST_CASE(std_string_capacity) { std::string s{"Hello, world!"}; BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_EQUAL(xxx, s.empty()); BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity()); s += s; s = "Hello, world!"; BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity()); s.shrink_to_fit(); BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_GE(static_cast<std::string::size_type>(xxx), s.capacity()); s.reserve(1024); BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_EQUAL(xxx, s.capacity()); } BOOST_AUTO_TEST_CASE(std_string_clear) { std::string s{"Hello, world!"}; s.clear(); BOOST_REQUIRE_EQUAL(xxx, s.length()); BOOST_REQUIRE_EQUAL(xxx, s.empty()); BOOST_REQUIRE_GE(s.capacity(), static_cast<std::string::size_type>(xxx)); } BOOST_AUTO_TEST_CASE(std_string_insert) { using namespace std::string_literals; std::string s2{"Bob"}; auto res1 = s2.insert(1, "illy B"); BOOST_REQUIRE((std::is_same_v<decltype(res1), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s2); auto res2 = s2.insert(0, 2, '-'); BOOST_REQUIRE((std::is_same_v<decltype(res2), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s2); auto res3 = s2.insert(2, "Hello, world!", 7); BOOST_REQUIRE((std::is_same_v<decltype(res3), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s2); std::string s3{"Hello, world!"}; std::string s4{"big, fat "}; auto res4 = s3.insert(7, s4); BOOST_REQUIRE((std::is_same_v<decltype(res4), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s3); std::string s5{"Hello, world!"}; auto res5 = s5.insert(7, s4, xxx, 3); BOOST_REQUIRE((std::is_same_v<decltype(res5), XXX>)); BOOST_REQUIRE_EQUAL("Hello, fat world!"s, s5); std::string s6{"Hello? "}; auto res6 = s5.insert<std::string::iterator>(s5.begin(), s6.begin(), xxx); BOOST_REQUIRE((std::is_same_v<decltype(res6), XXX>)); BOOST_REQUIRE_EQUAL("Hello? Hello, fat world!"s, s5); BOOST_REQUIRE_EQUAL(xxx, *res6); std::string s7{", world"}; auto res7 = s7.insert(0, {'H', 'e', 'l', 'l', 'o'}); BOOST_REQUIRE((std::is_same_v<decltype(res7), XXX>)); BOOST_REQUIRE_EQUAL(xxx, s7); } BOOST_AUTO_TEST_CASE(std_string_erase) { using namespace std::string_literals; std::string s1{"Hello, world!"}; s1.erase(5); BOOST_REQUIRE_EQUAL(xxx, s1); std::string s2{"Hello, world!"}; s2.erase(5, 1); BOOST_REQUIRE_EQUAL(xxx, s2); std::string s3{"Hello, world!"}; s3.erase(s3.end() - 1); BOOST_REQUIRE_EQUAL(xxx, s3); std::string s4{"Hello, world!"}; s4.erase(xxx, s4.end() - 1); BOOST_REQUIRE_EQUAL("H!"s, s4); } BOOST_AUTO_TEST_CASE(std_string_push_back) { using namespace std::string_literals; std::string s{"<"}; s.push_back(xxx); BOOST_REQUIRE_EQUAL("<>"s, s); } BOOST_AUTO_TEST_CASE(std_string_pop_back) { std::string s{"[]"}; s.pop_back(); BOOST_REQUIRE_EQUAL(xxx, s); } BOOST_AUTO_TEST_CASE(std_string_append) { using namespace std::string_literals; std::string s1{"<["}; auto res1 = s1.append(xxx, 2); BOOST_REQUIRE((std::is_same_v<decltype(res1), XXX>)); BOOST_REQUIRE_EQUAL("<[]>"s, s1); std::string s2{"Foo"}; s2.append("bar"s); BOOST_REQUIRE_EQUAL(xxx, s2); std::string s3{"Meta"}; s3.append("Well, what about the--"s, xxx); BOOST_REQUIRE_EQUAL("Meta--"s, s3); std::string s4{"Wafer "}; s4.append("Something"s, 4, xxx); BOOST_REQUIRE_EQUAL("Wafer thin"s, s4); std::string s5{"The good "}; s5.append(" wicked witch", xxx); BOOST_REQUIRE_EQUAL("The good witch"s, s5); std::string s6{"Powdered "}; const char lit[] = "donut"; s6.append(std::begin(lit), xxx); BOOST_REQUIRE_EQUAL("Powdered donut"s, s6); std::string s7{"+"}; s7.append({ xxx, xxx, xxx }); BOOST_REQUIRE_EQUAL("+--+"s, s7); } BOOST_AUTO_TEST_CASE(std_string_operators) { } BOOST_AUTO_TEST_CASE(std_string_compare) { } BOOST_AUTO_TEST_CASE(std_string_replace) { } BOOST_AUTO_TEST_CASE(std_string_substr) { } BOOST_AUTO_TEST_CASE(std_string_copy) { } BOOST_AUTO_TEST_CASE(std_string_resize) { } BOOST_AUTO_TEST_CASE(std_string_swap) { } BOOST_AUTO_TEST_CASE(std_string_find) { } BOOST_AUTO_TEST_CASE(std_string_rfind) { } BOOST_AUTO_TEST_CASE(std_string_find_first_of) { } BOOST_AUTO_TEST_CASE(std_string_find_first_not_of) { } BOOST_AUTO_TEST_CASE(std_string_find_last_of) { } BOOST_AUTO_TEST_CASE(std_string_find_last_not_of) { } BOOST_AUTO_TEST_CASE(std_string_conversions) { } BOOST_AUTO_TEST_CASE(std_string_allocators) { BOOST_REQUIRE((std::is_same_v<std::string::allocator_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::size_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::difference_type, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::pointer, XXX>)); BOOST_REQUIRE((std::is_same_v<std::string::const_pointer, XXX>)); } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <ios> // template <class charT, class traits> class basic_ios // char narrow(char_type c, char dfault) const; #include <ios> #include <cassert> int main() { const std::ios ios(0); assert(ios.narrow('c', '*') == 'c'); assert(ios.narrow('\xFE', '*') == '*'); } <commit_msg>[libcxx] [test] Remove nonportable locale assumption in basic.ios.members/narrow.pass.cpp<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <ios> // template <class charT, class traits> class basic_ios // char narrow(char_type c, char dfault) const; #include <ios> #include <cassert> int main() { const std::wios ios(0); assert(ios.narrow(L'c', '*') == 'c'); assert(ios.narrow(L'\u203C', '*') == '*'); } <|endoftext|>
<commit_before>/* * Copyright 2018 Google, Inc. * * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __SYSTEMC_CORE_PROCESS_TYPES_HH__ #define __SYSTEMC_CORE_PROCESS_TYPES_HH__ #include "systemc/core/process.hh" #include "systemc/core/scheduler.hh" namespace sc_gem5 { class Method : public Process { public: Method(const char *name, ProcessFuncWrapper *func, bool _dynamic=false) : Process(name, func, _dynamic) {} const char *kind() const override { return "sc_method_process"; } sc_core::sc_curr_proc_kind procKind() const override { return sc_core::SC_METHOD_PROC_; } }; class Thread : public Process { public: Thread(const char *name, ProcessFuncWrapper *func, bool _dynamic=false) : Process(name, func, _dynamic), ctx(nullptr) {} ~Thread() { delete ctx; } const char *kind() const override { return "sc_thread_process"; } void throw_it(ExceptionWrapperBase &exc, bool inc_kids) override; sc_core::sc_curr_proc_kind procKind() const override { return sc_core::SC_THREAD_PROC_; } Fiber * fiber() override { if (!ctx) ctx = new Context(this, stackSize); return ctx; } private: class Context : public Fiber { public: Context(Thread *thread, size_t size) : Fiber(size), thread(thread) {} private: Thread *thread; void main() override { thread->_needsStart = false; thread->run(); thread->terminate(); } }; friend class Context; Context *ctx; }; class CThread : public Thread { public: CThread(const char *name, ProcessFuncWrapper *func, bool _dynamic=false) : Thread(name, func, _dynamic) { // We'll be in the initialization list now, but we shouldn't be. popListNode(); } const char *kind() const override { return "sc_cthread_process"; } sc_core::sc_curr_proc_kind procKind() const override { return sc_core::SC_CTHREAD_PROC_; } }; } // namespace sc_gem5 #endif //__SYSTEMC_CORE_PROCESS_TYPES_HH__ <commit_msg>systemc: When a thread completes, yield to the scheduler.<commit_after>/* * Copyright 2018 Google, Inc. * * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __SYSTEMC_CORE_PROCESS_TYPES_HH__ #define __SYSTEMC_CORE_PROCESS_TYPES_HH__ #include "systemc/core/process.hh" #include "systemc/core/scheduler.hh" namespace sc_gem5 { class Method : public Process { public: Method(const char *name, ProcessFuncWrapper *func, bool _dynamic=false) : Process(name, func, _dynamic) {} const char *kind() const override { return "sc_method_process"; } sc_core::sc_curr_proc_kind procKind() const override { return sc_core::SC_METHOD_PROC_; } }; class Thread : public Process { public: Thread(const char *name, ProcessFuncWrapper *func, bool _dynamic=false) : Process(name, func, _dynamic), ctx(nullptr) {} ~Thread() { delete ctx; } const char *kind() const override { return "sc_thread_process"; } void throw_it(ExceptionWrapperBase &exc, bool inc_kids) override; sc_core::sc_curr_proc_kind procKind() const override { return sc_core::SC_THREAD_PROC_; } Fiber * fiber() override { if (!ctx) ctx = new Context(this, stackSize); return ctx; } private: class Context : public Fiber { public: Context(Thread *thread, size_t size) : Fiber(size), thread(thread) {} private: Thread *thread; void main() override { thread->_needsStart = false; thread->run(); thread->terminate(); scheduler.yield(); } }; friend class Context; Context *ctx; }; class CThread : public Thread { public: CThread(const char *name, ProcessFuncWrapper *func, bool _dynamic=false) : Thread(name, func, _dynamic) { // We'll be in the initialization list now, but we shouldn't be. popListNode(); } const char *kind() const override { return "sc_cthread_process"; } sc_core::sc_curr_proc_kind procKind() const override { return sc_core::SC_CTHREAD_PROC_; } }; } // namespace sc_gem5 #endif //__SYSTEMC_CORE_PROCESS_TYPES_HH__ <|endoftext|>
<commit_before>#line 2 "togo/gfx/renderer/private.ipp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #pragma once #include <togo/config.hpp> #include <togo/gfx/types.hpp> #include <togo/gfx/renderer/types.hpp> #include <togo/gfx/renderer/private.hpp> namespace togo { namespace gfx { namespace renderer { #define TOGO_GFX_RENDERER_TEARDOWN_RA_(ra, destroy_func) \ if (renderer->ra._num > 0) { \ for (auto const& slot : renderer->ra._slots) { \ if (slot.id._value == ID_VALUE_NULL) { \ renderer::destroy_func(renderer, slot.id); \ } \ } \ } void teardown_base(gfx::Renderer* const renderer) { TOGO_GFX_RENDERER_TEARDOWN_RA_(_vertex_buffers, destroy_vertex_buffer); TOGO_GFX_RENDERER_TEARDOWN_RA_(_index_buffers, destroy_index_buffer); //TOGO_GFX_RENDERER_TEARDOWN_RA_(_textures, destroy_texture); //TOGO_GFX_RENDERER_TEARDOWN_RA_(_uniforms, destroy_uniform); //TOGO_GFX_RENDERER_TEARDOWN_RA_(_shaders, destroy_shader); } } // namespace renderer } // namespace gfx } // namespace togo <commit_msg>gfx/renderer/private: qualified renderer::teardown_base().<commit_after>#line 2 "togo/gfx/renderer/private.ipp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #pragma once #include <togo/config.hpp> #include <togo/gfx/types.hpp> #include <togo/gfx/renderer/types.hpp> #include <togo/gfx/renderer/private.hpp> namespace togo { namespace gfx { #define TOGO_GFX_RENDERER_TEARDOWN_RA_(ra, destroy_func) \ if (renderer->ra._num > 0) { \ for (auto const& slot : renderer->ra._slots) { \ if (slot.id._value == ID_VALUE_NULL) { \ renderer::destroy_func(renderer, slot.id); \ } \ } \ } void renderer::teardown_base(gfx::Renderer* const renderer) { TOGO_GFX_RENDERER_TEARDOWN_RA_(_vertex_buffers, destroy_vertex_buffer); TOGO_GFX_RENDERER_TEARDOWN_RA_(_index_buffers, destroy_index_buffer); //TOGO_GFX_RENDERER_TEARDOWN_RA_(_textures, destroy_texture); //TOGO_GFX_RENDERER_TEARDOWN_RA_(_uniforms, destroy_uniform); //TOGO_GFX_RENDERER_TEARDOWN_RA_(_shaders, destroy_shader); } } // namespace gfx } // namespace togo <|endoftext|>
<commit_before>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // It is important to use OrientedImages #include "itkOrientedImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" // The following three should be used in every CLI application #include "tubeMessage.h" #include "tubeCLIFilterWatcher.h" #include "tubeCLIProgressReporter.h" #include "itkTimeProbesCollectorBase.h" // Includes specific to this CLI application #include "itkAnisotropicDiffusiveRegistrationFilter.h" #include "itkVectorCastImageFilter.h" #include "itkWarpImageFilter.h" #include "itkLinearInterpolateImageFunction.h" #include "vtkSmartPointer.h" #include "vtkPolyDataReader.h" #include "vtkXMLPolyDataReader.h" // Must do a forward declaraction of DoIt before including // tubeCLIHelperFunctions template< class pixelT, unsigned int dimensionT > int DoIt( int argc, char * argv[] ); // Must include CLP before including tubeCLIHelperFunctions #include "tubeAnisotropicDiffusiveDeformableRegistrationCLP.h" // Includes tube::ParseArgsAndCallDoIt function #include "tubeCLIHelperFunctions.h" // Your code should be within the DoIt function... template< class pixelT, unsigned int dimensionT > int DoIt( int argc, char * argv[] ) { PARSE_ARGS; // The timeCollector is used to perform basic profiling of the components // of your algorithm. itk::TimeProbesCollectorBase timeCollector; // CLIProgressReporter is used to communicate progress with the Slicer GUI tube::CLIProgressReporter progressReporter( "AnisotropicDiffusiveDeformableRegistration", CLPProcessInformation ); progressReporter.Start(); // Typedefs const unsigned int ImageDimension = 3; typedef pixelT FixedPixelType; typedef pixelT MovingPixelType; typedef MovingPixelType OutputPixelType; typedef double VectorScalarType; typedef itk::Image< FixedPixelType, ImageDimension > FixedImageType; typedef itk::Image< MovingPixelType, ImageDimension > MovingImageType; typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType; typedef itk::Vector< VectorScalarType, ImageDimension > VectorType; typedef itk::Image< VectorType, ImageDimension > VectorImageType; typedef itk::Image< double, ImageDimension > WeightImageType; typedef itk::Image< VectorType, ImageDimension > FieldType; //-------------------------------------------------------- typedef itk::AnisotropicDiffusiveRegistrationFilter < FixedImageType, MovingImageType, FieldType > RegistrationType; typename RegistrationType::Pointer registrator = RegistrationType::New(); timeCollector.Start( "Loading input data" ); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typename FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); fixedImageReader->SetFileName( fixedImageFileName.c_str() ); try { fixedImageReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Reading volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } typename FixedImageType::Pointer fixed = fixedImageReader->GetOutput(); registrator->SetFixedImage( fixed ); typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; typename MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); movingImageReader->SetFileName( movingImageFileName.c_str() ); try { movingImageReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Reading volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } typename MovingImageType::Pointer moving = movingImageReader->GetOutput(); registrator->SetMovingImage( moving ); FieldType::Pointer initField = FieldType::New(); initField->SetSpacing( fixed->GetSpacing() ); initField->SetOrigin( fixed->GetOrigin() ); initField->SetLargestPossibleRegion( fixed->GetLargestPossibleRegion() ); initField->SetRequestedRegion( fixed->GetRequestedRegion() ); initField->SetBufferedRegion( fixed->GetBufferedRegion() ); initField->Allocate(); // fill initial deformation with zero vectors VectorType zeroVec; zeroVec.Fill( 0.0 ); initField->FillBuffer( zeroVec ); typedef itk::VectorCastImageFilter< FieldType, FieldType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput( initField ); caster->InPlaceOff(); registrator->SetInitialDeformationField( caster->GetOutput() ); if( organBoundaryFileName != "" ) { // do we have .vtk or .vtp models? std::string::size_type loc = organBoundaryFileName.find_last_of("."); if( loc == std::string::npos ) { tube::ErrorMessage( "Failed to find an extension for organ boundary" ); timeCollector.Report(); return EXIT_FAILURE; } std::string extension = organBoundaryFileName.substr(loc); typename RegistrationType::BorderSurfacePointer borderSurface = NULL; if ( extension == std::string(".vtk") ) { vtkSmartPointer< vtkPolyDataReader > polyDataReader = vtkPolyDataReader::New(); polyDataReader->SetFileName( organBoundaryFileName.c_str() ); polyDataReader->Update(); borderSurface = polyDataReader->GetOutput(); } else if ( extension == std::string(".vtp") ) { vtkSmartPointer< vtkXMLPolyDataReader > polyDataReader = vtkXMLPolyDataReader::New(); polyDataReader->SetFileName( organBoundaryFileName.c_str() ); polyDataReader->Update(); borderSurface = polyDataReader->GetOutput(); } if( !borderSurface ) { tube::ErrorMessage( "Reading polydata: unsuccessful" ); timeCollector.Report(); return EXIT_FAILURE; } registrator->SetBorderSurface( borderSurface ); } if( inputNormalVectorImageFileName != "" ) { typedef itk::ImageFileReader< VectorImageType > VectorImageReaderType; typename VectorImageReaderType::Pointer vectorImageReader = VectorImageReaderType::New(); vectorImageReader->SetFileName( inputNormalVectorImageFileName.c_str() ); try { vectorImageReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Reading volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } registrator->SetNormalVectorImage( vectorImageReader->GetOutput() ); } if( inputWeightImageFileName != "" ) { typedef itk::ImageFileReader< WeightImageType > WeightImageReaderType; typename WeightImageReaderType::Pointer weightImageReader = WeightImageReaderType::New(); weightImageReader->SetFileName( inputWeightImageFileName.c_str() ); try { weightImageReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Reading volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } registrator->SetWeightImage( weightImageReader->GetOutput() ); } timeCollector.Stop( "Loading input data" ); double progress = 0.1; progressReporter.Report( progress ); //------------------------------------------------------------- timeCollector.Start( "Registration" ); registrator->SetNumberOfIterations( numberOfIterations ); registrator->SetComputeRegularizationTerm( !doNotPerformRegularization ); registrator->SetUseAnisotropicRegularization( !doNotUseAnisotropicRegularization ); registrator->SetTimeStep( timeStep ); if( lambda > 0.0 ) { tube::ErrorMessage( "Lambda must be negative." ); timeCollector.Report(); return EXIT_FAILURE; } registrator->SetLambda( lambda ); tube::CLIFilterWatcher watchRegistration(registrator, "Anisotropic Diffusive Registration", CLPProcessInformation, 0.8, progress ); // warp moving image typedef itk::WarpImageFilter< MovingImageType, MovingImageType, FieldType > WarperType; typename WarperType::Pointer warper = WarperType::New(); typedef typename WarperType::CoordRepType CoordRepType; typedef itk::LinearInterpolateImageFunction<MovingImageType,CoordRepType> InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); warper->SetInput( moving ); warper->SetDeformationField( registrator->GetOutput() ); warper->SetInterpolator( interpolator ); warper->SetOutputSpacing( fixed->GetSpacing() ); warper->SetOutputOrigin( fixed->GetOrigin() ); warper->SetOutputDirection( fixed->GetDirection() ); warper->SetEdgePaddingValue( 0 ); // Update triggers the registration warper->Update(); timeCollector.Stop( "Registration" ); progress = 0.9; progressReporter.Report( progress ); // --------------------------------------------------------- timeCollector.Start( "Write outputs" ); if( outputDeformationFieldFileName != "" ) { typedef itk::ImageFileWriter< FieldType > FieldWriterType; typename FieldWriterType::Pointer fieldWriter = FieldWriterType::New(); fieldWriter->SetFileName( outputDeformationFieldFileName ); fieldWriter->SetInput( registrator->GetOutput() ); try { fieldWriter->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Writing volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } if( outputResampledImageFileName != "" ) { typedef itk::ImageFileWriter< MovingImageType > ImageWriterType; typename ImageWriterType::Pointer imageWriter = ImageWriterType::New(); imageWriter->SetFileName( outputResampledImageFileName ); imageWriter->SetInput( warper->GetOutput() ); try { imageWriter->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Writing volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } if( outputNormalVectorImageFileName != "" ) { typedef itk::ImageFileWriter< VectorImageType > VectorWriterType; typename VectorWriterType::Pointer vectorWriter = VectorWriterType::New(); vectorWriter->SetFileName( outputNormalVectorImageFileName ); vectorWriter->SetInput( registrator->GetNormalVectorImage() ); try { vectorWriter->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Writing volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } if( outputWeightImageFileName != "" ) { typedef itk::ImageFileWriter< WeightImageType > WeightWriterType; typename WeightWriterType::Pointer weightWriter = WeightWriterType::New(); weightWriter->SetFileName( outputWeightImageFileName ); weightWriter->SetInput( registrator->GetWeightImage() ); try { weightWriter->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Writing volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } timeCollector.Stop( "Write outputs" ); progress = 1.0; progressReporter.Report( progress ); progressReporter.End( ); timeCollector.Report(); return EXIT_SUCCESS; } // Main int main( int argc, char **argv ) { PARSE_ARGS; // You may need to update this line if, in the project's .xml CLI file, // you change the variable name for the inputVolume. return tube::ParseArgsAndCallDoIt( fixedImageFileName, argc, argv ); } <commit_msg>STYLE: Remove redundant typedef<commit_after>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // It is important to use OrientedImages #include "itkOrientedImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" // The following three should be used in every CLI application #include "tubeMessage.h" #include "tubeCLIFilterWatcher.h" #include "tubeCLIProgressReporter.h" #include "itkTimeProbesCollectorBase.h" // Includes specific to this CLI application #include "itkAnisotropicDiffusiveRegistrationFilter.h" #include "itkVectorCastImageFilter.h" #include "itkWarpImageFilter.h" #include "itkLinearInterpolateImageFunction.h" #include "vtkSmartPointer.h" #include "vtkPolyDataReader.h" #include "vtkXMLPolyDataReader.h" // Must do a forward declaraction of DoIt before including // tubeCLIHelperFunctions template< class pixelT, unsigned int dimensionT > int DoIt( int argc, char * argv[] ); // Must include CLP before including tubeCLIHelperFunctions #include "tubeAnisotropicDiffusiveDeformableRegistrationCLP.h" // Includes tube::ParseArgsAndCallDoIt function #include "tubeCLIHelperFunctions.h" // Your code should be within the DoIt function... template< class pixelT, unsigned int dimensionT > int DoIt( int argc, char * argv[] ) { PARSE_ARGS; // The timeCollector is used to perform basic profiling of the components // of your algorithm. itk::TimeProbesCollectorBase timeCollector; // CLIProgressReporter is used to communicate progress with the Slicer GUI tube::CLIProgressReporter progressReporter( "AnisotropicDiffusiveDeformableRegistration", CLPProcessInformation ); progressReporter.Start(); // Typedefs const unsigned int ImageDimension = 3; typedef pixelT FixedPixelType; typedef pixelT MovingPixelType; typedef MovingPixelType OutputPixelType; typedef double VectorScalarType; typedef itk::Image< FixedPixelType, ImageDimension > FixedImageType; typedef itk::Image< MovingPixelType, ImageDimension > MovingImageType; typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType; typedef itk::Vector< VectorScalarType, ImageDimension > VectorType; typedef itk::Image< VectorType, ImageDimension > VectorImageType; typedef itk::Image< double, ImageDimension > WeightImageType; //-------------------------------------------------------- typedef itk::AnisotropicDiffusiveRegistrationFilter < FixedImageType, MovingImageType, VectorImageType > RegistrationType; typename RegistrationType::Pointer registrator = RegistrationType::New(); timeCollector.Start( "Loading input data" ); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typename FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); fixedImageReader->SetFileName( fixedImageFileName.c_str() ); try { fixedImageReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Reading volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } typename FixedImageType::Pointer fixed = fixedImageReader->GetOutput(); registrator->SetFixedImage( fixed ); typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; typename MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); movingImageReader->SetFileName( movingImageFileName.c_str() ); try { movingImageReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Reading volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } typename MovingImageType::Pointer moving = movingImageReader->GetOutput(); registrator->SetMovingImage( moving ); VectorImageType::Pointer initField = VectorImageType::New(); initField->SetSpacing( fixed->GetSpacing() ); initField->SetOrigin( fixed->GetOrigin() ); initField->SetLargestPossibleRegion( fixed->GetLargestPossibleRegion() ); initField->SetRequestedRegion( fixed->GetRequestedRegion() ); initField->SetBufferedRegion( fixed->GetBufferedRegion() ); initField->Allocate(); // fill initial deformation with zero vectors VectorType zeroVec; zeroVec.Fill( 0.0 ); initField->FillBuffer( zeroVec ); typedef itk::VectorCastImageFilter< VectorImageType, VectorImageType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput( initField ); caster->InPlaceOff(); registrator->SetInitialDeformationField( caster->GetOutput() ); if( organBoundaryFileName != "" ) { // do we have .vtk or .vtp models? std::string::size_type loc = organBoundaryFileName.find_last_of("."); if( loc == std::string::npos ) { tube::ErrorMessage( "Failed to find an extension for organ boundary" ); timeCollector.Report(); return EXIT_FAILURE; } std::string extension = organBoundaryFileName.substr(loc); typename RegistrationType::BorderSurfacePointer borderSurface = NULL; if ( extension == std::string(".vtk") ) { vtkSmartPointer< vtkPolyDataReader > polyDataReader = vtkPolyDataReader::New(); polyDataReader->SetFileName( organBoundaryFileName.c_str() ); polyDataReader->Update(); borderSurface = polyDataReader->GetOutput(); } else if ( extension == std::string(".vtp") ) { vtkSmartPointer< vtkXMLPolyDataReader > polyDataReader = vtkXMLPolyDataReader::New(); polyDataReader->SetFileName( organBoundaryFileName.c_str() ); polyDataReader->Update(); borderSurface = polyDataReader->GetOutput(); } if( !borderSurface ) { tube::ErrorMessage( "Reading polydata: unsuccessful" ); timeCollector.Report(); return EXIT_FAILURE; } registrator->SetBorderSurface( borderSurface ); } if( inputNormalVectorImageFileName != "" ) { typedef itk::ImageFileReader< VectorImageType > VectorImageReaderType; typename VectorImageReaderType::Pointer vectorImageReader = VectorImageReaderType::New(); vectorImageReader->SetFileName( inputNormalVectorImageFileName.c_str() ); try { vectorImageReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Reading volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } registrator->SetNormalVectorImage( vectorImageReader->GetOutput() ); } if( inputWeightImageFileName != "" ) { typedef itk::ImageFileReader< WeightImageType > WeightImageReaderType; typename WeightImageReaderType::Pointer weightImageReader = WeightImageReaderType::New(); weightImageReader->SetFileName( inputWeightImageFileName.c_str() ); try { weightImageReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Reading volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } registrator->SetWeightImage( weightImageReader->GetOutput() ); } timeCollector.Stop( "Loading input data" ); double progress = 0.1; progressReporter.Report( progress ); //------------------------------------------------------------- timeCollector.Start( "Registration" ); registrator->SetNumberOfIterations( numberOfIterations ); registrator->SetComputeRegularizationTerm( !doNotPerformRegularization ); registrator->SetUseAnisotropicRegularization( !doNotUseAnisotropicRegularization ); registrator->SetTimeStep( timeStep ); if( lambda > 0.0 ) { tube::ErrorMessage( "Lambda must be negative." ); timeCollector.Report(); return EXIT_FAILURE; } registrator->SetLambda( lambda ); tube::CLIFilterWatcher watchRegistration(registrator, "Anisotropic Diffusive Registration", CLPProcessInformation, 0.8, progress ); // warp moving image typedef itk::WarpImageFilter< MovingImageType, MovingImageType, VectorImageType > WarperType; typename WarperType::Pointer warper = WarperType::New(); typedef typename WarperType::CoordRepType CoordRepType; typedef itk::LinearInterpolateImageFunction<MovingImageType,CoordRepType> InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); warper->SetInput( moving ); warper->SetDeformationField( registrator->GetOutput() ); warper->SetInterpolator( interpolator ); warper->SetOutputSpacing( fixed->GetSpacing() ); warper->SetOutputOrigin( fixed->GetOrigin() ); warper->SetOutputDirection( fixed->GetDirection() ); warper->SetEdgePaddingValue( 0 ); // Update triggers the registration warper->Update(); timeCollector.Stop( "Registration" ); progress = 0.9; progressReporter.Report( progress ); // --------------------------------------------------------- timeCollector.Start( "Write outputs" ); if( outputDeformationFieldFileName != "" ) { typedef itk::ImageFileWriter< VectorImageType > FieldWriterType; typename FieldWriterType::Pointer fieldWriter = FieldWriterType::New(); fieldWriter->SetFileName( outputDeformationFieldFileName ); fieldWriter->SetInput( registrator->GetOutput() ); try { fieldWriter->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Writing volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } if( outputResampledImageFileName != "" ) { typedef itk::ImageFileWriter< MovingImageType > ImageWriterType; typename ImageWriterType::Pointer imageWriter = ImageWriterType::New(); imageWriter->SetFileName( outputResampledImageFileName ); imageWriter->SetInput( warper->GetOutput() ); try { imageWriter->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Writing volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } if( outputNormalVectorImageFileName != "" ) { typedef itk::ImageFileWriter< VectorImageType > VectorWriterType; typename VectorWriterType::Pointer vectorWriter = VectorWriterType::New(); vectorWriter->SetFileName( outputNormalVectorImageFileName ); vectorWriter->SetInput( registrator->GetNormalVectorImage() ); try { vectorWriter->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Writing volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } if( outputWeightImageFileName != "" ) { typedef itk::ImageFileWriter< WeightImageType > WeightWriterType; typename WeightWriterType::Pointer weightWriter = WeightWriterType::New(); weightWriter->SetFileName( outputWeightImageFileName ); weightWriter->SetInput( registrator->GetWeightImage() ); try { weightWriter->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Writing volume: Exception caught: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } timeCollector.Stop( "Write outputs" ); progress = 1.0; progressReporter.Report( progress ); progressReporter.End( ); timeCollector.Report(); return EXIT_SUCCESS; } // Main int main( int argc, char **argv ) { PARSE_ARGS; // You may need to update this line if, in the project's .xml CLI file, // you change the variable name for the inputVolume. return tube::ParseArgsAndCallDoIt( fixedImageFileName, argc, argv ); } <|endoftext|>
<commit_before>#include "training/graph_group_sync.h" namespace marian { SyncGraphGroup::SyncGraphGroup(Ptr<Config> config) : GraphGroup(config), ExponentialSmoothing{options_->get<float>("exponential-smoothing")}, delay_{options_->get<size_t>("optimizer-delay")} { // @TODO: rename to something else; delay means delayed updated, not accumulation mpi_ = initMPI(/*multiThreaded=*/false); // when not running under MPI, this will be a fake object that represents a one-MPI-process setup devices_ = options_->getDevices(mpi_->myMPIRank(), mpi_->numMPIProcesses()); for(auto device : devices_) { auto graph = New<ExpressionGraph>(); graph->setDevice(device); graph->reserveWorkspaceMB(options_->get<size_t>("workspace")); graph->getBackend()->setClip(options_->get<float>("clip-gemm")); graphs_.push_back(graph); shardOpt_.push_back(Optimizer(options_)); builders_.push_back(models::from_config(options_, models::usage::training)); } // Note: We may well end up with only one MPI process or only one graph per worker. // This part of the code will not special-case any of this here. // Rather, it is assumed that the communicator knows to reduce unnecessary transfers to no-ops. comm_ = createCommunicator(graphs_, /*noNccl=*/options_->get<bool>("no-nccl", false), /*mpi=*/mpi_); } void SyncGraphGroup::setScheduler(Ptr<Scheduler> scheduler) /*override*/ { scheduler_ = scheduler; // optimizer has to be registered last to see changes of learning rate // @TODO: ^^Fix this comment. Either it refers to the scheduler, or it should be moved. Which one? scheduler_->registerTrainingObserver(scheduler_); for(auto opt : shardOpt_) scheduler_->registerTrainingObserver(opt); } void SyncGraphGroup::initialize(const Ptr<data::Batch>& exampleBatch) { // Initialize 0th graph with random weights in one forward step THREAD_GUARD({ builders_[0]->build(graphs_[0], exampleBatch); graphs_[0]->forward(); }); // Copy weights from 0th graph to all other graphs // to have equal weights across devices ThreadPool pool(graphs_.size() - 1, graphs_.size() - 1); for(size_t i = 1; i < graphs_.size(); ++i) { auto init = [&](size_t i) { // initialize t-th graph and weights builders_[i]->build(graphs_[i], exampleBatch); graphs_[i]->forward(); // overwrite weights of t-th graph with weights from 0th graph graphs_[i]->params()->vals()->copyFrom(graphs_[0]->params()->vals()); }; pool.enqueue(init, i); } // ThreadPool destructor waits until completion of all tasks. } void SyncGraphGroup::initializeAvg() { Ptr<ExpressionGraph> graphAvg; // CPU-side temp std::string name = options_->get<std::string>("model"); if(filesystem::exists(name + ".orig.npz")) { // Load the averaged parameters into a temporary graph graphAvg = New<ExpressionGraph>(); graphAvg->setDevice({0, DeviceType::cpu}); graphAvg->load(name, false); graphAvg->forward(); // initialize parameters if needed } auto init = [&](size_t localDeviceIndex, size_t begin, size_t end) { size_t size = end-begin; // get the device-specific allocator auto paramsAllocator = New<TensorAllocator>(graphs_[localDeviceIndex]->getBackend()); paramsAllocs_[localDeviceIndex] = paramsAllocator; paramsAllocator->reserveExact(size * sizeof(float)); Tensor paramAvg; paramsAllocator->allocate(paramAvg, {1, (int)size}); paramsAvg_[localDeviceIndex] = paramAvg; if(graphAvg) paramAvg->copyFrom(graphAvg ->params()->vals()->subtensor(begin, size)); else paramAvg->copyFrom(graphs_[0]->params()->vals()->subtensor(begin, size)); // note: for multi-node, graphAvg and graphs_[0] contain a complete copy, from which // each MPI process copies only part into its respective shard(s) }; paramsAllocs_.resize(graphs_.size()); // allocators paramsAvg_.resize(graphs_.size()); // averaged parameters (shards; distributed over MPI processes if applicable) comm_->foreach(init, /*parallel=*/false); // @TODO: is sequential operation necessary here? (is the allocation stuff sufficiently reentrant or thread-separated?) } Ptr<data::BatchStats> SyncGraphGroup::collectStats() { size_t multiplier = devices_.size() * mpi_->numMPIProcesses() * delay_; return GraphGroup::collectStats(graphs_[0], builders_[0], multiplier); } void SyncGraphGroup::update(Ptr<data::Batch> batch) /*override*/ { ABORT_IF(finalized_, "Training has already finished."); // distribute the batch over (delay, local device, MPI rank) size_t numSubBatches = delay_ * devices_.size() * mpi_->numMPIProcesses(); auto subBatches = batch->split(numSubBatches); subBatches.resize(numSubBatches); // pad with nullptrs if out of data // Helper to access the subBatches array auto getSubBatch = [&](size_t t, size_t localDeviceIndex, size_t rank) { // 't' (the delay) should be slowest changing dimension. If subBatches are sorted by // length, then grouping sentences of similar length into the same delay step can // reduce unnecessary time spent in padding. return subBatches[(t * mpi_->numMPIProcesses() + rank) * devices_.size() + localDeviceIndex]; }; // Upon very first execution, reset everything if(first_) { LOG(info, "[{}] Processing first minibatch. Batches are processed as {} processes x {} GPUs/process x {} delay steps.", mpi_->idStr(), mpi_->numMPIProcesses(), devices_.size(), delay_); initialize(subBatches.front()); if(mvAvg_ && paramsAvg_.empty()) initializeAvg(); first_ = false; } // Compute gradients // This happens in multiple steps in case of delay_ > 1. std::vector<float> localDeviceCosts(devices_.size(), 0.f); // [local device index] aggregate cost for each local device for (size_t t = 0; t < delay_; t++) { // Execute single forward/backward step auto forwardBackward = [&](size_t localDeviceIndex, size_t /*begin*/, size_t /*end*/) { auto graph = graphs_[localDeviceIndex]; auto subBatch = getSubBatch(t, localDeviceIndex, mpi_->myMPIRank()); // temporary for the cost // @BUGBUG: must exist before first allocations; must do stuff in initialize() //auto costTmp = graph->param("special:costTmp", {}, inits::zeros); //if (t == 0) // costTmp->grad()->set(0.0f); if(subBatch) { timer::Timer timer; auto costNode = builders_[localDeviceIndex]->build(graph, subBatch); timer.format(2, "after build: %ws"); graph->forward(); timer.format(2, "after forward (no sync): %ws"); //localDeviceCosts[localDeviceIndex] += costNode->scalar(); graph->backward(/*zero=*/t == 0); // only reset gradients to 0 if t = 0 timer.format(2, "after backward (no sync): %ws"); localDeviceCosts[localDeviceIndex] += costNode->scalar(); // moved here for time measurements; @TODO: move this back timer.format(2, "after scalar() (that's a sync): %ws"); //// record cost in a gradient //using namespace functional; //Element(_1 += _2, costTmp->grad(), costNode->val()); // stick it into a fake gradient that gets aggregated //// @TODO: Complete this. We still need to move it back from grad to val, which is tricky due to sharding. } else { // empty batch: execute do-nothing fw-bw step for proper inits and resets graph->forward(); graph->backward(/*zero=*/t == 0); } }; comm_->foreach(forwardBackward); // compute gradients in parallel on each device. Aggregate if delay_ > 1. } // At this point, each device on eacn MPI process has a gradient aggregated over a subset of the sub-batches. // Update parameter shard with gradient shard auto update = [&](size_t idx, size_t begin, size_t end) { auto curGrad = graphs_[idx]->params()->grads()->subtensor(begin, end-begin); auto curParam = graphs_[idx]->params()->vals()->subtensor(begin, end-begin); // if individual gradients were averages, then need to average again over all subBatches auto div = subBatches.size(); if (options_->get<std::string>("cost-type") == "ce-sum") div = 1; if(div != 1) { using namespace functional; Element(_1 = _1 / (float)div, curGrad); } // actual model update shardOpt_[idx]->update(curParam, curGrad); if(mvAvg_) updateAvgParams( paramsAvg_[idx], curParam, scheduler_->numberOfBatches()); // fetch the aggregated cost // @TODO: We are sharded here. Need to copy costTmp->grad() to costTmp->val(). //auto costTmp = graphs_[idx]->param("special:costTmp", {}, inits::zeros); //costTmp->val()->copyFrom(costTmp->grad()); }; timer::Timer timer; comm_->scatterReduce(); // reduce gradients across all devices (globally) into shards timer.format(2, "after scatterReduce (has sync): %ws"); comm_->foreach(update); // per-shard model-update timer.format(2, "after model update (no sync): %ws"); comm_->allGather(); // distribute param value shards back timer.format(2, "after allGather (has sync): %ws"); // cost across all local devices // @TODO: We should report cost aggregated over all MPI processes. float cost = 0; for(auto& c : localDeviceCosts) // localDeviceCosts is already summed up over delay steps cost += c; // if cost is average-based, we need to turn the sum over devices into an average as well if(options_->get<std::string>("cost-type") != "ce-sum") cost /= numSubBatches; // the cost is not aggregated across MPI workers here; that is done inside the scheduler if(scheduler_) { // track and log cost scheduler_->update(cost, subBatches, mpi_); // save intermediate model (and optimizer state) to file if(scheduler_->saving()) { save(); } // process valid data set // This may save a model as well. if(scheduler_->validating()) { swapParamsAvg(); if (isMainProcess()) scheduler_->validate(graphs_); swapParamsAvg(); } } } void SyncGraphGroup::load() /*override*/ { if(!options_->get<bool>("no-reload")) { std::string name = options_->get<std::string>("model"); if(filesystem::exists(name)) { if(scheduler_) scheduler_->load(name); std::string nameGraph = name; if(mvAvg_ && filesystem::exists(name + ".orig.npz")) // Load the original parameters from model.npz.orig.npz nameGraph += ".orig.npz"; size_t i = 0; for(auto graph : graphs_) builders_[i++]->load(graph, nameGraph); // we just load it N times from disk (it'll be in disk cache after the first) // @TODO: probably we want to have the list of DeviceIds as an attribute std::vector<Ptr<Backend>> backends; for(auto graph : graphs_) backends.push_back(graph->getBackend()); shardOpt_[0]->load(name + ".optimizer.npz", shardOpt_, backends, [&](const std::vector<float>& data, const OptimizerBase::ScatterStateSetFunc& setFn) { comm_->scatterState(data, setFn); }); } else if(options_->has("pretrained-model")) { std::string nameInit = options_->get<std::string>("pretrained-model"); LOG(info, "Initialize model weights with the pre-trained model {}", nameInit); size_t i = 0; for(auto graph : graphs_) builders_[i++]->load(graph, nameInit, false); } } } void SyncGraphGroup::save(bool final) /*override*/ { barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}!", this->mpi_->idStr(), __LINE__); // do final validation if(final && scheduler_) { // bring the smoothed model in // Note that it is sharded. For multi-node, it is sharded over multiple machines, so this is a network access. // Also note that the swap must run on all MPI processes concurrently, although only one actually validates. LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); if (isMainProcess()) // in multi-node, only first MPI process saves the model (they are all identical) scheduler_->validate(graphs_, true); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } std::string name = options_->get<std::string>("model"); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // if smoothing then save original (unsmoothed) parameters as well // @TODO: Check whether we are reloading the correct file (the unsmoothed one). if(mvAvg_ && paramsAvg_.size() > 0 && isMainProcess()) // only save from one MPI process // Save the original parameters in model.npz.orig.npz builders_[0]->save(graphs_[0], name + ".orig.npz", true); // Temporarily switch to the averaged parameters // Note: the smoothed model is sharded across GPUs, and across MPI processes if applicable. This brings it into MPI process[*].device[*] LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save main model file if (isMainProcess()) { // only save from one MPI process // if not overwrite then save a copy with number of updates in the model pathname LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); if(!options_->get<bool>("overwrite") && !final) { std::string numberOfBatches = scheduler_ ? std::to_string(scheduler_->numberOfBatches()) : "unknown"; std::string nameOverwrite = name; nameOverwrite.replace(name.size() - 4, 4, ".iter" + numberOfBatches + ".npz"); // @TODO: use insert? builders_[0]->save(graphs_[0], nameOverwrite); } LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save main model file builders_[0]->save(graphs_[0], name, true); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save scheduler-related state if (scheduler_) scheduler_->save(name); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } // Switch back to the original parameters LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); #if 1 // temporary, for testing of saving distributed models; must be identical to .orig.npz if(mvAvg_ && paramsAvg_.size() > 0 && isMainProcess()) builders_[0]->save(graphs_[0], name + ".orig_after_swapping.npz", true); #endif LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // persist optimizer state LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); shardOpt_[0]->save(name + ".optimizer.npz", shardOpt_, [&](const OptimizerBase::GatherStateGetFunc& getFn) { return comm_->gatherState(getFn); }, isMainProcess()); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } } // namespace marian <commit_msg>fixed the time measurement (again); cleaned up comments<commit_after>#include "training/graph_group_sync.h" namespace marian { SyncGraphGroup::SyncGraphGroup(Ptr<Config> config) : GraphGroup(config), ExponentialSmoothing{options_->get<float>("exponential-smoothing")}, delay_{options_->get<size_t>("optimizer-delay")} { // @TODO: rename to something else; delay means delayed updated, not accumulation mpi_ = initMPI(/*multiThreaded=*/false); // when not running under MPI, this will be a fake object that represents a one-MPI-process setup devices_ = options_->getDevices(mpi_->myMPIRank(), mpi_->numMPIProcesses()); for(auto device : devices_) { auto graph = New<ExpressionGraph>(); graph->setDevice(device); graph->reserveWorkspaceMB(options_->get<size_t>("workspace")); graph->getBackend()->setClip(options_->get<float>("clip-gemm")); graphs_.push_back(graph); shardOpt_.push_back(Optimizer(options_)); builders_.push_back(models::from_config(options_, models::usage::training)); } // Note: We may well end up with only one MPI process or only one graph per worker. // This part of the code will not special-case any of this here. // Rather, it is assumed that the communicator knows to reduce unnecessary transfers to no-ops. comm_ = createCommunicator(graphs_, /*noNccl=*/options_->get<bool>("no-nccl", false), /*mpi=*/mpi_); } void SyncGraphGroup::setScheduler(Ptr<Scheduler> scheduler) /*override*/ { scheduler_ = scheduler; // optimizer has to be registered last to see changes of learning rate // @TODO: ^^Fix this comment. Either it refers to the scheduler, or it should be moved. Which one? scheduler_->registerTrainingObserver(scheduler_); for(auto opt : shardOpt_) scheduler_->registerTrainingObserver(opt); } void SyncGraphGroup::initialize(const Ptr<data::Batch>& exampleBatch) { // Initialize 0th graph with random weights in one forward step THREAD_GUARD({ builders_[0]->build(graphs_[0], exampleBatch); graphs_[0]->forward(); }); // Copy weights from 0th graph to all other graphs // to have equal weights across devices ThreadPool pool(graphs_.size() - 1, graphs_.size() - 1); for(size_t i = 1; i < graphs_.size(); ++i) { auto init = [&](size_t i) { // initialize t-th graph and weights builders_[i]->build(graphs_[i], exampleBatch); graphs_[i]->forward(); // overwrite weights of t-th graph with weights from 0th graph graphs_[i]->params()->vals()->copyFrom(graphs_[0]->params()->vals()); }; pool.enqueue(init, i); } // ThreadPool destructor waits until completion of all tasks. } void SyncGraphGroup::initializeAvg() { Ptr<ExpressionGraph> graphAvg; // CPU-side temp std::string name = options_->get<std::string>("model"); if(filesystem::exists(name + ".orig.npz")) { // Load the averaged parameters into a temporary graph graphAvg = New<ExpressionGraph>(); graphAvg->setDevice({0, DeviceType::cpu}); graphAvg->load(name, false); graphAvg->forward(); // initialize parameters if needed } auto init = [&](size_t localDeviceIndex, size_t begin, size_t end) { size_t size = end-begin; // get the device-specific allocator auto paramsAllocator = New<TensorAllocator>(graphs_[localDeviceIndex]->getBackend()); paramsAllocs_[localDeviceIndex] = paramsAllocator; paramsAllocator->reserveExact(size * sizeof(float)); Tensor paramAvg; paramsAllocator->allocate(paramAvg, {1, (int)size}); paramsAvg_[localDeviceIndex] = paramAvg; if(graphAvg) paramAvg->copyFrom(graphAvg ->params()->vals()->subtensor(begin, size)); else paramAvg->copyFrom(graphs_[0]->params()->vals()->subtensor(begin, size)); // note: for multi-node, graphAvg and graphs_[0] contain a complete copy, from which // each MPI process copies only part into its respective shard(s) }; paramsAllocs_.resize(graphs_.size()); // allocators paramsAvg_.resize(graphs_.size()); // averaged parameters (shards; distributed over MPI processes if applicable) comm_->foreach(init, /*parallel=*/false); // @TODO: is sequential operation necessary here? (is the allocation stuff sufficiently reentrant or thread-separated?) } Ptr<data::BatchStats> SyncGraphGroup::collectStats() { size_t multiplier = devices_.size() * mpi_->numMPIProcesses() * delay_; return GraphGroup::collectStats(graphs_[0], builders_[0], multiplier); } void SyncGraphGroup::update(Ptr<data::Batch> batch) /*override*/ { ABORT_IF(finalized_, "Training has already finished."); // distribute the batch over (delay, local device, MPI rank) size_t numSubBatches = delay_ * devices_.size() * mpi_->numMPIProcesses(); auto subBatches = batch->split(numSubBatches); subBatches.resize(numSubBatches); // pad with nullptrs if out of data // Helper to access the subBatches array auto getSubBatch = [&](size_t t, size_t localDeviceIndex, size_t rank) { // 't' (the delay) should be slowest changing dimension. If subBatches are sorted by // length, then grouping sentences of similar length into the same delay step can // reduce unnecessary time spent in padding. return subBatches[(t * mpi_->numMPIProcesses() + rank) * devices_.size() + localDeviceIndex]; }; // Upon very first execution, reset everything if(first_) { LOG(info, "[{}] Processing first minibatch. Batches are processed as {} processes x {} GPUs/process x {} delay steps.", mpi_->idStr(), mpi_->numMPIProcesses(), devices_.size(), delay_); initialize(subBatches.front()); if(mvAvg_ && paramsAvg_.empty()) initializeAvg(); first_ = false; } // Compute gradients // This happens in multiple steps in case of delay_ > 1. std::vector<float> localDeviceCosts(devices_.size(), 0.f); // [local device index] aggregate cost for each local device for (size_t t = 0; t < delay_; t++) { // Execute single forward/backward step auto forwardBackward = [&](size_t localDeviceIndex, size_t /*begin*/, size_t /*end*/) { auto graph = graphs_[localDeviceIndex]; auto subBatch = getSubBatch(t, localDeviceIndex, mpi_->myMPIRank()); if(subBatch) { timer::Timer timer; auto costNode = builders_[localDeviceIndex]->build(graph, subBatch); LOG(info, timer.format(2, "after build: %ws")); graph->forward(); LOG(info, timer.format(2, "after forward (no sync): %ws")); //localDeviceCosts[localDeviceIndex] += costNode->scalar(); graph->backward(/*zero=*/t == 0); // only reset gradients to 0 if t = 0 LOG(info, timer.format(2, "after backward (no sync): %ws")); localDeviceCosts[localDeviceIndex] += costNode->scalar(); // moved here for time measurements; @TODO: move this back LOG(info, timer.format(2, "after scalar() (that's a sync): %ws")); } else { // empty batch: execute do-nothing fw-bw step for proper inits and resets graph->forward(); graph->backward(/*zero=*/t == 0); } }; comm_->foreach(forwardBackward); // compute gradients in parallel on each device. Aggregate if delay_ > 1. } // At this point, each device on eacn MPI process has a gradient aggregated over a subset of the sub-batches. // Update parameter shard with gradient shard auto update = [&](size_t idx, size_t begin, size_t end) { auto curGrad = graphs_[idx]->params()->grads()->subtensor(begin, end-begin); auto curParam = graphs_[idx]->params()->vals()->subtensor(begin, end-begin); // if individual gradients were averages, then need to average again over all subBatches auto div = subBatches.size(); if (options_->get<std::string>("cost-type") == "ce-sum") div = 1; if(div != 1) { using namespace functional; Element(_1 = _1 / (float)div, curGrad); } // actual model update shardOpt_[idx]->update(curParam, curGrad); if(mvAvg_) updateAvgParams( paramsAvg_[idx], curParam, scheduler_->numberOfBatches()); }; timer::Timer timer; comm_->scatterReduce(); // reduce gradients across all devices (globally) into shards LOG(info, timer.format(2, "after scatterReduce (has sync): %ws")); comm_->foreach(update); // per-shard model-update LOG(info, timer.format(2, "after model update (no sync): %ws")); comm_->allGather(); // distribute param value shards back LOG(info, timer.format(2, "after allGather (has sync): %ws")); // cost across all local devices (scheduler will aggregate cross-process) float localCost = 0; for(auto& c : localDeviceCosts) // localDeviceCosts is already summed up over delay steps localCost += c; // if localCost is average-based, we need to turn the sum over devices into an average as well if(options_->get<std::string>("localCost-type") != "ce-sum") localCost /= numSubBatches; if(scheduler_) { // track and log localCost scheduler_->update(localCost, subBatches, mpi_); // save intermediate model (and optimizer state) to file if(scheduler_->saving()) save(); // process valid data set // This may save a model as well. if(scheduler_->validating()) { swapParamsAvg(); if (isMainProcess()) scheduler_->validate(graphs_); swapParamsAvg(); } } } void SyncGraphGroup::load() /*override*/ { if(!options_->get<bool>("no-reload")) { std::string name = options_->get<std::string>("model"); if(filesystem::exists(name)) { if(scheduler_) scheduler_->load(name); std::string nameGraph = name; if(mvAvg_ && filesystem::exists(name + ".orig.npz")) // Load the original parameters from model.npz.orig.npz nameGraph += ".orig.npz"; size_t i = 0; for(auto graph : graphs_) builders_[i++]->load(graph, nameGraph); // we just load it N times from disk (it'll be in disk cache after the first) // @TODO: probably we want to have the list of DeviceIds as an attribute std::vector<Ptr<Backend>> backends; for(auto graph : graphs_) backends.push_back(graph->getBackend()); shardOpt_[0]->load(name + ".optimizer.npz", shardOpt_, backends, [&](const std::vector<float>& data, const OptimizerBase::ScatterStateSetFunc& setFn) { comm_->scatterState(data, setFn); }); } else if(options_->has("pretrained-model")) { std::string nameInit = options_->get<std::string>("pretrained-model"); LOG(info, "Initialize model weights with the pre-trained model {}", nameInit); size_t i = 0; for(auto graph : graphs_) builders_[i++]->load(graph, nameInit, false); } } } void SyncGraphGroup::save(bool final) /*override*/ { barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}!", this->mpi_->idStr(), __LINE__); // do final validation if(final && scheduler_) { // bring the smoothed model in // Note that it is sharded. For multi-node, it is sharded over multiple machines, so this is a network access. // Also note that the swap must run on all MPI processes concurrently, although only one actually validates. LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); if (isMainProcess()) // in multi-node, only first MPI process saves the model (they are all identical) scheduler_->validate(graphs_, true); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } std::string name = options_->get<std::string>("model"); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // if smoothing then save original (unsmoothed) parameters as well // @TODO: Check whether we are reloading the correct file (the unsmoothed one). if(mvAvg_ && paramsAvg_.size() > 0 && isMainProcess()) // only save from one MPI process // Save the original parameters in model.npz.orig.npz builders_[0]->save(graphs_[0], name + ".orig.npz", true); // Temporarily switch to the averaged parameters // Note: the smoothed model is sharded across GPUs, and across MPI processes if applicable. This brings it into MPI process[*].device[*] LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save main model file if (isMainProcess()) { // only save from one MPI process // if not overwrite then save a copy with number of updates in the model pathname LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); if(!options_->get<bool>("overwrite") && !final) { std::string numberOfBatches = scheduler_ ? std::to_string(scheduler_->numberOfBatches()) : "unknown"; std::string nameOverwrite = name; nameOverwrite.replace(name.size() - 4, 4, ".iter" + numberOfBatches + ".npz"); // @TODO: use insert? builders_[0]->save(graphs_[0], nameOverwrite); } LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save main model file builders_[0]->save(graphs_[0], name, true); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // save scheduler-related state if (scheduler_) scheduler_->save(name); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } // Switch back to the original parameters LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); swapParamsAvg(); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); #if 1 // temporary, for testing of saving distributed models; must be identical to .orig.npz if(mvAvg_ && paramsAvg_.size() > 0 && isMainProcess()) builders_[0]->save(graphs_[0], name + ".orig_after_swapping.npz", true); #endif LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); // persist optimizer state LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); shardOpt_[0]->save(name + ".optimizer.npz", shardOpt_, [&](const OptimizerBase::GatherStateGetFunc& getFn) { return comm_->gatherState(getFn); }, isMainProcess()); LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); barrier(); // (for better grouping of log messages) LOG(info, "[{}] save() line {}", this->mpi_->idStr(), __LINE__); } } // namespace marian <|endoftext|>
<commit_before>/*--------------------------------------------------------------- * Copyright (c) 1999,2000,2001,2002,2003 * The Board of Trustees of the University of Illinois * All Rights Reserved. *--------------------------------------------------------------- * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software (Iperf) 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: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and * the following disclaimers. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimers in the documentation and/or other materials * provided with the distribution. * * * Neither the names of the University of Illinois, NCSA, * nor the names of its contributors may be used to endorse * or promote products derived from this Software without * specific prior written permission. * * 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 CONTIBUTORS 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. * ________________________________________________________________ * National Laboratory for Applied Network Research * National Center for Supercomputing Applications * University of Illinois at Urbana-Champaign * http://www.ncsa.uiuc.edu * ________________________________________________________________ * * Settings.hpp * by Mark Gates <mgates@nlanr.net> * & Ajay Tirumala <tirumala@ncsa.uiuc.edu> * ------------------------------------------------------------------- * Stores and parses the initial values for all the global variables. * ------------------------------------------------------------------- * headers * uses * <stdlib.h> * <assert.h> * ------------------------------------------------------------------- */ #ifndef SETTINGS_H #define SETTINGS_H #include "headers.h" #include "Thread.hpp" /* ------------------------------------------------------------------- * constants * ------------------------------------------------------------------- */ // server/client mode enum ServerMode { kMode_Server, kMode_Client, kMode_Unknown }; // protocol mode const bool kMode_UDP = false; const bool kMode_TCP = true; // termination mode const bool kMode_Amount = false; // transmit fixed amount const bool kMode_Time = true; // transmit fixed time // domain mode const bool kMode_IPv4 = false; const bool kMode_IPv6 = true; class Settings; extern Settings* gSettings; /* ------------------------------------------------------------------- */ class Settings { public: // set to defaults Settings( void ); // free associated memory ~Settings(); // parse settings from user's environment variables void ParseEnvironment( void ); // parse settings from app's command line void ParseCommandLine( int argc, char **argv ); // convert to lower case for [KMG]bits/sec const void GetLowerCaseArg(const char *,char *); // conver to upper case for [KMG]bytes/sec const void GetUpperCaseArg(const char *,char *); // ---- access settings // -b # // valid in UDP mode double GetUDPRate( void ) const { assert( GetProtocolMode() == kMode_UDP ); return mUDPRate; } // -c <host> // valid in client mode const char* GetHost( void ) const { assert( GetServerMode() == kMode_Client ); return mHost; } // -f [kmKM] char GetFormat( void ) const { return mFormat; } // -l # int GetBufferLen( void ) const { return mBufLen; } // -m // valid in TCP mode bool GetPrintMSS( void ) const { assert( GetProtocolMode() == kMode_TCP ); return mPrintMSS; } // -n # // valid in Amount mode (transmit fixed amount of data) max_size_t GetAmount( void ) const { assert( mAmount > 0 ); assert( GetTerminationMode() == kMode_Amount ); return(max_size_t) mAmount; } // -p # unsigned short GetPort( void ) const { return mPort; } // -s or -c ServerMode GetServerMode( void ) const { return mServerMode; } // -t # // valid in Time mode (transmit for fixed time) double GetTime( void ) const { assert( mAmount < 0 ); assert( GetTerminationMode() == kMode_Time ); return -mAmount; } // -w # int GetTCPWindowSize( void ) const { return mTCPWin; } // ---- more esoteric options // -B <host> const char* GetLocalhost( void ) const { return mLocalhost; } // -i # double GetInterval( void ) const { return mInterval; } // -M # // valid in TCP mode int GetTCP_MSS( void ) const { assert( GetProtocolMode() == kMode_TCP ); return mMSS; } // -N // valid in TCP mode bool GetTCP_Nodelay( void ) const { assert( GetProtocolMode() == kMode_TCP ); return mNodelay; } // -P # // only useful in TCP mode int GetClientThreads( void ) const { //assert( GetProtocolMode() == kMode_TCP ); return mThreads; } // -S # int GetTOS( void ) const { return mTOS; } // -T # // valid in UDP mode u_char GetMcastTTL( void ) const { return mTTL; } // ---- modes // differentiate Time and Amount; -t # and -n # // note these optimize to just the comparison with zero bool GetTerminationMode( void ) const { return(mAmount < 0 ? kMode_Time : kMode_Amount); } // differentiate UDP and TCP; -u or -b # gives UDP bool GetProtocolMode( void ) const { return(mUDPRate == 0 ? kMode_TCP : kMode_UDP); } // whether the server runs as a daemon or not bool GetDaemonMode(void) const { return mDaemon; } // Whether the client must suggest the window size or not bool GetSuggestWin(void) const { return mSuggestWin; } // Set the interval time void SetInterval(double interval) { mInterval = interval; } // Set the file input status void SetFileInput(bool status) { mFileInput = status; } // Whether the input is the default stream or a // file stream bool GetFileInput(void) const { return mFileInput; } // return the file name if the input is through a // file stream char *GetFileName(void) const { if ( mFileInput ) return mFileName; return NULL; } // return whether the input is from stdin bool GetStdin(void) const { return mStdin; } // file stream bool GetFileOutput(void) const { if ( mStdout ) return false; return true; } // return the file name if the output is through a // file stream char *GetOutputFileName(void) const { if ( !mStdout ) return mOutputFileName; return NULL; } // whether win32 service should be removed or not bool GetRemoveService(void) const { return mRemoveService; } // IPv4 or IPv6 domain bool GetDomain(void) const { return mDomain; } protected: void Interpret( char option, const char *optarg ); // here instead of listing by option order (as elsewhere) // I list by type so that the structure alignment will be nice char* mHost; // -c char* mLocalhost; // -B char* mFileName; // -F char* mOutputFileName; // -o double mUDPRate; // -b double mAmount; // -n or -t double mInterval; // -i int mBufLen; // -l int mTCPWin; // -w int mMSS; // -m int mThreads; // -P int mTOS; // -S unsigned short mPort; // -p char mFormat; // -f u_char mTTL; // --ttl ServerMode mServerMode; // -s or -c bool mPrintMSS; // -M bool mNodelay; // -N bool mBufLenSet; // if -l was specified. // UDP and TCP have different BufLen defaults. bool mDaemon; // -d bool mSuggestWin; bool mFileInput; // -F or -I bool mStdin; // -I bool mStdout; // -o bool mDomain; // -V bool mRemoveService; // -R }; // end class Settings #endif // SETTINGS_H <commit_msg>Import from CVS Thu Feb 27 22:35:24 2003 -0600<commit_after>/*--------------------------------------------------------------- * Copyright (c) 1999,2000,2001,2002,2003 * The Board of Trustees of the University of Illinois * All Rights Reserved. *--------------------------------------------------------------- * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software (Iperf) 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: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and * the following disclaimers. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimers in the documentation and/or other materials * provided with the distribution. * * * Neither the names of the University of Illinois, NCSA, * nor the names of its contributors may be used to endorse * or promote products derived from this Software without * specific prior written permission. * * 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 CONTIBUTORS 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. * ________________________________________________________________ * National Laboratory for Applied Network Research * National Center for Supercomputing Applications * University of Illinois at Urbana-Champaign * http://www.ncsa.uiuc.edu * ________________________________________________________________ * * Settings.hpp * by Mark Gates <mgates@nlanr.net> * & Ajay Tirumala <tirumala@ncsa.uiuc.edu> * ------------------------------------------------------------------- * Stores and parses the initial values for all the global variables. * ------------------------------------------------------------------- * headers * uses * <stdlib.h> * <assert.h> * ------------------------------------------------------------------- */ #ifndef SETTINGS_H #define SETTINGS_H #include "headers.h" #include "Thread.hpp" /* ------------------------------------------------------------------- * constants * ------------------------------------------------------------------- */ // server/client mode enum ServerMode { kMode_Server, kMode_Client, kMode_Unknown }; // test mode enum TestMode { kTest_Normal, kTest_DualTest, kTest_TradeOff, kTest_Unknown }; // protocol mode const bool kMode_UDP = false; const bool kMode_TCP = true; // termination mode const bool kMode_Amount = false; // transmit fixed amount const bool kMode_Time = true; // transmit fixed time // domain mode const bool kMode_IPv4 = false; const bool kMode_IPv6 = true; class Settings; /* * The ext_Settings is a structure that holds all * options for a given execution of either a client * or server. By using this structure rather than * a global structure or class we can have multiple * clients or servers running with different settings. */ struct ext_Settings { char* mFileName; // -F char* mHost; // -c char* mLocalhost; // -B char* mOutputFileName; // -o double mInterval; // -i int mAmount; // -n or -t int mBufLen; // -l int mMSS; // -M int mTCPWin; // -w int mThreads; // -P int mTOS; // -S int mUDPRate; // -b or -u ServerMode mServerMode; // -s or -c TestMode mMode; // -r or -d unsigned short mListenPort; // -L unsigned short mPort; // -p char mFormat; // -f u_char mTTL; // -T bool mBufLenSet; // -l bool mCompat; // -C bool mDaemon; // -D bool mDomain; // -V bool mFileInput; // -F or -I bool mNodelay; // -N bool mPrintMSS; // -m bool mRemoveService; // -R bool mStdin; // -I bool mStdout; // -o bool mSuggestWin; // -W }; #define HEADER_VERSION1 0x80000000 #define RUN_NOW 0x00000001 // used to reference the 4 byte ID number we place in UDP datagrams // use int32_t if possible, otherwise a 32 bit bitfield (e.g. on J90) struct UDP_datagram { #ifdef HAVE_INT32_T int32_t id; u_int32_t tv_sec; u_int32_t tv_usec; #else signed int id : 32; unsigned int tv_sec : 32; unsigned int tv_usec : 32; #endif }; /* * The client_hdr structure is sent from clients * to servers to alert them of things that need * to happen. Order must be perserved in all * future releases for backward compatibility. * 1.7 has flags, numThreads, mPort, and bufferlen */ struct client_hdr { #ifdef HAVE_INT32_T /* * flags is a bitmap for different options * the most significant bits are for determining * which information is available. So 1.7 uses * 0x80000000 and the next time information is added * the 1.7 bit will be set and 0x40000000 will be * set signifying additional information. If no * information bits are set then the header is ignored. * The lowest order diferentiates between dualtest and * tradeoff modes, wheither the speaker needs to start * immediately or after the audience finishes. */ int32_t flags; int32_t numThreads; int32_t mPort; int32_t bufferlen; int32_t mWinBand; int32_t mAmount; #else signed int flags : 32; signed int numThreads : 32; signed int mPort : 32; signed int bufferlen : 32; signed int mWinBand : 32; signed int mAmount : 32; #endif }; /* * The server_hdr structure facilitates the server * report of jitter and loss on the client side. * It piggy_backs on the existing clear to close * packet. */ struct server_hdr { #ifdef HAVE_INT32_T /* * flags is a bitmap for different options * the most significant bits are for determining * which information is available. So 1.7 uses * 0x80000000 and the next time information is added * the 1.7 bit will be set and 0x40000000 will be * set signifying additional information. If no * information bits are set then the header is ignored. */ int32_t flags; int32_t total_len1; int32_t total_len2; int32_t stop_sec; int32_t stop_usec; int32_t error_cnt; int32_t outorder_cnt; int32_t datagrams; int32_t jitter1; int32_t jitter2; #else signed int flags : 32; signed int total_len1 : 32; signed int total_len2 : 32; signed int stop_sec : 32; signed int stop_usec : 32; signed int error_cnt : 32; signed int outorder_cnt : 32; signed int datagrams : 32; signed int jitter1 : 32; signed int jitter2 : 32; #endif }; /* ------------------------------------------------------------------- */ class Settings { public: // set to defaults Settings( ext_Settings* main ); // free associated memory ~Settings(); // parse settings from user's environment variables void ParseEnvironment( void ); // parse settings from app's command line void ParseCommandLine( int argc, char **argv ); // convert to lower case for [KMG]bits/sec const void GetLowerCaseArg(const char *,char *); // conver to upper case for [KMG]bytes/sec const void GetUpperCaseArg(const char *,char *); // generate settings for listener instance static void GenerateListenerSettings( ext_Settings *old, ext_Settings **listener); // generate settings for speaker instance static void GenerateSpeakerSettings( ext_Settings *old, ext_Settings **speaker, client_hdr *hdr, sockaddr* peer ); // generate client header for server static void GenerateClientHdr( ext_Settings *old, client_hdr *hdr ); // ---- access settings // -b # // valid in UDP mode double GetUDPRate( void ) const { assert( GetProtocolMode() == kMode_UDP ); return mExtSettings->mUDPRate; } // -c <host> // valid in client mode const char* GetHost( void ) const { assert( mExtSettings->mServerMode == kMode_Client ); return mExtSettings->mHost; } // -f [kmKM] char GetFormat( void ) const { return mExtSettings->mFormat; } // -l # int GetBufferLen( void ) const { return mExtSettings->mBufLen; } // -m // valid in TCP mode bool GetPrintMSS( void ) const { assert( GetProtocolMode() == kMode_TCP ); return mExtSettings->mPrintMSS; } // -n # // valid in Amount mode (transmit fixed amount of data) max_size_t GetAmount( void ) const { assert( mExtSettings->mAmount > 0 ); assert( GetTerminationMode() == kMode_Amount ); return (max_size_t) mExtSettings->mAmount; } // -p # unsigned short GetPort( void ) const { return mExtSettings->mPort; } // -L # unsigned short GetListenPort( void ) const { return mExtSettings->mListenPort; } // -s or -c ServerMode GetServerMode( void ) const { return mExtSettings->mServerMode; } // -d or -r TestMode GetTestingMode( void ) const { return mExtSettings->mMode; } // -t # // valid in Time mode (transmit for fixed time) double GetTime( void ) const { assert( mExtSettings->mAmount < 0 ); return (-mExtSettings->mAmount) / 100.0; } // -w # int GetTCPWindowSize( void ) const { return mExtSettings->mTCPWin; } // ---- more esoteric options // -B <host> const char* GetLocalhost( void ) const { return mExtSettings->mLocalhost; } // -i # double GetInterval( void ) const { return mExtSettings->mInterval; } // -M # // valid in TCP mode int GetTCP_MSS( void ) const { assert( GetProtocolMode() == kMode_TCP ); return mExtSettings->mMSS; } // -N // valid in TCP mode bool GetTCP_Nodelay( void ) const { assert( GetProtocolMode() == kMode_TCP ); return mExtSettings->mNodelay; } // -P # int GetClientThreads( void ) const { return mExtSettings->mThreads; } // -S # int GetTOS( void ) const { return mExtSettings->mTOS; } // -T # // valid in UDP mode u_char GetMcastTTL( void ) const { return mExtSettings->mTTL; } // ---- modes // differentiate Time and Amount; -t # and -n # // note these optimize to just the comparison with zero bool GetTerminationMode( void ) const { return ( mExtSettings->mAmount < 0 ? kMode_Time : kMode_Amount ); } // differentiate UDP and TCP; -u or -b # gives UDP bool GetProtocolMode( void ) const { return ( mExtSettings->mUDPRate == 0 ? kMode_TCP : kMode_UDP ); } // whether the server runs as a daemon or not bool GetDaemonMode(void) const { return mExtSettings->mDaemon; } // whether running in compatibility mode or not bool GetCompatMode(void) const { return mExtSettings->mCompat; } // Whether the client must suggest the window size or not bool GetSuggestWin(void) const { return mExtSettings->mSuggestWin; } // Set the interval time void SetInterval(double interval) { mExtSettings->mInterval = interval; } // Set the file input status void SetFileInput(bool status) { mExtSettings->mFileInput = status; } // Whether the input is the default stream or a // file stream bool GetFileInput(void) const { return mExtSettings->mFileInput; } // return the file name if the input is through a // file stream char *GetFileName(void) const { if ( mExtSettings->mFileInput ) return mExtSettings->mFileName; return NULL; } // return whether the input is from stdin bool GetStdin(void) const { return mExtSettings->mStdin; } // file stream bool GetFileOutput(void) const { if ( mExtSettings->mStdout ) return false; return true; } // return the file name if the output is through a // file stream char *GetOutputFileName(void) const { if ( !mExtSettings->mStdout ) return mExtSettings->mOutputFileName; return NULL; } // whether win32 service should be removed or not bool GetRemoveService(void) const { return mExtSettings->mRemoveService; } // IPv4 or IPv6 domain bool GetDomain(void) const { return mExtSettings->mDomain; } protected: void Interpret( char option, const char *optarg ); ext_Settings* mExtSettings; }; // end class Settings #endif // SETTINGS_H <|endoftext|>
<commit_before>#include "unittest/gtest.hpp" #include "arch/runtime/context_switching.hpp" namespace unittest { static void noop(void) { } TEST(ContextSwitchingTest, ContextRefSemantics) { context_ref_t nil_ref; EXPECT_TRUE(nil_ref.is_nil()); } TEST(ContextSwitchingTest, CreateArtificialStack) { artificial_stack_t a(&noop, 1024*1024); EXPECT_FALSE(a.context.is_nil()); } /* Thread-local variables for use in test functions, because we cannot pass a `void*` to the test functions... */ static __thread context_ref_t *original_context = NULL, *artificial_stack_1_context = NULL, *artificial_stack_2_context = NULL; static __thread int test_int; static void switch_context_test(void) { test_int++; context_switch(artificial_stack_1_context, original_context); test_int += 2; context_switch(artificial_stack_1_context, original_context); test_int += 3; context_switch(artificial_stack_1_context, original_context); /* This will never get run */ test_int += 10000; } TEST(ContextSwitchingTest, SwitchToContextRepeatedly) { original_context = new context_ref_t; test_int = 5; { artificial_stack_t a(&switch_context_test, 1024*1024); artificial_stack_1_context = &a.context; /* `context_switch` will cause `switch_context_test` to be run, which will increment `test_int` and then switch back from `src_context` to `dest_context`. */ context_switch(original_context, artificial_stack_1_context); context_switch(original_context, artificial_stack_1_context); context_switch(original_context, artificial_stack_1_context); EXPECT_FALSE(a.context.is_nil()); } EXPECT_EQ(test_int, 11); delete original_context; } static void first_switch(void) { test_int++; context_switch(artificial_stack_1_context, artificial_stack_2_context); } static void second_switch(void) { test_int++; context_switch(artificial_stack_2_context, original_context); } TEST(ContextSwitchingTest, SwitchBetweenContexts) { original_context = new context_ref_t; test_int = 99; { artificial_stack_t a1(&first_switch, 1024*1024); artificial_stack_t a2(&second_switch, 1024*1024); artificial_stack_1_context = &a1.context; artificial_stack_2_context = &a2.context; context_switch(original_context, artificial_stack_1_context); } EXPECT_EQ(test_int, 101); delete original_context; } } /* namespace unittest */ <commit_msg>Set thread-local vars to NULL when done using them in context_switching unit test.<commit_after>#include "unittest/gtest.hpp" #include "arch/runtime/context_switching.hpp" namespace unittest { static void noop(void) { } TEST(ContextSwitchingTest, ContextRefSemantics) { context_ref_t nil_ref; EXPECT_TRUE(nil_ref.is_nil()); } TEST(ContextSwitchingTest, CreateArtificialStack) { artificial_stack_t a(&noop, 1024*1024); EXPECT_FALSE(a.context.is_nil()); } /* Thread-local variables for use in test functions, because we cannot pass a `void*` to the test functions... */ static __thread context_ref_t *original_context = NULL, *artificial_stack_1_context = NULL, *artificial_stack_2_context = NULL; static __thread int test_int; static void switch_context_test(void) { test_int++; context_switch(artificial_stack_1_context, original_context); test_int += 2; context_switch(artificial_stack_1_context, original_context); test_int += 3; context_switch(artificial_stack_1_context, original_context); /* This will never get run */ test_int += 10000; } TEST(ContextSwitchingTest, SwitchToContextRepeatedly) { original_context = new context_ref_t; test_int = 5; { artificial_stack_t a(&switch_context_test, 1024*1024); artificial_stack_1_context = &a.context; /* `context_switch` will cause `switch_context_test` to be run, which will increment `test_int` and then switch back from `src_context` to `dest_context`. */ context_switch(original_context, artificial_stack_1_context); context_switch(original_context, artificial_stack_1_context); context_switch(original_context, artificial_stack_1_context); EXPECT_FALSE(a.context.is_nil()); } EXPECT_EQ(test_int, 11); delete original_context; original_context = NULL; } static void first_switch(void) { test_int++; context_switch(artificial_stack_1_context, artificial_stack_2_context); } static void second_switch(void) { test_int++; context_switch(artificial_stack_2_context, original_context); } TEST(ContextSwitchingTest, SwitchBetweenContexts) { original_context = new context_ref_t; test_int = 99; { artificial_stack_t a1(&first_switch, 1024*1024); artificial_stack_t a2(&second_switch, 1024*1024); artificial_stack_1_context = &a1.context; artificial_stack_2_context = &a2.context; context_switch(original_context, artificial_stack_1_context); } EXPECT_EQ(test_int, 101); delete original_context; original_context = NULL; } } /* namespace unittest */ <|endoftext|>
<commit_before>#include "SentenceStateBuilder.h" #include <vector> #include "Sysout.h" #include "../language/Grammar.h" #include "../language/Dictionary.h" gmr::SentenceState* SentenceStateBuilder::processStatement(std::vector<std::string>* statement) { // Make a new builder SentenceStateBuilder* ssbuilder = new SentenceStateBuilder(); // Loop through all the words for(std::vector<std::string>::iterator wordPtr = statement->begin(); wordPtr != statement->end(); ++ wordPtr) { /* === Testing for nouns === */ // Remembers if this word is a noun bool isNoun = false; // Test for nouns for(gmr::NounId possiblyMatchingNounId = 0; possiblyMatchingNounId < Dictionary::numNouns(); ++ possiblyMatchingNounId) { // Does it match the singular form? if(*wordPtr == Dictionary::getNoun(possiblyMatchingNounId)->getSingularForm()) { // Process it ssbuilder->processNoun(possiblyMatchingNounId, gmr::singular); // It is a noun isNoun = true; // Do not test for the other nouns break; } // Does it match the plural form? else if(*wordPtr == Dictionary::getNoun(possiblyMatchingNounId)->getPluralForm()) { // Process it ssbuilder->processNoun(possiblyMatchingNounId, gmr::plural); // It is a noun isNoun = true; // Do not test for the other nouns break; } } // If it is a noun, then obviously it can't be anything else, // So stop analyzing this word and look at the next word if(isNoun) { continue; } /* === Testing for articles === */ // Test for articles gmr::ArticleProperties testArticleProperties = Dictionary::getArticle(*wordPtr); // If this article type is not erroneous if(testArticleProperties.type != gmr::undefinite) { ssbuilder->processArticle(testArticleProperties); // Continue to next word continue; } /* === Testing for modifiers === */ // Remembers if this word is a noun bool isModifier = false; // gmr::ModifierId possiblyMatchingModifierId = Dictionary::getModifierId(*wordPtr); // Test for modifiers Sysout::println(possiblyMatchingModifierId); if(possiblyMatchingModifierId != Dictionary::getErroneousModifierId()) { // Process it Sysout::println("notatnererr"); Sysout::println(Dictionary::getModifier(possiblyMatchingModifierId)->getForm()); ssbuilder->processModifier(possiblyMatchingModifierId); // It is a modifier isModifier = true; // Do not test for the other nouns break; } // If it is a noun, then obviously it can't be anything else, // So stop analyzing this word and look at the next word if(isModifier) { continue; } /* === Testing for adjuncts === */ // Put something here } gmr::SentenceState* sntcState = ssbuilder->finish(); delete ssbuilder; return sntcState; } gmr::SentenceState* SentenceStateBuilder::finish() { return new gmr::SentenceState(completedNouns); } void SentenceStateBuilder::publishNoun() { // Add the workspace address to the collection of addresses of completed nouns completedNouns->push_back(wipNoun); // Make a new workspace wipNoun = new gmr::NounState(); } void SentenceStateBuilder::processNoun(gmr::NounId id, gmr::Plurality plurality) { // If we can tell the difference between plural and singular if(!Dictionary::getNoun(id)->hasAmbiguousPlurality()) { wipNoun->plurality = plurality; } // Set the id wipNoun->id = id; // Publish the noun publishNoun(); } void SentenceStateBuilder::processArticle(gmr::ArticleProperties properties) { // If we do not already know the plurality for the noun if(wipNoun->plurality == gmr::ambiguous) { // Set it to be this one wipNoun->plurality = properties.plurality; } // Set its definity wipNoun->definity = properties.type; } void SentenceStateBuilder::processModifier(gmr::ModifierId modifierId) { bool alreadyHas = false; for(unsigned int indexOffset = 0; indexOffset < wipNoun->modifiers->size(); ++ indexOffset) { if(wipNoun->modifiers->at(indexOffset) == modifierId) { alreadyHas = true; break; } } if(!alreadyHas) { wipNoun->modifiers->push_back(modifierId); } } SentenceStateBuilder::SentenceStateBuilder() { wipNoun = new gmr::NounState(); // The space we will build our work in progress (WIP) noun completedNouns = new std::vector<gmr::NounState*>(); // All of our completed nouns } <commit_msg>Fixed modifier recognition<commit_after>#include "SentenceStateBuilder.h" #include <vector> #include "../language/Grammar.h" #include "../language/Dictionary.h" gmr::SentenceState* SentenceStateBuilder::processStatement(std::vector<std::string>* statement) { // Make a new builder SentenceStateBuilder* ssbuilder = new SentenceStateBuilder(); // Loop through all the words for(std::vector<std::string>::iterator wordPtr = statement->begin(); wordPtr != statement->end(); ++ wordPtr) { /* === Testing for nouns === */ // Remembers if this word is a noun bool isNoun = false; // Test for nouns for(gmr::NounId possiblyMatchingNounId = 0; possiblyMatchingNounId < Dictionary::numNouns(); ++ possiblyMatchingNounId) { // Does it match the singular form? if(*wordPtr == Dictionary::getNoun(possiblyMatchingNounId)->getSingularForm()) { // Process it ssbuilder->processNoun(possiblyMatchingNounId, gmr::singular); // It is a noun isNoun = true; // Do not test for the other nouns break; } // Does it match the plural form? else if(*wordPtr == Dictionary::getNoun(possiblyMatchingNounId)->getPluralForm()) { // Process it ssbuilder->processNoun(possiblyMatchingNounId, gmr::plural); // It is a noun isNoun = true; // Do not test for the other nouns break; } } // If it is a noun, then obviously it can't be anything else, // So stop analyzing this word and look at the next word if(isNoun) { continue; } /* === Testing for articles === */ // Test for articles gmr::ArticleProperties testArticleProperties = Dictionary::getArticle(*wordPtr); // If this article type is not erroneous if(testArticleProperties.type != gmr::undefinite) { ssbuilder->processArticle(testArticleProperties); // Continue to next word continue; } /* === Testing for modifiers === */ // gmr::ModifierId possiblyMatchingModifierId = Dictionary::getModifierId(*wordPtr); // Test for modifiers if(possiblyMatchingModifierId != Dictionary::getErroneousModifierId()) { // Process it ssbuilder->processModifier(possiblyMatchingModifierId); // If it is a modifier, then obviously it can't be anything else, // So stop analyzing this word and look at the next word continue; } /* === Testing for adjuncts === */ // Put something here } gmr::SentenceState* sntcState = ssbuilder->finish(); delete ssbuilder; return sntcState; } gmr::SentenceState* SentenceStateBuilder::finish() { return new gmr::SentenceState(completedNouns); } void SentenceStateBuilder::publishNoun() { // Add the workspace address to the collection of addresses of completed nouns completedNouns->push_back(wipNoun); // Make a new workspace wipNoun = new gmr::NounState(); } void SentenceStateBuilder::processNoun(gmr::NounId id, gmr::Plurality plurality) { // If we can tell the difference between plural and singular if(!Dictionary::getNoun(id)->hasAmbiguousPlurality()) { wipNoun->plurality = plurality; } // Set the id wipNoun->id = id; // Publish the noun publishNoun(); } void SentenceStateBuilder::processArticle(gmr::ArticleProperties properties) { // If we do not already know the plurality for the noun if(wipNoun->plurality == gmr::ambiguous) { // Set it to be this one wipNoun->plurality = properties.plurality; } // Set its definity wipNoun->definity = properties.type; } void SentenceStateBuilder::processModifier(gmr::ModifierId modifierId) { bool alreadyHas = false; for(unsigned int indexOffset = 0; indexOffset < wipNoun->modifiers->size(); ++ indexOffset) { if(wipNoun->modifiers->at(indexOffset) == modifierId) { alreadyHas = true; break; } } if(!alreadyHas) { wipNoun->modifiers->push_back(modifierId); } } SentenceStateBuilder::SentenceStateBuilder() { wipNoun = new gmr::NounState(); // The space we will build our work in progress (WIP) noun completedNouns = new std::vector<gmr::NounState*>(); // All of our completed nouns } <|endoftext|>
<commit_before>#include "glyphcellrenderer.h" #include <wx/dcclient.h> #include <wx/graphics.h> #include <memory> GlyphCellRenderer::GlyphCellRenderer(const std::map<wxString, SvgGlyph> &glyphs, int fontSize): glyphs(glyphs), fontSize(fontSize) { } wxGridCellRenderer *GlyphCellRenderer::Clone() const { return nullptr; } void GlyphCellRenderer::Draw(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected) { wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, isSelected); wxString value = grid.GetTable()->GetValue(row, col); auto it = glyphs.find(value); if (it == glyphs.end()) return; const SvgGlyph &glyph = it->second; if (!glyph.isOk()) return; // Oh, crap wxRect newRect = rect; newRect.x += dc.GetDeviceOrigin().x; newRect.y += dc.GetDeviceOrigin().y; std::unique_ptr<wxGraphicsContext> gc(wxGraphicsContext::Create(static_cast<wxPaintDC&>(dc))); gc->SetBrush(wxBrush(*wxBLACK)); SvgPath path(glyph.data.ToStdString()); SvgGlyphCtrl::RenderGlyph(gc.get(), newRect, path, glyph, fontSize); } wxSize GlyphCellRenderer::GetBestSize(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col) { return wxSize(fontSize + 4, fontSize + 4); } <commit_msg>do not set device origins for GDI+ graphics context<commit_after>#include "glyphcellrenderer.h" #include <wx/dcclient.h> #include <wx/graphics.h> #include <memory> GlyphCellRenderer::GlyphCellRenderer(const std::map<wxString, SvgGlyph> &glyphs, int fontSize): glyphs(glyphs), fontSize(fontSize) { } wxGridCellRenderer *GlyphCellRenderer::Clone() const { return nullptr; } void GlyphCellRenderer::Draw(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected) { wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, isSelected); wxString value = grid.GetTable()->GetValue(row, col); auto it = glyphs.find(value); if (it == glyphs.end()) return; const SvgGlyph &glyph = it->second; if (!glyph.isOk()) return; std::unique_ptr<wxGraphicsContext> gc(wxGraphicsContext::Create(static_cast<wxPaintDC&>(dc))); gc->SetBrush(wxBrush(*wxBLACK)); wxRect newRect = rect; // Oh, crap if (gc->GetRenderer()->GetName() == L"cairo") { newRect.x += dc.GetDeviceOrigin().x; newRect.y += dc.GetDeviceOrigin().y; } SvgPath path(glyph.data.ToStdString()); SvgGlyphCtrl::RenderGlyph(gc.get(), newRect, path, glyph, fontSize); } wxSize GlyphCellRenderer::GetBestSize(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col) { return wxSize(fontSize + 4, fontSize + 4); } <|endoftext|>
<commit_before>#include "archivestabwidget.h" WARNINGS_DISABLE #include <QAction> #include <QComboBox> #include <QCoreApplication> #include <QCursor> #include <QEvent> #include <QEventLoop> #include <QKeyEvent> #include <QKeySequence> #include <QMenu> #include <QWidget> #include <Qt> #include "ui_archivestabwidget.h" WARNINGS_ENABLE #include "archivelistwidget.h" #include "archivewidget.h" #include "basetask.h" #include "persistentmodel/archive.h" ArchivesTabWidget::ArchivesTabWidget(QWidget *parent) : QWidget(parent), _ui(new Ui::ArchivesTabWidget) { // Ui initialization _ui->setupUi(this); updateUi(); // Basic UI setup. _ui->archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false); _ui->archiveDetailsWidget->hide(); _ui->archivesFilterFrame->hide(); // Context menu. _archiveListMenu = new QMenu(_ui->archiveListWidget); connect(_ui->archiveListWidget, &ArchiveListWidget::customContextMenuRequested, this, &ArchivesTabWidget::showArchiveListMenu); // Context menu actions. _ui->archiveListWidget->addAction(_ui->actionRefresh); _ui->archiveListWidget->addAction(_ui->actionInspect); _ui->archiveListWidget->addAction(_ui->actionDelete); _ui->archiveListWidget->addAction(_ui->actionRestore); connect(_ui->actionInspect, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::inspectSelectedItem); connect(_ui->actionDelete, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::deleteSelectedItems); connect(_ui->actionRestore, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::restoreSelectedItem); // Connections from the ArchiveListWidget. connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, this, &ArchivesTabWidget::displayInspectArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::clearInspectArchive, this, &ArchivesTabWidget::hideInspectArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::deleteArchives, this, &ArchivesTabWidget::deleteArchives); connect(_ui->archiveListWidget, &ArchiveListWidget::restoreArchive, this, &ArchivesTabWidget::restoreArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::displayJobDetails, [this](const QString &jobRef) { emit displayJobDetails(jobRef); }); connect(_ui->archiveListWidget, &ArchiveListWidget::countChanged, [this](int total, int visible) { _ui->archivesCountLabel->setText( tr("Archives (%1/%2)").arg(visible).arg(total)); }); // Connections to the ArchiveListWidget. connect(this, &ArchivesTabWidget::archiveList, _ui->archiveListWidget, &ArchiveListWidget::setArchives); connect(this, &ArchivesTabWidget::addArchive, _ui->archiveListWidget, &ArchiveListWidget::addArchive); // Connections from the ArchiveDetailsWidget. connect(_ui->archiveDetailsWidget, &ArchiveDetailsWidget::restoreArchive, this, &ArchivesTabWidget::restoreArchive); connect(_ui->archiveDetailsWidget, &ArchiveDetailsWidget::hidden, _ui->archiveListWidget, &ArchiveListWidget::noInspect); connect(_ui->archiveDetailsWidget, &ArchiveDetailsWidget::taskRequested, this, &ArchivesTabWidget::taskRequested); connect(_ui->archiveDetailsWidget, &ArchiveDetailsWidget::jobClicked, [this](const QString &jobRef) { emit jobClicked(jobRef); }); // Filtering. _ui->archiveListWidget->addAction(_ui->actionFilterArchives); _ui->archivesFilterButton->setDefaultAction(_ui->actionFilterArchives); connect(_ui->archivesFilter, &QComboBox::editTextChanged, _ui->archiveListWidget, &ArchiveListWidget::setFilter); connect(_ui->actionFilterArchives, &QAction::triggered, [this]() { _ui->archivesFilterFrame->setVisible( !_ui->archivesFilterFrame->isVisible()); if(_ui->archivesFilter->isVisible()) _ui->archivesFilter->setFocus(); else _ui->archivesFilter->clearEditText(); }); connect(_ui->archivesFilter, &QComboBox::editTextChanged, _ui->archiveListWidget, &ArchiveListWidget::setFilter); connect(_ui->archivesFilter, static_cast<void (QComboBox::*)(int)>( &QComboBox::currentIndexChanged), [this]() { _ui->archiveListWidget->setFocus(); }); } ArchivesTabWidget::~ArchivesTabWidget() { delete _ui; } void ArchivesTabWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { _ui->retranslateUi(this); updateUi(); } QWidget::changeEvent(event); } void ArchivesTabWidget::keyPressEvent(QKeyEvent *event) { switch(event->key()) { case Qt::Key_Escape: // Apply to the ArchiveDetailsWidget, if possible... if(_ui->archiveDetailsWidget->isVisible()) { _ui->archiveDetailsWidget->close(); return; } // ... otherwise, apply the archive filter, if possible... if(_ui->archivesFilter->isVisible()) { if(_ui->archivesFilter->currentText().isEmpty()) { _ui->actionFilterArchives->trigger(); } else { _ui->archivesFilter->clearEditText(); _ui->archivesFilter->setFocus(); } return; } // ... otherwise, use the default handling. break; default: QWidget::keyPressEvent(event); } } void ArchivesTabWidget::hideInspectArchive() { _ui->archiveDetailsWidget->hide(); } void ArchivesTabWidget::displayInspectArchive(ArchivePtr archive) { // Get the size. if(archive->sizeTotal() == 0) emit loadArchiveStats(archive); // Get the file list. if(archive->contents().count() == 0) emit loadArchiveContents(archive); // Highlight the row in the ArchiveListWidget. _ui->archiveListWidget->selectArchive(archive); // Display Archive details. _ui->archiveDetailsWidget->setArchive(archive); if(!_ui->archiveDetailsWidget->isVisible()) { _ui->archiveDetailsWidget->show(); // Allow the event loop to update the geometry of the scroll area. // I haven't found a way to fix this without dropping back to the // main event loop. :( QCoreApplication::processEvents(QEventLoop::AllEvents, 10); } // Make sure we can see it in the Archive List. Must be after showing // the ArchiveDetailsWidget, otherwise the highlighted row might be // "visible" underneath the newly-expanded ArchiveDetailsWidget. _ui->archiveListWidget->ensureCurrentItemVisible(); } void ArchivesTabWidget::showArchiveListMenu() { // Construct menu. _archiveListMenu->clear(); if(!_ui->archiveListWidget->selectedItems().isEmpty()) { if(_ui->archiveListWidget->selectedItems().count() == 1) { _archiveListMenu->addAction(_ui->actionInspect); _archiveListMenu->addAction(_ui->actionRestore); } _archiveListMenu->addAction(_ui->actionDelete); } _archiveListMenu->addAction(_ui->actionRefresh); // Display menu. _archiveListMenu->popup(QCursor::pos()); } void ArchivesTabWidget::updateUi() { _ui->actionFilterArchives->setToolTip( _ui->actionFilterArchives->toolTip().arg( _ui->actionFilterArchives->shortcut().toString( QKeySequence::NativeText))); _ui->archivesFilter->setToolTip(_ui->archivesFilter->toolTip().arg( _ui->actionFilterArchives->shortcut().toString( QKeySequence::NativeText))); } void ArchivesTabWidget::displayInspectArchiveByRef(QString archiveName) { ArchivePtr archive = _ui->archiveListWidget->findArchiveByName(archiveName); displayInspectArchive(archive); } <commit_msg>ArchivesTabWidget: use default key handling<commit_after>#include "archivestabwidget.h" WARNINGS_DISABLE #include <QAction> #include <QComboBox> #include <QCoreApplication> #include <QCursor> #include <QEvent> #include <QEventLoop> #include <QKeyEvent> #include <QKeySequence> #include <QMenu> #include <QWidget> #include <Qt> #include "ui_archivestabwidget.h" WARNINGS_ENABLE #include "archivelistwidget.h" #include "archivewidget.h" #include "basetask.h" #include "persistentmodel/archive.h" ArchivesTabWidget::ArchivesTabWidget(QWidget *parent) : QWidget(parent), _ui(new Ui::ArchivesTabWidget) { // Ui initialization _ui->setupUi(this); updateUi(); // Basic UI setup. _ui->archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false); _ui->archiveDetailsWidget->hide(); _ui->archivesFilterFrame->hide(); // Context menu. _archiveListMenu = new QMenu(_ui->archiveListWidget); connect(_ui->archiveListWidget, &ArchiveListWidget::customContextMenuRequested, this, &ArchivesTabWidget::showArchiveListMenu); // Context menu actions. _ui->archiveListWidget->addAction(_ui->actionRefresh); _ui->archiveListWidget->addAction(_ui->actionInspect); _ui->archiveListWidget->addAction(_ui->actionDelete); _ui->archiveListWidget->addAction(_ui->actionRestore); connect(_ui->actionInspect, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::inspectSelectedItem); connect(_ui->actionDelete, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::deleteSelectedItems); connect(_ui->actionRestore, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::restoreSelectedItem); // Connections from the ArchiveListWidget. connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, this, &ArchivesTabWidget::displayInspectArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::clearInspectArchive, this, &ArchivesTabWidget::hideInspectArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::deleteArchives, this, &ArchivesTabWidget::deleteArchives); connect(_ui->archiveListWidget, &ArchiveListWidget::restoreArchive, this, &ArchivesTabWidget::restoreArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::displayJobDetails, [this](const QString &jobRef) { emit displayJobDetails(jobRef); }); connect(_ui->archiveListWidget, &ArchiveListWidget::countChanged, [this](int total, int visible) { _ui->archivesCountLabel->setText( tr("Archives (%1/%2)").arg(visible).arg(total)); }); // Connections to the ArchiveListWidget. connect(this, &ArchivesTabWidget::archiveList, _ui->archiveListWidget, &ArchiveListWidget::setArchives); connect(this, &ArchivesTabWidget::addArchive, _ui->archiveListWidget, &ArchiveListWidget::addArchive); // Connections from the ArchiveDetailsWidget. connect(_ui->archiveDetailsWidget, &ArchiveDetailsWidget::restoreArchive, this, &ArchivesTabWidget::restoreArchive); connect(_ui->archiveDetailsWidget, &ArchiveDetailsWidget::hidden, _ui->archiveListWidget, &ArchiveListWidget::noInspect); connect(_ui->archiveDetailsWidget, &ArchiveDetailsWidget::taskRequested, this, &ArchivesTabWidget::taskRequested); connect(_ui->archiveDetailsWidget, &ArchiveDetailsWidget::jobClicked, [this](const QString &jobRef) { emit jobClicked(jobRef); }); // Filtering. _ui->archiveListWidget->addAction(_ui->actionFilterArchives); _ui->archivesFilterButton->setDefaultAction(_ui->actionFilterArchives); connect(_ui->archivesFilter, &QComboBox::editTextChanged, _ui->archiveListWidget, &ArchiveListWidget::setFilter); connect(_ui->actionFilterArchives, &QAction::triggered, [this]() { _ui->archivesFilterFrame->setVisible( !_ui->archivesFilterFrame->isVisible()); if(_ui->archivesFilter->isVisible()) _ui->archivesFilter->setFocus(); else _ui->archivesFilter->clearEditText(); }); connect(_ui->archivesFilter, &QComboBox::editTextChanged, _ui->archiveListWidget, &ArchiveListWidget::setFilter); connect(_ui->archivesFilter, static_cast<void (QComboBox::*)(int)>( &QComboBox::currentIndexChanged), [this]() { _ui->archiveListWidget->setFocus(); }); } ArchivesTabWidget::~ArchivesTabWidget() { delete _ui; } void ArchivesTabWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { _ui->retranslateUi(this); updateUi(); } QWidget::changeEvent(event); } void ArchivesTabWidget::keyPressEvent(QKeyEvent *event) { switch(event->key()) { case Qt::Key_Escape: // Apply to the ArchiveDetailsWidget, if possible... if(_ui->archiveDetailsWidget->isVisible()) { _ui->archiveDetailsWidget->close(); return; } // ... otherwise, apply the archive filter, if possible... if(_ui->archivesFilter->isVisible()) { if(_ui->archivesFilter->currentText().isEmpty()) { _ui->actionFilterArchives->trigger(); } else { _ui->archivesFilter->clearEditText(); _ui->archivesFilter->setFocus(); } return; } // ... otherwise, use the default handling. break; } QWidget::keyPressEvent(event); } void ArchivesTabWidget::hideInspectArchive() { _ui->archiveDetailsWidget->hide(); } void ArchivesTabWidget::displayInspectArchive(ArchivePtr archive) { // Get the size. if(archive->sizeTotal() == 0) emit loadArchiveStats(archive); // Get the file list. if(archive->contents().count() == 0) emit loadArchiveContents(archive); // Highlight the row in the ArchiveListWidget. _ui->archiveListWidget->selectArchive(archive); // Display Archive details. _ui->archiveDetailsWidget->setArchive(archive); if(!_ui->archiveDetailsWidget->isVisible()) { _ui->archiveDetailsWidget->show(); // Allow the event loop to update the geometry of the scroll area. // I haven't found a way to fix this without dropping back to the // main event loop. :( QCoreApplication::processEvents(QEventLoop::AllEvents, 10); } // Make sure we can see it in the Archive List. Must be after showing // the ArchiveDetailsWidget, otherwise the highlighted row might be // "visible" underneath the newly-expanded ArchiveDetailsWidget. _ui->archiveListWidget->ensureCurrentItemVisible(); } void ArchivesTabWidget::showArchiveListMenu() { // Construct menu. _archiveListMenu->clear(); if(!_ui->archiveListWidget->selectedItems().isEmpty()) { if(_ui->archiveListWidget->selectedItems().count() == 1) { _archiveListMenu->addAction(_ui->actionInspect); _archiveListMenu->addAction(_ui->actionRestore); } _archiveListMenu->addAction(_ui->actionDelete); } _archiveListMenu->addAction(_ui->actionRefresh); // Display menu. _archiveListMenu->popup(QCursor::pos()); } void ArchivesTabWidget::updateUi() { _ui->actionFilterArchives->setToolTip( _ui->actionFilterArchives->toolTip().arg( _ui->actionFilterArchives->shortcut().toString( QKeySequence::NativeText))); _ui->archivesFilter->setToolTip(_ui->archivesFilter->toolTip().arg( _ui->actionFilterArchives->shortcut().toString( QKeySequence::NativeText))); } void ArchivesTabWidget::displayInspectArchiveByRef(QString archiveName) { ArchivePtr archive = _ui->archiveListWidget->findArchiveByName(archiveName); displayInspectArchive(archive); } <|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 <iostream> #include <string> #include <cstdlib> #include <boost/program_options.hpp> #include <boost/lambda/bind.hpp> #include <boost/lambda/lambda.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/noncopyable.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/exception/diagnostic_information.hpp> #include <boost/scope_exit.hpp> #include <vespa/fastos/app.h> #include <vespa/config-zookeepers.h> #include <vespa/fileacquirer/config-filedistributorrpc.h> #include <vespa/filedistribution/distributor/config-filedistributor.h> #include <vespa/filedistribution/model/config-filereferences.h> #include <vespa/filedistribution/distributor/filedistributortrackerimpl.h> #include <vespa/filedistribution/distributor/filedownloadermanager.h> #include <vespa/filedistribution/distributor/filedownloader.h> #include <vespa/filedistribution/distributor/signalhandling.h> #include <vespa/filedistribution/distributor/state_server_impl.h> #include <vespa/filedistribution/model/filedistributionmodelimpl.h> #include <vespa/filedistribution/rpc/filedistributorrpc.h> #include <vespa/filedistribution/common/exception.h> #include <vespa/filedistribution/common/componentsdeleter.h> namespace { const char* programName = "filedistributor"; } #include <vespa/log/log.h> LOG_SETUP(programName); namespace ll = boost::lambda; using namespace filedistribution; using cloud::config::ZookeepersConfig; using cloud::config::filedistribution::FiledistributorConfig; using cloud::config::filedistribution::FiledistributorrpcConfig; class FileDistributor : public config::IFetcherCallback<ZookeepersConfig>, public config::IFetcherCallback<FiledistributorConfig>, public config::IFetcherCallback<FiledistributorrpcConfig>, public config::IGenerationCallback, boost::noncopyable { class Components : boost::noncopyable { ComponentsDeleter _componentsDeleter; public: const boost::shared_ptr<ZKFacade> _zk; const boost::shared_ptr<FileDistributionModelImpl> _model; const boost::shared_ptr<FileDistributorTrackerImpl> _tracker; const boost::shared_ptr<FileDownloader> _downloader; const boost::shared_ptr<FileDownloaderManager> _manager; const boost::shared_ptr<FileDistributorRPC> _rpcHandler; const boost::shared_ptr<StateServerImpl> _stateServer; private: boost::thread _downloaderEventLoopThread; config::ConfigFetcher _configFetcher; template <class T> typename boost::shared_ptr<T> track(T* component) { return _componentsDeleter.track(component); } public: Components(const boost::shared_ptr<ExceptionRethrower>& exceptionRethrower, const config::ConfigUri & configUri, const ZookeepersConfig& zooKeepersConfig, const FiledistributorConfig& fileDistributorConfig, const FiledistributorrpcConfig& rpcConfig) :_zk(track(new ZKFacade(zooKeepersConfig.zookeeperserverlist, exceptionRethrower))), _model(track(new FileDistributionModelImpl( fileDistributorConfig.hostname, fileDistributorConfig.torrentport, _zk, exceptionRethrower))), _tracker(track(new FileDistributorTrackerImpl(_model, exceptionRethrower))), _downloader(track(new FileDownloader( _tracker, fileDistributorConfig.hostname, fileDistributorConfig.torrentport, boost::filesystem::path(fileDistributorConfig.filedbpath), exceptionRethrower))), _manager(track(new FileDownloaderManager(_downloader, _model))), _rpcHandler(track(new FileDistributorRPC(rpcConfig.connectionspec, _manager))), _stateServer(track(new StateServerImpl(fileDistributorConfig.stateport))), _downloaderEventLoopThread( ll::bind(&FileDownloader::runEventLoop, _downloader.get())), _configFetcher(configUri.getContext()) { _manager->start(); _rpcHandler->start(); _tracker->setDownloader(_downloader); _configFetcher.subscribe<FilereferencesConfig>(configUri.getConfigId(), _model.get()); _configFetcher.start(); updatedConfig(_configFetcher.getGeneration()); } void updatedConfig(int64_t generation) { vespalib::ComponentConfigProducer::Config curr("filedistributor", generation); _stateServer->myComponents.addConfig(curr); } ~Components() { _configFetcher.close(); //Do not waste time retrying zookeeper operations when going down. _zk->disableRetries(); _downloaderEventLoopThread.interrupt(); _downloaderEventLoopThread.join(); } }; typedef boost::lock_guard<boost::mutex> LockGuard; boost::mutex _configMutex; bool _completeReconfigurationNeeded; std::unique_ptr<ZookeepersConfig> _zooKeepersConfig; std::unique_ptr<FiledistributorConfig> _fileDistributorConfig; std::unique_ptr<FiledistributorrpcConfig> _rpcConfig; boost::shared_ptr<ExceptionRethrower> _exceptionRethrower; std::unique_ptr<Components> _components; public: FileDistributor() : _configMutex(), _completeReconfigurationNeeded(false), _zooKeepersConfig(), _fileDistributorConfig(), _rpcConfig(), _exceptionRethrower(), _components() { } void notifyGenerationChange(int64_t generation) { if (_components && ! completeReconfigurationNeeded()) { _components->updatedConfig(generation); } } //configure overrides void configure(std::unique_ptr<ZookeepersConfig> config) { LockGuard guard(_configMutex); _zooKeepersConfig = std::move(config); _completeReconfigurationNeeded = true; } void configure(std::unique_ptr<FiledistributorConfig> config) { LockGuard guard(_configMutex); if (_fileDistributorConfig.get() != NULL && (config->torrentport != _fileDistributorConfig->torrentport || config->stateport != _fileDistributorConfig->stateport || config->hostname != _fileDistributorConfig->hostname || config->filedbpath != _fileDistributorConfig->filedbpath)) { _completeReconfigurationNeeded = true; } else if (_components.get()) { configureSpeedLimits(*config); } _fileDistributorConfig = std::move(config); } void configure(std::unique_ptr<FiledistributorrpcConfig> config) { LockGuard guard(_configMutex); _rpcConfig = std::move(config); _completeReconfigurationNeeded = true; } void run(const config::ConfigUri & configUri) { while (!askedToShutDown()) { clearReinitializeFlag(); _exceptionRethrower.reset(new ExceptionRethrower()); runImpl(configUri); if (_exceptionRethrower->exceptionStored()) _exceptionRethrower->rethrow(); } } static void ensureExceptionsStored(const boost::shared_ptr<ExceptionRethrower>& exceptionRethrower) { //TODO: this is somewhat hackish, refactor to eliminate this later. LOG(debug, "Waiting for shutdown"); for (int i=0; i<50 && !exceptionRethrower.unique(); ++i) { boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } LOG(debug, "Done waiting for shutdown"); if (!exceptionRethrower.unique()) { EV_STOPPING(programName, "Forced termination"); kill(getpid(), SIGKILL); } } void createComponents(const boost::shared_ptr<ExceptionRethrower>& exceptionRethrower, const config::ConfigUri & configUri) { LockGuard guard(_configMutex); _components.reset( new Components(exceptionRethrower, configUri, *_zooKeepersConfig, *_fileDistributorConfig, *_rpcConfig)); configureSpeedLimits(*_fileDistributorConfig); _completeReconfigurationNeeded = false; } bool completeReconfigurationNeeded() { LockGuard guard(_configMutex); if (_completeReconfigurationNeeded) { LOG(debug, "Complete reconfiguration needed"); } return _completeReconfigurationNeeded; } void configureSpeedLimits(const FiledistributorConfig& config) { FileDownloader& downloader = *_components->_downloader; downloader.setMaxDownloadSpeed(config.maxdownloadspeed); downloader.setMaxUploadSpeed(config.maxuploadspeed); } //avoid warning due to scope exit macro #pragma GCC diagnostic ignored "-Wshadow" void runImpl(const config::ConfigUri & configUri) { BOOST_SCOPE_EXIT((&_components)(&_exceptionRethrower)) { _components.reset(); //Ensures that any exception stored during destruction will be available when returning. ensureExceptionsStored(_exceptionRethrower); } BOOST_SCOPE_EXIT_END createComponents(_exceptionRethrower, configUri); // We do not want back to back reinitializing as it gives zero time for serving // some torrents. int postPoneAskedToReinitializedSecs = 50; while (!askedToShutDown() && (postPoneAskedToReinitializedSecs > 0 || !askedToReinitialize()) && !completeReconfigurationNeeded() && !_exceptionRethrower->exceptionStored()) { postPoneAskedToReinitializedSecs--; boost::this_thread::sleep(boost::posix_time::seconds(1)); } } }; //TODO: use pop in gcc 4.6 #pragma GCC diagnostic warning "-Wshadow" class FileDistributorApplication : public FastOS_Application { const config::ConfigUri _configUri; public: FileDistributorApplication(const config::ConfigUri & configUri); //overrides int Main(); }; namespace { struct ProgramOptionException { std::string _msg; ProgramOptionException(const std::string & msg) : _msg(msg) {} }; bool exists(const std::string& optionName, const boost::program_options::variables_map& map) { return map.find(optionName) != map.end(); } void ensureExists(const std::string& optionName, const boost::program_options::variables_map& map \ ) { if (!exists(optionName, map)) { throw ProgramOptionException("Error: Missing option " + optionName); } } } //anonymous namespace FileDistributorApplication::FileDistributorApplication(const config::ConfigUri & configUri) :_configUri(configUri) { } int FileDistributorApplication::Main() { try { FileDistributor distributor; config::ConfigFetcher configFetcher(_configUri.getContext()); configFetcher.subscribe<ZookeepersConfig>(_configUri.getConfigId(), &distributor); configFetcher.subscribe<FiledistributorConfig>(_configUri.getConfigId(), &distributor); configFetcher.subscribe<FiledistributorrpcConfig>(_configUri.getConfigId(), &distributor); configFetcher.subscribeGenerationChanges(&distributor); configFetcher.start(); distributor.run(_configUri); EV_STOPPING(programName, "Clean exit"); return 0; } catch(const FileDoesNotExistException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 1; } catch(const ZKNodeDoesNotExistsException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 2; } catch(const ZKSessionExpired & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 3; } catch(const config::ConfigTimeoutException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 4; } catch(const FailedListeningException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 5; } catch(const ZKGenericException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 99; } catch(const boost::unknown_exception & e) { std::string s = boost::diagnostic_information(e); LOG(warning, "Caught '%s'", s.c_str()); EV_STOPPING(programName, s.c_str()); return 255; #if 0 /* These are kept hanging around for reference as to how it was when we just held our ears singing "na, na, na, na..." no matter if the sun was shining or if the world imploded. */ } catch(const boost::exception& e) { std::string s = boost::diagnostic_information(e); LOG(error, "Caught '%s'", s.c_str()); EV_STOPPING(programName, s.c_str()); return -1; } catch(const std::string& msg) { std::string s = "Error: " + msg; LOG(error, "Caught '%s'", s.c_str()); EV_STOPPING(programName, s.c_str()); return -1; #endif } } int executeApplication(int argc, char** argv) { const char *configId("configid"), *help("help"); namespace po = boost::program_options; po::options_description description; description.add_options() (configId, po::value<std::string > (), "id to request config for") (help, "help"); try { po::variables_map values; po::store( po::parse_command_line(argc, argv, description), values); if (exists(help, values)) { std::cout <<description; return 0; } ensureExists(configId, values); FileDistributorApplication application( values[configId].as<std::string > ()); return application.Entry(argc, argv); } catch(ProgramOptionException& e) { std::cerr <<e._msg <<std::endl; return -1; } } int main(int argc, char** argv) { EV_STARTED(programName); initSignals(); std::srand(std::time(0)); filedistribution::ZKLogging loggingGuard; return executeApplication(argc, argv); } <commit_msg>Install signals very early.<commit_after>// 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 <iostream> #include <string> #include <cstdlib> #include <boost/program_options.hpp> #include <boost/lambda/bind.hpp> #include <boost/lambda/lambda.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/noncopyable.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/exception/diagnostic_information.hpp> #include <boost/scope_exit.hpp> #include <vespa/fastos/app.h> #include <vespa/config-zookeepers.h> #include <vespa/fileacquirer/config-filedistributorrpc.h> #include <vespa/filedistribution/distributor/config-filedistributor.h> #include <vespa/filedistribution/model/config-filereferences.h> #include <vespa/filedistribution/distributor/filedistributortrackerimpl.h> #include <vespa/filedistribution/distributor/filedownloadermanager.h> #include <vespa/filedistribution/distributor/filedownloader.h> #include <vespa/filedistribution/distributor/signalhandling.h> #include <vespa/filedistribution/distributor/state_server_impl.h> #include <vespa/filedistribution/model/filedistributionmodelimpl.h> #include <vespa/filedistribution/rpc/filedistributorrpc.h> #include <vespa/filedistribution/common/exception.h> #include <vespa/filedistribution/common/componentsdeleter.h> namespace { const char* programName = "filedistributor"; } #include <vespa/log/log.h> LOG_SETUP(programName); namespace ll = boost::lambda; using namespace filedistribution; using cloud::config::ZookeepersConfig; using cloud::config::filedistribution::FiledistributorConfig; using cloud::config::filedistribution::FiledistributorrpcConfig; class FileDistributor : public config::IFetcherCallback<ZookeepersConfig>, public config::IFetcherCallback<FiledistributorConfig>, public config::IFetcherCallback<FiledistributorrpcConfig>, public config::IGenerationCallback, boost::noncopyable { class Components : boost::noncopyable { ComponentsDeleter _componentsDeleter; public: const boost::shared_ptr<ZKFacade> _zk; const boost::shared_ptr<FileDistributionModelImpl> _model; const boost::shared_ptr<FileDistributorTrackerImpl> _tracker; const boost::shared_ptr<FileDownloader> _downloader; const boost::shared_ptr<FileDownloaderManager> _manager; const boost::shared_ptr<FileDistributorRPC> _rpcHandler; const boost::shared_ptr<StateServerImpl> _stateServer; private: boost::thread _downloaderEventLoopThread; config::ConfigFetcher _configFetcher; template <class T> typename boost::shared_ptr<T> track(T* component) { return _componentsDeleter.track(component); } public: Components(const boost::shared_ptr<ExceptionRethrower>& exceptionRethrower, const config::ConfigUri & configUri, const ZookeepersConfig& zooKeepersConfig, const FiledistributorConfig& fileDistributorConfig, const FiledistributorrpcConfig& rpcConfig) :_zk(track(new ZKFacade(zooKeepersConfig.zookeeperserverlist, exceptionRethrower))), _model(track(new FileDistributionModelImpl( fileDistributorConfig.hostname, fileDistributorConfig.torrentport, _zk, exceptionRethrower))), _tracker(track(new FileDistributorTrackerImpl(_model, exceptionRethrower))), _downloader(track(new FileDownloader( _tracker, fileDistributorConfig.hostname, fileDistributorConfig.torrentport, boost::filesystem::path(fileDistributorConfig.filedbpath), exceptionRethrower))), _manager(track(new FileDownloaderManager(_downloader, _model))), _rpcHandler(track(new FileDistributorRPC(rpcConfig.connectionspec, _manager))), _stateServer(track(new StateServerImpl(fileDistributorConfig.stateport))), _downloaderEventLoopThread( ll::bind(&FileDownloader::runEventLoop, _downloader.get())), _configFetcher(configUri.getContext()) { _manager->start(); _rpcHandler->start(); _tracker->setDownloader(_downloader); _configFetcher.subscribe<FilereferencesConfig>(configUri.getConfigId(), _model.get()); _configFetcher.start(); updatedConfig(_configFetcher.getGeneration()); } void updatedConfig(int64_t generation) { vespalib::ComponentConfigProducer::Config curr("filedistributor", generation); _stateServer->myComponents.addConfig(curr); } ~Components() { _configFetcher.close(); //Do not waste time retrying zookeeper operations when going down. _zk->disableRetries(); _downloaderEventLoopThread.interrupt(); _downloaderEventLoopThread.join(); } }; typedef boost::lock_guard<boost::mutex> LockGuard; boost::mutex _configMutex; bool _completeReconfigurationNeeded; std::unique_ptr<ZookeepersConfig> _zooKeepersConfig; std::unique_ptr<FiledistributorConfig> _fileDistributorConfig; std::unique_ptr<FiledistributorrpcConfig> _rpcConfig; boost::shared_ptr<ExceptionRethrower> _exceptionRethrower; std::unique_ptr<Components> _components; public: FileDistributor() : _configMutex(), _completeReconfigurationNeeded(false), _zooKeepersConfig(), _fileDistributorConfig(), _rpcConfig(), _exceptionRethrower(), _components() { } void notifyGenerationChange(int64_t generation) { if (_components && ! completeReconfigurationNeeded()) { _components->updatedConfig(generation); } } //configure overrides void configure(std::unique_ptr<ZookeepersConfig> config) { LockGuard guard(_configMutex); _zooKeepersConfig = std::move(config); _completeReconfigurationNeeded = true; } void configure(std::unique_ptr<FiledistributorConfig> config) { LockGuard guard(_configMutex); if (_fileDistributorConfig.get() != NULL && (config->torrentport != _fileDistributorConfig->torrentport || config->stateport != _fileDistributorConfig->stateport || config->hostname != _fileDistributorConfig->hostname || config->filedbpath != _fileDistributorConfig->filedbpath)) { _completeReconfigurationNeeded = true; } else if (_components.get()) { configureSpeedLimits(*config); } _fileDistributorConfig = std::move(config); } void configure(std::unique_ptr<FiledistributorrpcConfig> config) { LockGuard guard(_configMutex); _rpcConfig = std::move(config); _completeReconfigurationNeeded = true; } void run(const config::ConfigUri & configUri) { while (!askedToShutDown()) { clearReinitializeFlag(); _exceptionRethrower.reset(new ExceptionRethrower()); runImpl(configUri); if (_exceptionRethrower->exceptionStored()) _exceptionRethrower->rethrow(); } } static void ensureExceptionsStored(const boost::shared_ptr<ExceptionRethrower>& exceptionRethrower) { //TODO: this is somewhat hackish, refactor to eliminate this later. LOG(debug, "Waiting for shutdown"); for (int i=0; i<50 && !exceptionRethrower.unique(); ++i) { boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } LOG(debug, "Done waiting for shutdown"); if (!exceptionRethrower.unique()) { EV_STOPPING(programName, "Forced termination"); kill(getpid(), SIGKILL); } } void createComponents(const boost::shared_ptr<ExceptionRethrower>& exceptionRethrower, const config::ConfigUri & configUri) { LockGuard guard(_configMutex); _components.reset( new Components(exceptionRethrower, configUri, *_zooKeepersConfig, *_fileDistributorConfig, *_rpcConfig)); configureSpeedLimits(*_fileDistributorConfig); _completeReconfigurationNeeded = false; } bool completeReconfigurationNeeded() { LockGuard guard(_configMutex); if (_completeReconfigurationNeeded) { LOG(debug, "Complete reconfiguration needed"); } return _completeReconfigurationNeeded; } void configureSpeedLimits(const FiledistributorConfig& config) { FileDownloader& downloader = *_components->_downloader; downloader.setMaxDownloadSpeed(config.maxdownloadspeed); downloader.setMaxUploadSpeed(config.maxuploadspeed); } //avoid warning due to scope exit macro #pragma GCC diagnostic ignored "-Wshadow" void runImpl(const config::ConfigUri & configUri) { BOOST_SCOPE_EXIT((&_components)(&_exceptionRethrower)) { _components.reset(); //Ensures that any exception stored during destruction will be available when returning. ensureExceptionsStored(_exceptionRethrower); } BOOST_SCOPE_EXIT_END createComponents(_exceptionRethrower, configUri); // We do not want back to back reinitializing as it gives zero time for serving // some torrents. int postPoneAskedToReinitializedSecs = 50; while (!askedToShutDown() && (postPoneAskedToReinitializedSecs > 0 || !askedToReinitialize()) && !completeReconfigurationNeeded() && !_exceptionRethrower->exceptionStored()) { postPoneAskedToReinitializedSecs--; boost::this_thread::sleep(boost::posix_time::seconds(1)); } } }; //TODO: use pop in gcc 4.6 #pragma GCC diagnostic warning "-Wshadow" class FileDistributorApplication : public FastOS_Application { const config::ConfigUri _configUri; public: FileDistributorApplication(const config::ConfigUri & configUri); //overrides int Main(); }; namespace { struct ProgramOptionException { std::string _msg; ProgramOptionException(const std::string & msg) : _msg(msg) {} }; bool exists(const std::string& optionName, const boost::program_options::variables_map& map) { return map.find(optionName) != map.end(); } void ensureExists(const std::string& optionName, const boost::program_options::variables_map& map \ ) { if (!exists(optionName, map)) { throw ProgramOptionException("Error: Missing option " + optionName); } } } //anonymous namespace FileDistributorApplication::FileDistributorApplication(const config::ConfigUri & configUri) :_configUri(configUri) { } int FileDistributorApplication::Main() { try { FileDistributor distributor; config::ConfigFetcher configFetcher(_configUri.getContext()); configFetcher.subscribe<ZookeepersConfig>(_configUri.getConfigId(), &distributor); configFetcher.subscribe<FiledistributorConfig>(_configUri.getConfigId(), &distributor); configFetcher.subscribe<FiledistributorrpcConfig>(_configUri.getConfigId(), &distributor); configFetcher.subscribeGenerationChanges(&distributor); configFetcher.start(); distributor.run(_configUri); EV_STOPPING(programName, "Clean exit"); return 0; } catch(const FileDoesNotExistException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 1; } catch(const ZKNodeDoesNotExistsException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 2; } catch(const ZKSessionExpired & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 3; } catch(const config::ConfigTimeoutException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 4; } catch(const FailedListeningException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 5; } catch(const ZKGenericException & e) { std::string s = boost::diagnostic_information(e); EV_STOPPING(programName, s.c_str()); return 99; } catch(const boost::unknown_exception & e) { std::string s = boost::diagnostic_information(e); LOG(warning, "Caught '%s'", s.c_str()); EV_STOPPING(programName, s.c_str()); return 255; #if 0 /* These are kept hanging around for reference as to how it was when we just held our ears singing "na, na, na, na..." no matter if the sun was shining or if the world imploded. */ } catch(const boost::exception& e) { std::string s = boost::diagnostic_information(e); LOG(error, "Caught '%s'", s.c_str()); EV_STOPPING(programName, s.c_str()); return -1; } catch(const std::string& msg) { std::string s = "Error: " + msg; LOG(error, "Caught '%s'", s.c_str()); EV_STOPPING(programName, s.c_str()); return -1; #endif } } int executeApplication(int argc, char** argv) { const char *configId("configid"), *help("help"); namespace po = boost::program_options; po::options_description description; description.add_options() (configId, po::value<std::string > (), "id to request config for") (help, "help"); try { po::variables_map values; po::store( po::parse_command_line(argc, argv, description), values); if (exists(help, values)) { std::cout <<description; return 0; } ensureExists(configId, values); FileDistributorApplication application( values[configId].as<std::string > ()); return application.Entry(argc, argv); } catch(ProgramOptionException& e) { std::cerr <<e._msg <<std::endl; return -1; } } namespace { class InitSignals { public: InitSignals() { initSignals(); } }; InitSignals _G_initSignals; } int main(int argc, char** argv) { if (askedToShutDown()) { return 0; } EV_STARTED(programName); std::srand(std::time(0)); filedistribution::ZKLogging loggingGuard; return executeApplication(argc, argv); } <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2013-12-17 Tobias Stollenwerk <Tobias.Stollenwerk@dlr.de> * * 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. */ /** * @file * @brief Implementation of CPACS wing profile as a CST profile * * The wing profile is defined by the (C)lass function / (S)hape function (T)ransformation * geometry representation method. */ #include "CCPACSWingProfileCST.h" #include "CCSTCurveBuilder.h" #include "CTiglError.h" #include "CTiglTypeRegistry.h" #include "CTiglLogging.h" #include "CTiglTransformation.h" #include "CWireToCurve.h" #include "CCPACSWingProfileFactory.h" #include "TixiSaveExt.h" #include "math.h" #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <Geom_BSplineCurve.hxx> namespace tigl { namespace { // helper function to read in tixi vector std::vector<double> readTixiVector (TixiDocumentHandle tixiHandle, const std::string& xpath, const std::string& name, const std::string& funcname) { std::string fullpath = xpath + name; int count; if (tixiGetVectorSize(tixiHandle, fullpath.c_str(), &count) != SUCCESS) { throw CTiglError("Error: XML error while reading vector <" + name + "> in " + funcname, TIGL_XML_ERROR); } double *tmp; if (tixiGetFloatVector(tixiHandle, fullpath.c_str(), &tmp, count) != SUCCESS) { throw CTiglError("Error: XML error while reading vector <" + name + "> in " + funcname, TIGL_XML_ERROR); } std::vector<double> res(tmp, tmp+count); return res; } // helper function to read in tixi double double readTixiDouble (TixiDocumentHandle tixiHandle, const std::string& xpath, const std::string& name, const std::string& funcname) { std::string fullpath = xpath + name; double res; if (tixiGetDoubleElement(tixiHandle, fullpath.c_str(), &res) != SUCCESS) { throw CTiglError("Error: XML error while reading double <" + name + "> in " + funcname, TIGL_XML_ERROR); } return res; } } // anonymous namespace // register profile algo at factory PTiglWingProfileAlgo CreateProfileCST(const CCPACSWingProfile& profile, const std::string& cpacsPath) { return PTiglWingProfileAlgo(new CCPACSWingProfileCST(profile, cpacsPath)); } AUTORUN(CCPACSWingProfileCST) { return CCPACSWingProfileFactory::Instance().RegisterAlgo(CCPACSWingProfileCST::CPACSID(), CreateProfileCST); } // Constructor CCPACSWingProfileCST::CCPACSWingProfileCST(const CCPACSWingProfile& profile, const std::string& path) { ProfileDataXPath=path + "/" + CPACSID(); trailingEdge.Nullify(); } // Destructor CCPACSWingProfileCST::~CCPACSWingProfileCST(void) { } std::string CCPACSWingProfileCST::CPACSID() { return "cst2D"; } // Cleanup routine void CCPACSWingProfileCST::Cleanup(void) { upperB.clear(); lowerB.clear(); trailingEdge.Nullify(); } void CCPACSWingProfileCST::Update(void) { BuildWires(); } // Read wing profile file void CCPACSWingProfileCST::ReadCPACS(TixiDocumentHandle tixiHandle) { upperB=readTixiVector(tixiHandle, ProfileDataXPath, "/upperB", "CCPACSWingProfileCST::ReadCPACS"); lowerB=readTixiVector(tixiHandle, ProfileDataXPath, "/lowerB", "CCPACSWingProfileCST::ReadCPACS"); upperN1=readTixiDouble(tixiHandle, ProfileDataXPath, "/upperN1", "CCPACSWingProfileCST::ReadCPACS"); upperN2=readTixiDouble(tixiHandle, ProfileDataXPath, "/upperN2", "CCPACSWingProfileCST::ReadCPACS"); lowerN1=readTixiDouble(tixiHandle, ProfileDataXPath, "/lowerN1", "CCPACSWingProfileCST::ReadCPACS"); lowerN2=readTixiDouble(tixiHandle, ProfileDataXPath, "/lowerN2", "CCPACSWingProfileCST::ReadCPACS"); } // Write CPACS wing profile void CCPACSWingProfileCST::WriteCPACS(TixiDocumentHandle tixiHandle, const std::string& ProfileXPath) { // Set the element "point" TixiSaveExt::TixiSaveElement(tixiHandle, ProfileXPath.c_str(), CPACSID().c_str() ); std::string elementPath = ProfileXPath + "/" + CPACSID(); TixiSaveExt::TixiSaveVector(tixiHandle, elementPath, "upperB", upperB); TixiSaveExt::TixiSaveVector(tixiHandle, elementPath, "lowerB", lowerB); TixiSaveExt::TixiSaveDoubleElement(tixiHandle, elementPath.c_str(), "upperN1", upperN1); TixiSaveExt::TixiSaveDoubleElement(tixiHandle, elementPath.c_str(), "upperN2", upperN2); TixiSaveExt::TixiSaveDoubleElement(tixiHandle, elementPath.c_str(), "lowerN1", lowerN1); TixiSaveExt::TixiSaveDoubleElement(tixiHandle, elementPath.c_str(), "lowerN2", lowerN2); } // Builds the wing profile wire. The returned wire is already transformed by the // wing profile element transformation. void CCPACSWingProfileCST::BuildWires() { gp_Trsf yzSwitch; yzSwitch.SetMirror(gp_Ax2(gp_Pnt(0.,0.,0.), gp_Dir(0.,-1.,1.))); // Build upper wire CCSTCurveBuilder upperBuilder(upperN1, upperN2, upperB); Handle_Geom_BSplineCurve upperCurve = upperBuilder.Curve(); upperCurve->Transform(yzSwitch); upperWire = BRepBuilderAPI_MakeEdge(upperCurve); // Build lower curve, std::vector<double> binv; for (unsigned int i = 0; i < lowerB.size(); ++i) { binv.push_back(-lowerB[i]); } CCSTCurveBuilder lowerBuilder(lowerN1, lowerN2, binv); Handle_Geom_BSplineCurve lowerCurve = lowerBuilder.Curve(); lowerCurve->Transform(yzSwitch); lowerCurve->Reverse(); lowerWire = BRepBuilderAPI_MakeEdge(lowerCurve); BRepBuilderAPI_MakeWire upperLowerWireMaker(lowerWire, upperWire); TopoDS_Wire upperLowerWire = upperLowerWireMaker.Wire(); // conatenate wire Handle_Geom_Curve upperLowerCurve = CWireToCurve(upperLowerWire).curve(); upperLowerEdge = BRepBuilderAPI_MakeEdge(upperLowerCurve); tePoint = gp_Pnt(1,0,0); lePoint = gp_Pnt(0,0,0); } // Returns sample points std::vector<CTiglPoint*> CCPACSWingProfileCST::GetSamplePoints() const { std::vector<CTiglPoint*> empty; return empty; } // get profiles CPACS XML path const std::string & CCPACSWingProfileCST::GetProfileDataXPath() const { return ProfileDataXPath; } // Getter for upper wire of closed profile const TopoDS_Edge& CCPACSWingProfileCST::GetUpperWireClosed() const { return upperWire; } // Getter for lower wire of closed profile const TopoDS_Edge& CCPACSWingProfileCST::GetLowerWireClosed() const { return lowerWire; } // Getter for upper wire of opened profile const TopoDS_Edge& CCPACSWingProfileCST::GetUpperWireOpened() const { throw CTiglError("ERROR: GetUpperWireOpened not implemented yet for CCPACSWingProfileCST!"); } // Getter for lower wire of opened profile const TopoDS_Edge& CCPACSWingProfileCST::GetLowerWireOpened() const { throw CTiglError("ERROR: GetLowerWireOpened not implemented yet for CCPACSWingProfileCST!"); } // get upper wing profile wire const TopoDS_Edge & CCPACSWingProfileCST::GetUpperWire() const { return upperWire; } // get lower wing profile wire const TopoDS_Edge & CCPACSWingProfileCST::GetLowerWire() const { return lowerWire; } // gets the upper and lower wing profile into on edge const TopoDS_Edge & CCPACSWingProfileCST::GetUpperLowerWire() const { return upperLowerEdge; } // get trailing edge const TopoDS_Edge & CCPACSWingProfileCST::GetTrailingEdge() const { return trailingEdge; } // get trailing edge const TopoDS_Edge & CCPACSWingProfileCST::GetTrailingEdgeOpened() const { throw CTiglError("ERROR: GetTrailingEdgeOpened not implemented yet for CCPACSWingProfileCST!"); } // get leading edge point(); const gp_Pnt & CCPACSWingProfileCST::GetLEPoint() const { return lePoint; } // get trailing edge point(); const gp_Pnt & CCPACSWingProfileCST::GetTEPoint() const { return tePoint; } } // end namespace tigl <commit_msg>Fix for build issue with OCE 17 by including Standard_Version.hxx<commit_after>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2013-12-17 Tobias Stollenwerk <Tobias.Stollenwerk@dlr.de> * * 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. */ /** * @file * @brief Implementation of CPACS wing profile as a CST profile * * The wing profile is defined by the (C)lass function / (S)hape function (T)ransformation * geometry representation method. */ #include "CCPACSWingProfileCST.h" #include "CCSTCurveBuilder.h" #include "CTiglError.h" #include "CTiglTypeRegistry.h" #include "CTiglLogging.h" #include "CTiglTransformation.h" #include "CWireToCurve.h" #include "CCPACSWingProfileFactory.h" #include "TixiSaveExt.h" #include "math.h" #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <Geom_BSplineCurve.hxx> #include <Standard_Version.hxx> namespace tigl { namespace { // helper function to read in tixi vector std::vector<double> readTixiVector (TixiDocumentHandle tixiHandle, const std::string& xpath, const std::string& name, const std::string& funcname) { std::string fullpath = xpath + name; int count; if (tixiGetVectorSize(tixiHandle, fullpath.c_str(), &count) != SUCCESS) { throw CTiglError("Error: XML error while reading vector <" + name + "> in " + funcname, TIGL_XML_ERROR); } double *tmp; if (tixiGetFloatVector(tixiHandle, fullpath.c_str(), &tmp, count) != SUCCESS) { throw CTiglError("Error: XML error while reading vector <" + name + "> in " + funcname, TIGL_XML_ERROR); } std::vector<double> res(tmp, tmp+count); return res; } // helper function to read in tixi double double readTixiDouble (TixiDocumentHandle tixiHandle, const std::string& xpath, const std::string& name, const std::string& funcname) { std::string fullpath = xpath + name; double res; if (tixiGetDoubleElement(tixiHandle, fullpath.c_str(), &res) != SUCCESS) { throw CTiglError("Error: XML error while reading double <" + name + "> in " + funcname, TIGL_XML_ERROR); } return res; } } // anonymous namespace // register profile algo at factory PTiglWingProfileAlgo CreateProfileCST(const CCPACSWingProfile& profile, const std::string& cpacsPath) { return PTiglWingProfileAlgo(new CCPACSWingProfileCST(profile, cpacsPath)); } AUTORUN(CCPACSWingProfileCST) { return CCPACSWingProfileFactory::Instance().RegisterAlgo(CCPACSWingProfileCST::CPACSID(), CreateProfileCST); } // Constructor CCPACSWingProfileCST::CCPACSWingProfileCST(const CCPACSWingProfile& profile, const std::string& path) { ProfileDataXPath=path + "/" + CPACSID(); trailingEdge.Nullify(); } // Destructor CCPACSWingProfileCST::~CCPACSWingProfileCST(void) { } std::string CCPACSWingProfileCST::CPACSID() { return "cst2D"; } // Cleanup routine void CCPACSWingProfileCST::Cleanup(void) { upperB.clear(); lowerB.clear(); trailingEdge.Nullify(); } void CCPACSWingProfileCST::Update(void) { BuildWires(); } // Read wing profile file void CCPACSWingProfileCST::ReadCPACS(TixiDocumentHandle tixiHandle) { upperB=readTixiVector(tixiHandle, ProfileDataXPath, "/upperB", "CCPACSWingProfileCST::ReadCPACS"); lowerB=readTixiVector(tixiHandle, ProfileDataXPath, "/lowerB", "CCPACSWingProfileCST::ReadCPACS"); upperN1=readTixiDouble(tixiHandle, ProfileDataXPath, "/upperN1", "CCPACSWingProfileCST::ReadCPACS"); upperN2=readTixiDouble(tixiHandle, ProfileDataXPath, "/upperN2", "CCPACSWingProfileCST::ReadCPACS"); lowerN1=readTixiDouble(tixiHandle, ProfileDataXPath, "/lowerN1", "CCPACSWingProfileCST::ReadCPACS"); lowerN2=readTixiDouble(tixiHandle, ProfileDataXPath, "/lowerN2", "CCPACSWingProfileCST::ReadCPACS"); } // Write CPACS wing profile void CCPACSWingProfileCST::WriteCPACS(TixiDocumentHandle tixiHandle, const std::string& ProfileXPath) { // Set the element "point" TixiSaveExt::TixiSaveElement(tixiHandle, ProfileXPath.c_str(), CPACSID().c_str() ); std::string elementPath = ProfileXPath + "/" + CPACSID(); TixiSaveExt::TixiSaveVector(tixiHandle, elementPath, "upperB", upperB); TixiSaveExt::TixiSaveVector(tixiHandle, elementPath, "lowerB", lowerB); TixiSaveExt::TixiSaveDoubleElement(tixiHandle, elementPath.c_str(), "upperN1", upperN1); TixiSaveExt::TixiSaveDoubleElement(tixiHandle, elementPath.c_str(), "upperN2", upperN2); TixiSaveExt::TixiSaveDoubleElement(tixiHandle, elementPath.c_str(), "lowerN1", lowerN1); TixiSaveExt::TixiSaveDoubleElement(tixiHandle, elementPath.c_str(), "lowerN2", lowerN2); } // Builds the wing profile wire. The returned wire is already transformed by the // wing profile element transformation. void CCPACSWingProfileCST::BuildWires() { gp_Trsf yzSwitch; yzSwitch.SetMirror(gp_Ax2(gp_Pnt(0.,0.,0.), gp_Dir(0.,-1.,1.))); // Build upper wire CCSTCurveBuilder upperBuilder(upperN1, upperN2, upperB); Handle_Geom_BSplineCurve upperCurve = upperBuilder.Curve(); upperCurve->Transform(yzSwitch); upperWire = BRepBuilderAPI_MakeEdge(upperCurve); // Build lower curve, std::vector<double> binv; for (unsigned int i = 0; i < lowerB.size(); ++i) { binv.push_back(-lowerB[i]); } CCSTCurveBuilder lowerBuilder(lowerN1, lowerN2, binv); Handle_Geom_BSplineCurve lowerCurve = lowerBuilder.Curve(); lowerCurve->Transform(yzSwitch); lowerCurve->Reverse(); lowerWire = BRepBuilderAPI_MakeEdge(lowerCurve); BRepBuilderAPI_MakeWire upperLowerWireMaker(lowerWire, upperWire); TopoDS_Wire upperLowerWire = upperLowerWireMaker.Wire(); // conatenate wire Handle_Geom_Curve upperLowerCurve = CWireToCurve(upperLowerWire).curve(); upperLowerEdge = BRepBuilderAPI_MakeEdge(upperLowerCurve); tePoint = gp_Pnt(1,0,0); lePoint = gp_Pnt(0,0,0); } // Returns sample points std::vector<CTiglPoint*> CCPACSWingProfileCST::GetSamplePoints() const { std::vector<CTiglPoint*> empty; return empty; } // get profiles CPACS XML path const std::string & CCPACSWingProfileCST::GetProfileDataXPath() const { return ProfileDataXPath; } // Getter for upper wire of closed profile const TopoDS_Edge& CCPACSWingProfileCST::GetUpperWireClosed() const { return upperWire; } // Getter for lower wire of closed profile const TopoDS_Edge& CCPACSWingProfileCST::GetLowerWireClosed() const { return lowerWire; } // Getter for upper wire of opened profile const TopoDS_Edge& CCPACSWingProfileCST::GetUpperWireOpened() const { throw CTiglError("ERROR: GetUpperWireOpened not implemented yet for CCPACSWingProfileCST!"); } // Getter for lower wire of opened profile const TopoDS_Edge& CCPACSWingProfileCST::GetLowerWireOpened() const { throw CTiglError("ERROR: GetLowerWireOpened not implemented yet for CCPACSWingProfileCST!"); } // get upper wing profile wire const TopoDS_Edge & CCPACSWingProfileCST::GetUpperWire() const { return upperWire; } // get lower wing profile wire const TopoDS_Edge & CCPACSWingProfileCST::GetLowerWire() const { return lowerWire; } // gets the upper and lower wing profile into on edge const TopoDS_Edge & CCPACSWingProfileCST::GetUpperLowerWire() const { return upperLowerEdge; } // get trailing edge const TopoDS_Edge & CCPACSWingProfileCST::GetTrailingEdge() const { return trailingEdge; } // get trailing edge const TopoDS_Edge & CCPACSWingProfileCST::GetTrailingEdgeOpened() const { throw CTiglError("ERROR: GetTrailingEdgeOpened not implemented yet for CCPACSWingProfileCST!"); } // get leading edge point(); const gp_Pnt & CCPACSWingProfileCST::GetLEPoint() const { return lePoint; } // get trailing edge point(); const gp_Pnt & CCPACSWingProfileCST::GetTEPoint() const { return tePoint; } } // end namespace tigl <|endoftext|>
<commit_before>//============================================================================================================= /** * @file informationwindow.h * @author Lorenz Esch <Lorenz.Esch@tu-ilmenau.de> * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date August, 2014 * * @section LICENSE * * Copyright (C) 2014, Lorenz Esch, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Contains the implementation of the InformationWindow class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "informationwindow.h" //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace MNEBrowseRawQt; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= InformationWindow::InformationWindow(QWidget *parent) : QDockWidget(parent), ui(new Ui::InformationWindowWidget) { ui->setupUi(this); m_pTextBrowser_Log = (QTextBrowser*)ui->tab_log->childAt(50,50); } //************************************************************************************************************* InformationWindow::~InformationWindow() { delete ui; } //************************************************************************************************************* void InformationWindow::writeToLog(const QString& logMsg, LogKind lgknd, LogLevel lglvl) { if(lglvl<=m_eLogLevelCurrent) { if(lgknd == _LogKndError) m_pTextBrowser_Log->insertHtml("<font color=red><b>Error:</b> "+logMsg+"</font>"); else if(lgknd == _LogKndWarning) m_pTextBrowser_Log->insertHtml("<font color=blue><b>Warning:</b> "+logMsg+"</font>"); else m_pTextBrowser_Log->insertHtml(logMsg); m_pTextBrowser_Log->insertPlainText("\n"); // new line //scroll down to the latest entry QTextCursor c = m_pTextBrowser_Log->textCursor(); c.movePosition(QTextCursor::End); m_pTextBrowser_Log->setTextCursor(c); m_pTextBrowser_Log->verticalScrollBar()->setValue(m_pTextBrowser_Log->verticalScrollBar()->maximum()); } } //************************************************************************************************************* void InformationWindow::setLogLevel(LogLevel lvl) { switch(lvl) { case _LogLvMin: writeToLog(tr("minimal log level set"), _LogKndMessage, _LogLvMin); break; case _LogLvNormal: writeToLog(tr("normal log level set"), _LogKndMessage, _LogLvMin); break; case _LogLvMax: writeToLog(tr("maximum log level set"), _LogKndMessage, _LogLvMin); break; } m_eLogLevelCurrent = lvl; } <commit_msg>initialize log level before writing to log<commit_after>//============================================================================================================= /** * @file informationwindow.h * @author Lorenz Esch <Lorenz.Esch@tu-ilmenau.de> * Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date August, 2014 * * @section LICENSE * * Copyright (C) 2014, Lorenz Esch, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Contains the implementation of the InformationWindow class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "informationwindow.h" //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace MNEBrowseRawQt; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= InformationWindow::InformationWindow(QWidget *parent) : QDockWidget(parent), ui(new Ui::InformationWindowWidget) { ui->setupUi(this); m_pTextBrowser_Log = (QTextBrowser*)ui->tab_log->childAt(50,50); } //************************************************************************************************************* InformationWindow::~InformationWindow() { delete ui; } //************************************************************************************************************* void InformationWindow::writeToLog(const QString& logMsg, LogKind lgknd, LogLevel lglvl) { if(lglvl<=m_eLogLevelCurrent) { if(lgknd == _LogKndError) m_pTextBrowser_Log->insertHtml("<font color=red><b>Error:</b> "+logMsg+"</font>"); else if(lgknd == _LogKndWarning) m_pTextBrowser_Log->insertHtml("<font color=blue><b>Warning:</b> "+logMsg+"</font>"); else m_pTextBrowser_Log->insertHtml(logMsg); m_pTextBrowser_Log->insertPlainText("\n"); // new line //scroll down to the latest entry QTextCursor c = m_pTextBrowser_Log->textCursor(); c.movePosition(QTextCursor::End); m_pTextBrowser_Log->setTextCursor(c); m_pTextBrowser_Log->verticalScrollBar()->setValue(m_pTextBrowser_Log->verticalScrollBar()->maximum()); } } //************************************************************************************************************* void InformationWindow::setLogLevel(LogLevel lvl) { m_eLogLevelCurrent = lvl; switch(lvl) { case _LogLvMin: writeToLog(tr("minimal log level set"), _LogKndMessage, _LogLvMin); break; case _LogLvNormal: writeToLog(tr("normal log level set"), _LogKndMessage, _LogLvMin); break; case _LogLvMax: writeToLog(tr("maximum log level set"), _LogKndMessage, _LogLvMin); break; } } <|endoftext|>
<commit_before>#pragma once #include "support/uref.hpp" #include <boost/python/to_python_converter.hpp> #include <boost/python/tuple.hpp> #include <boost/python/cast.hpp> #define NPY_NO_DEPRECATED_API NPY_1_8_API_VERSION #include <numpy/ndarrayobject.h> #include <cstdint> namespace bp = boost::python; /// type map: C++ type to numpy type template<class T> struct dtype; template<> struct dtype<bool> { static constexpr auto value = NPY_BOOL; }; template<> struct dtype<float> { static constexpr auto value = NPY_FLOAT; }; template<> struct dtype<double> { static constexpr auto value = NPY_DOUBLE; }; template<> struct dtype<std::complex<float>> { static constexpr auto value = NPY_CFLOAT; }; template<> struct dtype<std::complex<double>> { static constexpr auto value = NPY_CDOUBLE; }; template<> struct dtype<std::int8_t> { static constexpr auto value = NPY_INT8; }; template<> struct dtype<std::int16_t> { static constexpr auto value = NPY_INT16; }; template<> struct dtype<std::int32_t> { static constexpr auto value = NPY_INT32; }; template<> struct dtype<std::int64_t> { static constexpr auto value = NPY_INT64; }; template<> struct dtype<std::uint8_t> { static constexpr auto value = NPY_UINT8; }; template<> struct dtype<std::uint16_t> { static constexpr auto value = NPY_UINT16; }; template<> struct dtype<std::uint32_t> { static constexpr auto value = NPY_UINT32; }; template<> struct dtype<std::uint64_t> { static constexpr auto value = NPY_UINT64; }; template<> struct bp::base_type_traits<PyArrayObject> : std::true_type {}; struct denseuref_to_python { static PyObject* convert(const DenseURef& u) { int ndim = (u.rows == 1 || u.cols == 1) ? 1 : 2; npy_intp shape[ndim]; if (ndim == 1) { // row or column vector shape[0] = u.is_row_major ? u.cols : u.rows; } else { // matrix shape[0] = u.rows; shape[1] = u.cols; } auto const type = [&]{ switch (u.type) { case ScalarType::f: return NPY_FLOAT; case ScalarType::cf: return NPY_CFLOAT; case ScalarType::d: return NPY_DOUBLE; case ScalarType::cd: return NPY_CDOUBLE; case ScalarType::b: return NPY_BOOL; case ScalarType::i8: return NPY_INT8; case ScalarType::i16: return NPY_INT16; case ScalarType::i32: return NPY_INT32; case ScalarType::u8: return NPY_UINT8; case ScalarType::u16: return NPY_UINT16; case ScalarType::u32: return NPY_UINT32; default: return NPY_VOID; } }(); int flags = u.is_row_major ? NPY_ARRAY_CARRAY : NPY_ARRAY_FARRAY; // ndarray from existing data -> it does not own the data and will not delete it return PyArray_New(&PyArray_Type, ndim, shape, type, nullptr, (void*)u.data, 0, flags, nullptr); } static const PyTypeObject* get_pytype() { return &PyArray_Type; } }; template<class EigenType> struct eigen3_to_numpy { static PyObject* convert(const EigenType& eigen_object) { constexpr int ndim = EigenType::IsVectorAtCompileTime ? 1 : 2; npy_intp shape[ndim]; if (ndim == 1) { // row or column vector shape[0] = EigenType::IsRowMajor ? eigen_object.cols() : eigen_object.rows(); } else { // matrix shape[0] = eigen_object.rows(); shape[1] = eigen_object.cols(); } using scalar_t = typename EigenType::Scalar; int flags = EigenType::IsRowMajor ? NPY_ARRAY_CARRAY : NPY_ARRAY_FARRAY; // new empty ndarray of the correct type and shape PyObject* array = PyArray_New(&PyArray_Type, ndim, shape, dtype<scalar_t>::value, nullptr, nullptr, 0, flags, nullptr); std::memcpy( PyArray_DATA(bp::downcast<PyArrayObject>(array)), eigen_object.data(), eigen_object.size() * sizeof(scalar_t) ); return array; } static const PyTypeObject* get_pytype() { return &PyArray_Type; } }; /** Helper function that will construct an eigen vector or matrix */ template<class EigenType, int ndim, bool fixed_size> struct construct_eigen; template<class EigenType> struct construct_eigen<EigenType, 1, false> { static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) { new (v) EigenType(shape[0]); std::copy_n(data, v->size(), v->data()); } }; template<class EigenType> struct construct_eigen<EigenType, 2, false> { static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) { new (v) EigenType(shape[0], shape[1]); std::copy_n(data, v->rows() * v->cols(), v->data()); } }; template<class EigenType> struct construct_eigen<EigenType, 1, true> { static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) { new (v) EigenType(EigenType::Zero()); auto size = std::min(v->size(), shape[0]); std::copy_n(data, size, v->data()); } }; template<class EigenType> struct numpy_to_eigen3 { numpy_to_eigen3() { bp::converter::registry::insert_rvalue_converter( &convertible, &construct, bp::type_id<EigenType>(), &PyArray_Type ); } static constexpr auto ndim = EigenType::IsVectorAtCompileTime ? 1 : 2; static constexpr auto ndtype = dtype<typename EigenType::Scalar>::value; static constexpr auto fixed_size = EigenType::SizeAtCompileTime > 0; static void* convertible(PyObject* p) { // try to make an ndarray from the python object auto ndarray = bp::handle<PyArrayObject>{bp::allow_null(PyArray_FROMANY( p, ndtype, ndim, ndim, EigenType::IsRowMajor ? NPY_ARRAY_C_CONTIGUOUS : NPY_ARRAY_F_CONTIGUOUS ))}; if (!ndarray) return nullptr; if (EigenType::IsRowMajor && !PyArray_IS_C_CONTIGUOUS(ndarray.get())) return nullptr; // row major only accepts C-style array if (!EigenType::IsRowMajor && !PyArray_IS_F_CONTIGUOUS(ndarray.get())) return nullptr; // column major only accepts Fortran-style array return p; } static void construct(PyObject* p, bp::converter::rvalue_from_python_stage1_data* data) { // get the pointer to memory where to construct the new eigen3 object auto storage = reinterpret_cast<EigenType*>( ((bp::converter::rvalue_from_python_storage<EigenType>*)data)->storage.bytes ); auto ndarray = bp::handle<PyArrayObject>{PyArray_FROMANY( p, ndtype, ndim, ndim, EigenType::IsRowMajor ? NPY_ARRAY_C_CONTIGUOUS : NPY_ARRAY_F_CONTIGUOUS )}; auto array_data = static_cast<typename EigenType::Scalar*>(PyArray_DATA(ndarray.get())); auto array_shape = PyArray_SHAPE(ndarray.get()); // in-place construct a new eigen3 object using data from the numpy array construct_eigen<EigenType, ndim, fixed_size>::exec(storage, array_data, array_shape); // save the pointer to the eigen3 object for later use by boost.python data->convertible = storage; } }; template<class EigenType> inline void eigen3_numpy_register_type() { numpy_to_eigen3<EigenType>{}; bp::to_python_converter<EigenType, eigen3_to_numpy<EigenType>>{}; } <commit_msg>Add numpy to Eigen::Map converter<commit_after>#pragma once #include "support/uref.hpp" #include <boost/python/to_python_converter.hpp> #include <boost/python/tuple.hpp> #include <boost/python/cast.hpp> #define NPY_NO_DEPRECATED_API NPY_1_8_API_VERSION #include <numpy/ndarrayobject.h> #include <cstdint> namespace bp = boost::python; /// type map: C++ type to numpy type template<class T> struct dtype; template<> struct dtype<bool> { static constexpr auto value = NPY_BOOL; }; template<> struct dtype<float> { static constexpr auto value = NPY_FLOAT; }; template<> struct dtype<double> { static constexpr auto value = NPY_DOUBLE; }; template<> struct dtype<std::complex<float>> { static constexpr auto value = NPY_CFLOAT; }; template<> struct dtype<std::complex<double>> { static constexpr auto value = NPY_CDOUBLE; }; template<> struct dtype<std::int8_t> { static constexpr auto value = NPY_INT8; }; template<> struct dtype<std::int16_t> { static constexpr auto value = NPY_INT16; }; template<> struct dtype<std::int32_t> { static constexpr auto value = NPY_INT32; }; template<> struct dtype<std::int64_t> { static constexpr auto value = NPY_INT64; }; template<> struct dtype<std::uint8_t> { static constexpr auto value = NPY_UINT8; }; template<> struct dtype<std::uint16_t> { static constexpr auto value = NPY_UINT16; }; template<> struct dtype<std::uint32_t> { static constexpr auto value = NPY_UINT32; }; template<> struct dtype<std::uint64_t> { static constexpr auto value = NPY_UINT64; }; template<> struct bp::base_type_traits<PyArrayObject> : std::true_type {}; struct denseuref_to_python { static PyObject* convert(const DenseURef& u) { int ndim = (u.rows == 1 || u.cols == 1) ? 1 : 2; npy_intp shape[ndim]; if (ndim == 1) { // row or column vector shape[0] = u.is_row_major ? u.cols : u.rows; } else { // matrix shape[0] = u.rows; shape[1] = u.cols; } auto const type = [&]{ switch (u.type) { case ScalarType::f: return NPY_FLOAT; case ScalarType::cf: return NPY_CFLOAT; case ScalarType::d: return NPY_DOUBLE; case ScalarType::cd: return NPY_CDOUBLE; case ScalarType::b: return NPY_BOOL; case ScalarType::i8: return NPY_INT8; case ScalarType::i16: return NPY_INT16; case ScalarType::i32: return NPY_INT32; case ScalarType::u8: return NPY_UINT8; case ScalarType::u16: return NPY_UINT16; case ScalarType::u32: return NPY_UINT32; default: return NPY_VOID; } }(); int flags = u.is_row_major ? NPY_ARRAY_CARRAY : NPY_ARRAY_FARRAY; // ndarray from existing data -> it does not own the data and will not delete it return PyArray_New(&PyArray_Type, ndim, shape, type, nullptr, (void*)u.data, 0, flags, nullptr); } static const PyTypeObject* get_pytype() { return &PyArray_Type; } }; template<class EigenType> struct eigen3_to_numpy { static PyObject* convert(const EigenType& eigen_object) { constexpr int ndim = EigenType::IsVectorAtCompileTime ? 1 : 2; npy_intp shape[ndim]; if (ndim == 1) { // row or column vector shape[0] = EigenType::IsRowMajor ? eigen_object.cols() : eigen_object.rows(); } else { // matrix shape[0] = eigen_object.rows(); shape[1] = eigen_object.cols(); } using scalar_t = typename EigenType::Scalar; int flags = EigenType::IsRowMajor ? NPY_ARRAY_CARRAY : NPY_ARRAY_FARRAY; // new empty ndarray of the correct type and shape PyObject* array = PyArray_New(&PyArray_Type, ndim, shape, dtype<scalar_t>::value, nullptr, nullptr, 0, flags, nullptr); std::memcpy( PyArray_DATA(bp::downcast<PyArrayObject>(array)), eigen_object.data(), eigen_object.size() * sizeof(scalar_t) ); return array; } static const PyTypeObject* get_pytype() { return &PyArray_Type; } }; /** Helper function that will construct an eigen vector or matrix */ template<class EigenType, int ndim, bool fixed_size> struct construct_eigen; template<class EigenType> struct construct_eigen<EigenType, 1, false> { static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) { new (v) EigenType(shape[0]); std::copy_n(data, v->size(), v->data()); } }; template<class EigenType> struct construct_eigen<EigenType, 2, false> { static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) { new (v) EigenType(shape[0], shape[1]); std::copy_n(data, v->rows() * v->cols(), v->data()); } }; template<class EigenType> struct construct_eigen<EigenType, 1, true> { static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) { new (v) EigenType(EigenType::Zero()); auto size = std::min(v->size(), shape[0]); std::copy_n(data, size, v->data()); } }; template<class EigenType> struct numpy_to_eigen3 { numpy_to_eigen3() { bp::converter::registry::insert_rvalue_converter( &convertible, &construct, bp::type_id<EigenType>(), &PyArray_Type ); } static constexpr auto ndim = EigenType::IsVectorAtCompileTime ? 1 : 2; static constexpr auto ndtype = dtype<typename EigenType::Scalar>::value; static constexpr auto fixed_size = EigenType::SizeAtCompileTime > 0; static void* convertible(PyObject* p) { // try to make an ndarray from the python object auto ndarray = bp::handle<PyArrayObject>{bp::allow_null(PyArray_FROMANY( p, ndtype, ndim, ndim, EigenType::IsRowMajor ? NPY_ARRAY_C_CONTIGUOUS : NPY_ARRAY_F_CONTIGUOUS ))}; if (!ndarray) return nullptr; if (EigenType::IsRowMajor && !PyArray_IS_C_CONTIGUOUS(ndarray.get())) return nullptr; // row major only accepts C-style array if (!EigenType::IsRowMajor && !PyArray_IS_F_CONTIGUOUS(ndarray.get())) return nullptr; // column major only accepts Fortran-style array return p; } static void construct(PyObject* p, bp::converter::rvalue_from_python_stage1_data* data) { // get the pointer to memory where to construct the new eigen3 object auto storage = reinterpret_cast<EigenType*>( ((bp::converter::rvalue_from_python_storage<EigenType>*)data)->storage.bytes ); auto ndarray = bp::handle<PyArrayObject>{PyArray_FROMANY( p, ndtype, ndim, ndim, EigenType::IsRowMajor ? NPY_ARRAY_C_CONTIGUOUS : NPY_ARRAY_F_CONTIGUOUS )}; auto array_data = static_cast<typename EigenType::Scalar*>(PyArray_DATA(ndarray.get())); auto array_shape = PyArray_SHAPE(ndarray.get()); // in-place construct a new eigen3 object using data from the numpy array construct_eigen<EigenType, ndim, fixed_size>::exec(storage, array_data, array_shape); // save the pointer to the eigen3 object for later use by boost.python data->convertible = storage; } }; template<class EigenType, int ndim> struct construct_eigen_map; template<class EigenType> struct construct_eigen_map<EigenType, 1> { static void exec(void* storage, typename EigenType::Scalar* data, npy_intp const* shape) { new (storage) Eigen::Map<EigenType>{data, shape[0]}; } }; template<class EigenType> struct construct_eigen_map<EigenType, 2> { static void exec(void* storage, typename EigenType::Scalar* data, npy_intp const* shape) { new (storage) Eigen::Map<EigenType>{data, shape[0], shape[1]}; } }; template<class EigenType> struct numpy_to_eigen3_map { numpy_to_eigen3_map() { bp::converter::registry::insert_rvalue_converter( &convertible, &construct, bp::type_id<Eigen::Map<EigenType>>(), &PyArray_Type ); } static constexpr auto ndim = EigenType::IsVectorAtCompileTime ? 1 : 2; static constexpr auto ndtype = dtype<typename EigenType::Scalar>::value; static void* convertible(PyObject* p) { if (!PyArray_Check(p)) return nullptr; auto array = (PyArrayObject*)p; if (PyArray_NDIM(array) != ndim || PyArray_TYPE(array) != ndtype) return nullptr; if (EigenType::IsRowMajor && !PyArray_IS_C_CONTIGUOUS(array)) return nullptr; if (!EigenType::IsRowMajor && !PyArray_IS_F_CONTIGUOUS(array)) return nullptr; return p; } static void construct(PyObject* p, bp::converter::rvalue_from_python_stage1_data* data) { void* storage = ((bp::converter::rvalue_from_python_storage<EigenType>*) data)->storage.bytes; auto array = (PyArrayObject*)p; auto array_data = static_cast<typename EigenType::Scalar*>(PyArray_DATA(array)); auto array_shape = PyArray_SHAPE(array); construct_eigen_map<EigenType, ndim>::exec(storage, array_data, array_shape); data->convertible = storage; } }; template<class EigenType> inline void eigen3_numpy_register_type() { numpy_to_eigen3<EigenType>{}; numpy_to_eigen3_map<EigenType>{}; bp::to_python_converter<EigenType, eigen3_to_numpy<EigenType>>{}; } <|endoftext|>