diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..c38ef3470ee867424442ffc6b198105139ef7efe --- /dev/null +++ b/.clang-format @@ -0,0 +1,36 @@ +BasedOnStyle: llvm +Language: Cpp +ColumnLimit: 0 +IndentWidth: 4 +AccessModifierOffset: -4 +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^<(gtest|gmock)/)' + Priority: -1 + - Regex: '^<[^Q]' + Priority: 1 + - Regex: '^<Q' + Priority: 2 +AlignTrailingComments: true +BreakConstructorInitializers: AfterColon +ConstructorInitializerAllOnOneLineOrOnePerLine: true +AllowShortFunctionsOnASingleLine: None +KeepEmptyLinesAtTheStartOfBlocks: false +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH, forever, Q_FOREVER, QBENCHMARK, QBENCHMARK_ONCE ] \ No newline at end of file diff --git a/DoxyGen/Function/Markdown/Simulation/Development/FrameworkModules.md b/DoxyGen/Function/Markdown/Simulation/Development/FrameworkModules.md index 159ecb2c526dcf72e4b5e46cf79763862f4460a5..9bd8213b91a36a6c180f3c832a026657cafab5cc 100644 --- a/DoxyGen/Function/Markdown/Simulation/Development/FrameworkModules.md +++ b/DoxyGen/Function/Markdown/Simulation/Development/FrameworkModules.md @@ -35,6 +35,21 @@ Then the AgentType with the components and channels is build by the DynamicAgent  +\section dev_framework_modules_datastore DataStore + +The DataStore accepts arbitrary values from different components (from framework as well as agents). +The stored values if cyclic and acyclic type are associated with an timestamp, entity id and a key (topic). +Static values are only associated with a key. + +Typically, Observers are using the DataStore to retrieve information about the simulation. +This can happen during the simulation run and/or at the end of a run. +For the keys, a generic datatype is used (strings). +For the values, a set of predefined datatypes is used (bool, char, int, size_t, float, double, string). +A value can also hold a vector of one of the mentioned datatypes. + +For information about the usage, please refer to the implementation's inline documentation. + + \section dev_framework_modules_eventdetectors EventDetectors [//]: <> "Please refer to each section!" diff --git a/OpenPass_Source_Code/openPASS/Common/basicEvent.h b/OpenPass_Source_Code/openPASS/Common/basicEvent.h index 65e36782ec9e946d043af5770b7d6dea329dfb84..6761afa56ca3a6a45b200c6d03432ded82cddfda 100644 --- a/OpenPass_Source_Code/openPASS/Common/basicEvent.h +++ b/OpenPass_Source_Code/openPASS/Common/basicEvent.h @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2017, 2018, 2019 in-tech GmbH +* Copyright (c) 2017, 2018, 2019, 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -20,6 +20,8 @@ #pragma once +#include <vector> + #include "Interfaces/eventInterface.h" //----------------------------------------------------------------------------- @@ -30,115 +32,125 @@ class BasicEvent : public EventInterface { public: - BasicEvent(int time, - std::string eventName, - std::string source): + BasicEvent(int time, std::string eventName, std::string source, + const std::vector<int> triggeringAgents, const std::vector<int> actingAgents) : time(time), name(eventName), - source(source) - {} - BasicEvent(const BasicEvent&) = delete; - BasicEvent(BasicEvent&&) = delete; - BasicEvent& operator=(const BasicEvent&) = delete; - BasicEvent& operator=(BasicEvent&&) = delete; + source(source), + triggeringAgents(triggeringAgents), + actingAgents(actingAgents) + { + } + + BasicEvent(int time, std::string eventName, std::string source) : + time(time), + name(eventName), + source(source), + triggeringAgents{}, + actingAgents{} + { + } + virtual ~BasicEvent() override = default; - /*! - * \brief Sets the Id of the event. - * - * @param[in] Id of the event. - */ virtual void SetId(const int eventId) override { this->eventId = eventId; } - /*! - * \brief Returns the Id of the event. - * - * @return Id. - */ virtual int GetId() const override { return eventId; } - /*! - * \brief Returns the time of the event. - * - * @return Time in milliseconds. - */ virtual int GetEventTime() const override { return time; } - /*! - * \brief Returns the category of the event. - * - * @return EventCategory. - */ virtual EventDefinitions::EventCategory GetCategory() const override { return EventDefinitions::EventCategory::Basic; } - /*! - * \brief Sets the Id of the event which triggered this event. - * - * @param[in] Event Id. - */ virtual void SetTriggeringEventId(const int triggeringEventId) override { this->triggeringEventId = triggeringEventId; } - /*! - * \brief Returns the Id of the event which triggered this event. - * - * @return Event Id. - */ virtual int GetTriggeringEventId() const override { return triggeringEventId; } - /*! - * \brief Returns the name of the event. - * - * @return Name of the event as string. - */ virtual std::string GetName() const override { return name; } - /*! - * \brief Returns the name of the source component. - * - * @return Name of source component as string. - */ virtual std::string GetSource() const override { return source; } - /*! - * \brief Returns all parameters of the event as string list. - * \details Returns all parameters of the event as a generic string list. - * The parameter name and the value are returned as string. - * - * @return List of string pairs of the event parameters. - */ + virtual const std::vector<int> GetTriggeringAgents() const override + { + return triggeringAgents; + } + + virtual const std::vector<int> GetActingAgents() const override + { + return actingAgents; + } + virtual EventParameters GetParametersAsString() override { - return {}; + EventParameters eventParameters; + + std::string triggeringAgentsAsString{}; + for (auto &triggeringAgentId : triggeringAgents) + { + triggeringAgentsAsString += std::to_string(triggeringAgentId) + ","; + } + + std::string actingAgentsAsString; + for (auto &actingAgentId : actingAgents) + { + actingAgentsAsString += std::to_string(actingAgentId) + ","; + } + + if (!triggeringAgentsAsString.empty()) + { + triggeringAgentsAsString.pop_back(); + eventParameters.push_back({"TriggeringAgentIds", triggeringAgentsAsString}); + } + + if (!actingAgentsAsString.empty()) + { + actingAgentsAsString.pop_back(); + eventParameters.push_back({"ActingAgentIds", actingAgentsAsString}); + } + + return eventParameters; + } + + const openpass::type::FlatParameter &GetParameter() const noexcept override + { + return parameter; } private: - int eventId; const int time; - int triggeringEventId {-1}; const std::string name; const std::string source; + + int eventId{}; + int triggeringEventId{-1}; + +public: + const std::vector<int> triggeringAgents; + const std::vector<int> actingAgents; + +protected: + openpass::type::FlatParameter parameter{}; }; diff --git a/OpenPass_Source_Code/openPASS/Common/collisionEvent.h b/OpenPass_Source_Code/openPASS/Common/collisionEvent.h index 7f2ed6475c540f19a6669a970f282b2107f84d3e..9bf4688f2dbb0b21803e9cadfad65b93dfedc2d3 100644 --- a/OpenPass_Source_Code/openPASS/Common/collisionEvent.h +++ b/OpenPass_Source_Code/openPASS/Common/collisionEvent.h @@ -14,7 +14,6 @@ * * This class contains all functionality of the module. */ //----------------------------------------------------------------------------- - #pragma once #include "basicEvent.h" @@ -27,54 +26,32 @@ class CollisionEvent : public BasicEvent { public: - CollisionEvent(int time, - std::string source, - bool collisionWithAgent, - int collisionAgentId, - int collisionOpponentId): - BasicEvent(time, - "Collision", - source), - collisionWithAgent(collisionWithAgent), - collisionAgentId(collisionAgentId), - collisionOpponentId(collisionOpponentId) - {} - CollisionEvent(const CollisionEvent&) = delete; - CollisionEvent(CollisionEvent&&) = delete; - CollisionEvent& operator=(const CollisionEvent&) = delete; - CollisionEvent& operator=(CollisionEvent&&) = delete; - virtual ~CollisionEvent() override = default; - - /*! - * \brief Returns the category of the event. - * - * @return EventCategory. - */ - virtual EventDefinitions::EventCategory GetCategory() const override + CollisionEvent(int time, std::string source, bool collisionWithAgent, int collisionAgentId, int collisionOpponentId) : + BasicEvent{time, "Collision", source, {collisionAgentId, collisionOpponentId}, {}}, + collisionWithAgent{collisionWithAgent}, + collisionAgentId{collisionAgentId}, + collisionOpponentId{collisionOpponentId} { - return EventDefinitions::EventCategory::Collision; + parameter.emplace("CollisionWithAgent", collisionWithAgent); } - /*! - * \brief Returns all parameters of the event as string list. - * \details Returns the CollisionWithAgent flag and both worldobject ids as string list. - * - * @return List of string pairs of the event parameters. - */ - virtual EventParameters GetParametersAsString() override + ~CollisionEvent() override = default; + + EventDefinitions::EventCategory GetCategory() const override { - EventParameters eventParameters; + return EventDefinitions::EventCategory::OpenPASS; + } + EventParameters GetParametersAsString() override + { + EventParameters eventParameters = BasicEvent::GetParametersAsString(); eventParameters.push_back({"CollisionWithAgent", collisionWithAgent ? "true" : "false"}); eventParameters.push_back({"CollisionAgentId", std::to_string(collisionAgentId)}); eventParameters.push_back({"CollisionOpponentId", std::to_string(collisionOpponentId)}); - return eventParameters; } - - bool collisionWithAgent; - int collisionAgentId; - int collisionOpponentId; + [[deprecated("Will be replaced by BasicEvent::parameter")]] bool collisionWithAgent; + [[deprecated("Will be replaced by BasicEvent::parameter")]] int collisionAgentId; + [[deprecated("Will be replaced by BasicEvent::parameter")]] int collisionOpponentId; }; - diff --git a/OpenPass_Source_Code/openPASS/Common/commonTools.h b/OpenPass_Source_Code/openPASS/Common/commonTools.h index bbb3ffaade0733fcf45265343fd989b1b385ae58..bd847b53a1614a0f2644afb02cbe67bc60528824 100644 --- a/OpenPass_Source_Code/openPASS/Common/commonTools.h +++ b/OpenPass_Source_Code/openPASS/Common/commonTools.h @@ -17,10 +17,11 @@ #define _USE_MATH_DEFINES #endif #include <cmath> - #include <map> #include <unordered_map> +#include <boost/algorithm/string/trim.hpp> + #include "globalDefinitions.h" #include "vector2d.h" @@ -318,6 +319,27 @@ public: } }; +namespace helper::vector { + +/// \brief convenience function to convert a vector into a string using a constom delimiter +/// \remark Please refer to the standard, how decimals are converted +/// \param values vector of strings +/// \param delimiter string in between the individual values +/// \return delimiter seperated list as string +template <typename T> +std::string to_string(const std::vector<T>& values, const std::string& delimiter = ",") +{ + if (values.empty()) + { + return ""; + } + + std::ostringstream oss; + std::copy(values.begin(), values.end(), std::ostream_iterator<T>(oss, delimiter.c_str())); + + return {oss.str(), 0, oss.str().length() - delimiter.size()}; +} +} // namespace helper::vector namespace helper::map { /// @brief queries a map for a given key and returns the value if available diff --git a/OpenPass_Source_Code/openPASS/Common/componentStateChangeEvent.h b/OpenPass_Source_Code/openPASS/Common/componentStateChangeEvent.h index dc04676cf07d7ccb9536b35c2a1567fcfddfa2b4..09a5c35afca080edf20b9cb4cdaeac7c16637eef 100644 --- a/OpenPass_Source_Code/openPASS/Common/componentStateChangeEvent.h +++ b/OpenPass_Source_Code/openPASS/Common/componentStateChangeEvent.h @@ -33,44 +33,43 @@ class ComponentChangeEvent : public ConditionalEvent { public: - ComponentChangeEvent(int time, - const std::string& eventName, - const std::string& source, - std::vector<int> triggeringAgents, - std::vector<int> actingAgents, - const std::string& componentName, - const std::string& goalStateName): - ConditionalEvent(time, - eventName, - source, - triggeringAgents, - actingAgents), - componentName(componentName), - goalStateName(goalStateName) + ComponentChangeEvent(int time, const std::string &eventName, const std::string &source, + std::vector<int> triggeringAgents, std::vector<int> actingAgents, + const std::string &componentName, const std::string &goalStateName) : + ConditionalEvent{time, eventName, source, triggeringAgents, actingAgents}, + componentName{componentName}, + goalStateName{goalStateName} { goalState = ComponentStateMapping.at(goalStateName); + + parameter.emplace("ComponentName", componentName); + parameter.emplace("GoalStateName", goalStateName); } - ComponentChangeEvent(const ComponentChangeEvent&) = delete; - ComponentChangeEvent(ComponentChangeEvent&&) = delete; - ComponentChangeEvent& operator=(const ComponentChangeEvent&) = delete; - ComponentChangeEvent& operator=(ComponentChangeEvent&&) = delete; - virtual ~ComponentChangeEvent() override = default; - /*! - * \brief Returns the category of the event. - * - * @return EventCategory. - */ - virtual EventDefinitions::EventCategory GetCategory() const override + ~ComponentChangeEvent() override = default; + + EventDefinitions::EventCategory GetCategory() const override { return EventDefinitions::EventCategory::ComponentStateChange; } + + EventParameters GetParametersAsString() override + { + EventParameters eventParameters = ConditionalEvent::GetParametersAsString(); + + eventParameters.push_back({"ComponentName", componentName}); + eventParameters.push_back({"State", goalStateName}); + + return eventParameters; + } + /*! * \brief Returns the component name for which the event is targeted * @return Component Name */ - std::string GetComponentName() const { + std::string GetComponentName() const + { return componentName; } @@ -78,7 +77,8 @@ public: * \brief Returns the goal state name for which the event is targeted * @return State Name */ - std::string GetGoalStateName() const { + std::string GetGoalStateName() const + { return goalStateName; } @@ -86,24 +86,9 @@ public: * \brief Returns the goal state as a result of the event * @return State */ - ComponentState GetGoalState() const { - return goalState; - } - - /*! - * \brief Returns all parameters of the event as string list. - * \details Returns the agentId as string list. - * - * @return List of string pairs of the event parameters. - */ - virtual EventParameters GetParametersAsString() override + ComponentState GetGoalState() const { - EventParameters eventParameters = ConditionalEvent::GetParametersAsString(); - - eventParameters.push_back({"ComponentName", componentName}); - eventParameters.push_back({"State", goalStateName}); - - return eventParameters; + return goalState; } private: diff --git a/OpenPass_Source_Code/openPASS/Common/componentWarningEvent.h b/OpenPass_Source_Code/openPASS/Common/componentWarningEvent.h deleted file mode 100644 index 1da4dc673eecf1dc6b67f8fed69b19ff610a66d1..0000000000000000000000000000000000000000 --- a/OpenPass_Source_Code/openPASS/Common/componentWarningEvent.h +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2019 in-tech GmbH -* -* This program and the accompanying materials are made -* available under the terms of the Eclipse Public License 2.0 -* which is available at https://www.eclipse.org/legal/epl-2.0/ -* -* SPDX-License-Identifier: EPL-2.0 -*******************************************************************************/ - -#pragma once - -#include "vehicleComponentEvent.h" -#include "Interfaces/signalInterface.h" - -/*! - * ---------------------------------------------------------------------------- - * \brief The ComponentWarningEvent class contains all information related to - * an event emitted in response to a Component Warning. - * ---------------------------------------------------------------------------- - */ -class ComponentWarningEvent : public VehicleComponentEvent -{ -public: - ComponentWarningEvent(const int time, - const std::string& source, - const int agentId, - const std::string& componentName, - const ComponentWarningInformation& warning): - VehicleComponentEvent(time, - "", - source, - agentId), - componentName(componentName), - warning(warning) - {} - - ComponentWarningEvent(const ComponentWarningEvent&) = delete; - ComponentWarningEvent(ComponentWarningEvent&&) = delete; - ComponentWarningEvent& operator=(const ComponentWarningEvent&) = delete; - ComponentWarningEvent& operator=(ComponentWarningEvent&&) = delete; - virtual ~ComponentWarningEvent() override = default; - - /*! - * \brief Returns the component name for which the event is targeted - * @return Component Name - */ - std::string GetComponentName() const - { - return componentName; - } - - /*! - * \brief GetComponentWarningInformation gets the information regarding the warning from the event - * \return Component warning information - */ - ComponentWarningInformation GetComponentWarningInformation() const - { - return warning; - } - - /*! - * \brief Returns all parameters of the event as string list. - * \details Returns the agentId as string list. - * - * @return List of string pairs of the event parameters. - */ - virtual EventParameters GetParametersAsString() override - { - auto eventParameters = VehicleComponentEvent::GetParametersAsString(); - - eventParameters.push_back({"ComponentName", componentName}); - eventParameters.push_back({"Activity", warning.activity ? "true" : "false"}); - eventParameters.push_back({"Level", ComponentWarningLevelMapping.at(warning.level)}); - eventParameters.push_back({"Type", ComponentWarningTypeMapping.at(warning.type)}); - eventParameters.push_back({"Intensity", ComponentWarningIntensityMapping.at(warning.intensity)}); - - return eventParameters; - } - - -private: - const std::string componentName; //!< The name of the component that has a warning - const ComponentWarningInformation warning; //!< The collected information regarding the warning -}; diff --git a/OpenPass_Source_Code/openPASS/Common/conditionalEvent.h b/OpenPass_Source_Code/openPASS/Common/conditionalEvent.h index 5917fc0f709605b11eb6f1de06f0ec85a597db0d..3e5d229771b7df581250d4aae3a40e5bc2090158 100644 --- a/OpenPass_Source_Code/openPASS/Common/conditionalEvent.h +++ b/OpenPass_Source_Code/openPASS/Common/conditionalEvent.h @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2017, 2018, 2019 in-tech GmbH +* Copyright (c) 2017, 2018, 2019, 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -8,13 +8,6 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -//----------------------------------------------------------------------------- -/** @file AgentBasedEvent.h -* @brief This file contains all functions for agent based events. -* -* This class contains all functionality of the module. */ -//----------------------------------------------------------------------------- - #pragma once #include <vector> @@ -22,71 +15,23 @@ #include "basicEvent.h" //----------------------------------------------------------------------------- -/** This class implements all functionality of the AgentBasedEvent. +/** This class implements all functionality of the ConditionalEvent. * * \ingroup Event */ //----------------------------------------------------------------------------- class ConditionalEvent : public BasicEvent { public: - ConditionalEvent(int time, - std::string eventName, - std::string source, - std::vector<int> triggeringAgents, - std::vector<int> actingAgents): - BasicEvent(time, - eventName, - source), - triggeringAgents(triggeringAgents), - actingAgents(actingAgents) - {} - ~ConditionalEvent() override = default; - - /*! - * \brief Returns the category of the event. - * - * @return EventCategory. - */ - virtual EventDefinitions::EventCategory GetCategory() const override + ConditionalEvent(int time, std::string eventName, std::string source, + std::vector<int> triggeringAgents, std::vector<int> actingAgents) : + BasicEvent{time, eventName, source, triggeringAgents, actingAgents} { - return EventDefinitions::EventCategory::Conditional; } - /*! - * \brief Returns all parameters of the event as string list. - * \details Returns the agentId as string list. - * - * @return List of string pairs of the event parameters. - */ - EventParameters GetParametersAsString() override - { - EventParameters eventParameters; - - std::string triggeringAgentsAsString{}; - for (auto &triggeringAgentId : triggeringAgents) { - triggeringAgentsAsString += std::to_string(triggeringAgentId) + ","; - } - - std::string actingAgentsAsString; - for (auto &actingAgentId : actingAgents) { - actingAgentsAsString += std::to_string(actingAgentId) + ","; - } - - if(triggeringAgentsAsString.size() > 0) - { - triggeringAgentsAsString.pop_back(); - eventParameters.push_back({"TriggeringAgentIds", triggeringAgentsAsString}); - } - if(actingAgentsAsString.size() > 0) - { - actingAgentsAsString.pop_back(); - eventParameters.push_back({"ActingAgentIds", actingAgentsAsString}); - } + ~ConditionalEvent() override = default; - return eventParameters; + EventDefinitions::EventCategory GetCategory() const override + { + return EventDefinitions::EventCategory::OpenSCENARIO; } - - const std::vector<int> triggeringAgents; - const std::vector<int> actingAgents; }; - diff --git a/OpenPass_Source_Code/openPASS/Common/eventDetectorDefinitions.h b/OpenPass_Source_Code/openPASS/Common/eventDetectorDefinitions.h index 2197e95f9cab37b7da909614fa43cdfbea67f9e8..9602f3861fa0a551585ea60e87a64ba6458d1b35 100644 --- a/OpenPass_Source_Code/openPASS/Common/eventDetectorDefinitions.h +++ b/OpenPass_Source_Code/openPASS/Common/eventDetectorDefinitions.h @@ -266,10 +266,13 @@ using Condition = std::variant<ReachPositionRoadCondition, TimeHeadwayCondition>; using ConditionCollection = std::vector<Condition>; +/// +/// \brief Event specific information collected from an openSCENARIO story +/// struct ConditionalEventDetectorInformation { ActorInformation actorInformation{}; - int numberOfExecutions{}; + int numberOfExecutions{}; ///< Specifies number of executions. Use -1 for "unrestricted" std::string eventName{}; ConditionCollection conditions{}; }; diff --git a/OpenPass_Source_Code/openPASS/Common/eventTypes.h b/OpenPass_Source_Code/openPASS/Common/eventTypes.h index b9882f52d9f186579167237dd6b0c524f1162b94..90db6156c99800749bbac3807fbbfc066fe93f4d 100644 --- a/OpenPass_Source_Code/openPASS/Common/eventTypes.h +++ b/OpenPass_Source_Code/openPASS/Common/eventTypes.h @@ -14,20 +14,83 @@ #include <map> #include <string> -namespace EventDefinitions +#include "Common/openPassTypes.h" +#include "Interfaces/dataStoreInterface.h" // TODO: RP: make datastore types (Acyclic, TriggeringEntites,...) explicitly available + +namespace openpass::narrator { + +class EventBase { +public: + EventBase() = default; + EventBase(std::string name) : + name{std::move(name)} + { + } + EventBase(std::string name, TriggeringEntities triggeringEntities, AffectedEntities affectedEntities) : + name{std::move(name)}, + triggeringEntities{std::move(triggeringEntities)}, + affectedEntities{std::move(affectedEntities)} + { + } + + std::string name; + TriggeringEntities triggeringEntities; + AffectedEntities affectedEntities; + + virtual explicit operator Acyclic() const = 0; + + // We do not allow copy to force move semantics + EventBase(const EventBase &) = delete; + EventBase &operator=(const EventBase &) = delete; + + // Explicitly allow move + EventBase(EventBase &&) = default; + EventBase &operator=(EventBase &&) = default; + + // Neccesary evil + virtual ~EventBase() = default; +}; + +} + +namespace EventDefinitions { enum struct EventCategory { - Basic = 0, - Conditional, - Collision, - ComponentStateChange, - LaneChange, - CustomLaneChange, - SetTrajectory, - SetGazeFollower, - VehicleComponent + Basic, // deprecated + Conditional, // deprecated + Collision, // deprecated + ComponentStateChange, // deprecated + LaneChange, // deprecated + CustomLaneChange, // deprecated ? + SetTrajectory, // deprecated ? + SetGazeFollower, // deprecated ? + VehicleComponent, // deprecated + OpenPASS, + OpenSCENARIO }; -}//namespace EventDefinitions +namespace helper { + +static constexpr std::array<const char *, 11> EventCategoryMapping{ + "Basic", + "Conditional", + "Collision", + "ComponentStateChange", + "LaneChange", + "CustomLaneChange", + "SetTrajectory", + "SetGazeFollower", + "VehicleComponent", + "OpenPASS", + "OpenSCENARIO"}; + +constexpr auto GetAsString(EventCategory category) +{ + return EventCategoryMapping[static_cast<size_t>(category)]; +} + +} // namespace helper + +} //namespace EventDefinitions diff --git a/OpenPass_Source_Code/openPASS/Common/globalDefinitions.h b/OpenPass_Source_Code/openPASS/Common/globalDefinitions.h index 103fe31b47f62529983023d6da3cd9482d7a2e63..08509b726231caf88f03753183bdfa0b45a1a1ff 100644 --- a/OpenPass_Source_Code/openPASS/Common/globalDefinitions.h +++ b/OpenPass_Source_Code/openPASS/Common/globalDefinitions.h @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2017, 2018, 2019 in-tech GmbH +* Copyright (c) 2017, 2018, 2019, 2020 in-tech GmbH * 2018, 2019 AMFD GmbH * 2016, 2017, 2018, 2019 ITK Engineering GmbH * @@ -15,8 +15,7 @@ //! @brief This file contains several classes for global purposes //----------------------------------------------------------------------------- -#ifndef GLOBALDEFINITIONS -#define GLOBALDEFINITIONS +#pragma once #include <list> #include <map> @@ -103,20 +102,19 @@ inline AgentVehicleType GetAgentVehicleType(const std::string &strVehicleType) // convert a AgentVehicleType to VehicleType string inline std::string GetAgentVehicleTypeStr(const AgentVehicleType &vehicleType) { - return (vehicleType == AgentVehicleType::Car) ? "Car" : - (vehicleType == AgentVehicleType::Pedestrian) ? "Pedestrian" : - (vehicleType == AgentVehicleType::Motorbike) ? "Motorbike" : - (vehicleType == AgentVehicleType::Bicycle) ? "Bicycle" : - (vehicleType == AgentVehicleType::Truck) ? "Truck" : "unknown type"; + return (vehicleType == AgentVehicleType::Car) ? "Car" : (vehicleType == AgentVehicleType::Pedestrian) ? "Pedestrian" : (vehicleType == AgentVehicleType::Motorbike) ? "Motorbike" : (vehicleType == AgentVehicleType::Bicycle) ? "Bicycle" : (vehicleType == AgentVehicleType::Truck) ? "Truck" : "unknown type"; } // convert a string of type code to VehicleType string inline std::string GetAgentVehicleTypeStr(const std::string &vehicleTypeCode) { - try{ + try + { AgentVehicleType vehicleType = static_cast<AgentVehicleType>(std::stoi(vehicleTypeCode)); return GetAgentVehicleTypeStr(vehicleType); - } catch(...) { + } + catch (...) + { return "unknown type"; } } @@ -139,23 +137,26 @@ enum class IndicatorState struct Position { - Position() {} + Position() + { + } Position(double x, double y, double yaw, - double curvature): + double curvature) : xPos(x), yPos(y), yawAngle(yaw), - curvature(curvature) {} + curvature(curvature) + { + } - double xPos {0}; - double yPos {0}; - double yawAngle {0}; - double curvature {0}; + double xPos{0}; + double yPos{0}; + double yawAngle{0}; + double curvature{0}; }; - //! Enum of potential types of marks. enum class MarkType { @@ -178,10 +179,10 @@ enum class ObjectType enum ObjectTypeOSI : int { - None = 0x00, // default at initialization + None = 0x00, // default at initialization Vehicle = 0x01, - Object = 0x02, - Any = Vehicle | Object + Object = 0x02, + Any = Vehicle | Object }; using CollisionPartner = std::pair<ObjectTypeOSI, int>; @@ -301,10 +302,9 @@ enum class AdasType Undefined }; -const std::map<AdasType, std::string> adasTypeToString = { { AdasType::Safety, "Safety" }, - { AdasType::Comfort, "Comfort" }, - { AdasType::Undefined, "Undefined" } -}; +const std::map<AdasType, std::string> adasTypeToString = {{AdasType::Safety, "Safety"}, + {AdasType::Comfort, "Comfort"}, + {AdasType::Undefined, "Undefined"}}; enum class ComponentType { @@ -330,7 +330,8 @@ public: weekday(weekday), timeOfDay(timeOfDay), libraryName(libraryName) - {} + { + } WorldParameter(const WorldParameter &) = delete; WorldParameter(WorldParameter &&) = delete; WorldParameter &operator=(const WorldParameter &) = delete; @@ -367,7 +368,8 @@ public: AgentSpawnItem(int id, int reference) : id(id), reference(reference) - {} + { + } AgentSpawnItem(const AgentSpawnItem &) = delete; AgentSpawnItem(AgentSpawnItem &&) = delete; AgentSpawnItem &operator=(const AgentSpawnItem &) = delete; @@ -538,6 +540,3 @@ private: double accelerationY; double yawAngle; }; - - -#endif // GLOBALDEFINITIONS diff --git a/OpenPass_Source_Code/openPASS/Common/namedType.h b/OpenPass_Source_Code/openPASS/Common/namedType.h new file mode 100644 index 0000000000000000000000000000000000000000..777686471294ea855e5b6219eba854cf7e2c34e0 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/Common/namedType.h @@ -0,0 +1,31 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#pragma once + +namespace openpass::type { + +template <typename T, typename Tag> +struct NamedType +{ + T value; + + NamedType(T value) : + value(value) + { + } + + operator T() const + { + return value; + } +}; + +} // namespace openpass::type diff --git a/OpenPass_Source_Code/openPASS/Common/observationLibraryDefinitions.h b/OpenPass_Source_Code/openPASS/Common/observationLibraryDefinitions.h index ce5b7816ca9e80b506cf705a4ca93ce3f0243dec..c7789eab14de07e5995acbd8774230eb87bead62 100644 --- a/OpenPass_Source_Code/openPASS/Common/observationLibraryDefinitions.h +++ b/OpenPass_Source_Code/openPASS/Common/observationLibraryDefinitions.h @@ -12,6 +12,7 @@ #include <string> #include <vector> #include "parameter.h" +#include "Interfaces/dataStoreInterface.h" /** * @brief Wrapper for building an ObservationInstance diff --git a/OpenPass_Source_Code/openPASS/Common/observationTypes.h b/OpenPass_Source_Code/openPASS/Common/observationTypes.h index b5b69129753f0a54fedbe9abcdca85b7d0a9765c..bf239d50f1bf7a21644a12a941bbc7c6dafc3c22 100644 --- a/OpenPass_Source_Code/openPASS/Common/observationTypes.h +++ b/OpenPass_Source_Code/openPASS/Common/observationTypes.h @@ -14,17 +14,74 @@ #define OBSERVATION_LOG_VALUE_UNDEFINED "" #include <string> +#include <unordered_map> +#include <vector> -enum class LoggingGroup +//! Defines the cyclic coloumn names associated with each logging group +const std::unordered_map<std::string, std::vector<std::string>> LOGGINGGROUP_DEFINITIONS { - Trace, - Visualization, - RoadPosition, - RoadPositionExtended, - Vehicle, - Sensor, - SensorExtended, - Driver + { "RoadPosition", { + "AgentInFront", + "Lane", + "PositionRoute", + "Road", + "TCoordinate" + } + }, + { "RoadPositionExtended", { + "SecondaryLanes" + } + }, + { "Trace", { + "XPosition", + "YPosition", + "YawAngle" + } + }, + { "Sensor", { + } + }, + { "SensorExtended", { + "Sensor0_DetectedAgents", + "Sensor1_DetectedAgents", + "Sensor2_DetectedAgents", + "Sensor3_DetectedAgents", + "Sensor4_DetectedAgents", + "Sensor5_DetectedAgents", + "Sensor6_DetectedAgents", + "Sensor7_DetectedAgents", + "Sensor8_DetectedAgents", + "Sensor9_DetectedAgents", + "Sensor0_VisibleAgents", + "Sensor1_VisibleAgents", + "Sensor2_VisibleAgents", + "Sensor3_VisibleAgents", + "Sensor4_VisibleAgents", + "Sensor5_VisibleAgents", + "Sensor6_VisibleAgents", + "Sensor7_VisibleAgents", + "Sensor8_VisibleAgents", + "Sensor9_VisibleAgents" + } + }, + { "Vehicle", { + "AccelerationPedalPosition", + "BrakePedalPosition", + "EngineMoment", + "Gear", + "SteeringAngle", + "TotalDistanceTraveled", + "YawRate", + } + }, + { "Visualization", { + "AccelerationEgo", + "BrakeLight", + "IndicatorState", + "LightStatus", + "VelocityEgo" + } + } }; const std::string AgentCategoryStrings[] = diff --git a/OpenPass_Source_Code/openPASS/Common/openPassTypes.h b/OpenPass_Source_Code/openPASS/Common/openPassTypes.h new file mode 100644 index 0000000000000000000000000000000000000000..3d84e51deb902c025188b85333552f1477406ac6 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/Common/openPassTypes.h @@ -0,0 +1,41 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#pragma once + +#include <functional> +#include <string> +#include <variant> + +#include "namedType.h" + +namespace openpass::type { + +// TODO: MOVE TO CORE ONLY! +static constexpr int CoreId = 67798269; // ASCII: C O R E + +using AgentId = int; +using EntityId = NamedType<AgentId, struct EntityIdType>; +using Timestamp = NamedType<int, struct TimestampType>; +using EntityIds = std::vector<EntityId>; + +using FlatParameterKey = std::string; +using FlatParameterValue = std::variant< + bool, std::vector<bool>, + char, std::vector<char>, + int, std::vector<int>, + size_t, std::vector<size_t>, + float, std::vector<float>, + double, std::vector<double>, + std::string, std::vector<std::string>>; + +using FlatParameter = std::unordered_map<FlatParameterKey, FlatParameterValue>; + +} // namespace openpass::type diff --git a/OpenPass_Source_Code/openPASS/Common/openPassUtils.h b/OpenPass_Source_Code/openPASS/Common/openPassUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..316dbf3c01b9c5373dc474ae6003805d27955cce --- /dev/null +++ b/OpenPass_Source_Code/openPASS/Common/openPassUtils.h @@ -0,0 +1,88 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#pragma once + +#include <functional> +#include <iterator> +#include <sstream> +#include <string> +#include <vector> + +template <class... Ts> +struct overload : Ts... +{ + using Ts::operator()...; +}; + +template <class... Ts> +overload(Ts...)->overload<Ts...>; + +namespace openpass::utils { + +namespace vector { + +/// \brief convenience function to convert a vector into a string using a constom delimiter +/// \remark Please refer to the standard, how decimals are converted +/// \param values vector of strings +/// \param delimiter string in between the individual values +/// \return delimiter seperated list as string +template <typename T> +std::string to_string(const std::vector<T> &values, const std::string &delimiter = ",") +{ + if (values.empty()) + { + return ""; + } + + std::ostringstream oss; + std::copy(values.begin(), values.end(), std::ostream_iterator<T>(oss, delimiter.c_str())); + + return {oss.str(), 0, oss.str().length() - delimiter.size()}; +} + +} // namespace vector + +namespace FlatParameter { + +/// \brief visitor for parameter values of events +/// Converts the visitor values into strings and forwards the result to writer callable +/// Values in vectors are converted and seperated by a delimiter. +/// If value is 12.34 => writer("12.34"); +/// If value is {12.34, 23.45} => writer("12.34,23.45"); +/// \see openpass::type::FlatParameterValue +/// \see openpass::utils::vector::to_string +/// \param[in] writer callable collecting the converted value +/// \param[in] delimiter used for vector type (default = ",") +[[maybe_unused]] static auto to_string(std::function<void(std::string)> writer, const std::string &delimiter = ",") +{ + return overload{ + //[&](std::string &value) { writer(value); }, + [&](const std::string &value) { writer(value); }, + [&](auto &value) { + if constexpr (std::is_arithmetic_v<std::decay_t<decltype(value)>>) + { + writer(std::to_string(value)); + } + else // path for std::vector types + { + if (!value.empty()) + { + writer(vector::to_string(value, delimiter)); + } + } + }, + + }; +} + +} // namespace FlatParameter + +} // namespace openpass::utils diff --git a/OpenPass_Source_Code/openPASS/Common/openScenarioDefinitions.h b/OpenPass_Source_Code/openPASS/Common/openScenarioDefinitions.h index dbc1cb3cca005a983e2ffb9b105db15c8f53b78b..723ac5fc503cf8e4f731ab03ece362e333946975 100644 --- a/OpenPass_Source_Code/openPASS/Common/openScenarioDefinitions.h +++ b/OpenPass_Source_Code/openPASS/Common/openScenarioDefinitions.h @@ -56,7 +56,7 @@ struct StochasticAttribute struct ActorInformation { - std::optional<bool> triggeringAgentsAsActors{}; + bool actorIsTriggeringEntity{false}; std::optional<std::vector<std::string>> actors{}; }; diff --git a/OpenPass_Source_Code/openPASS/Common/parameter.h b/OpenPass_Source_Code/openPASS/Common/parameter.h index 64e9b9616ffff8a88427115e99c7cfffea222c21..08548b5089e57a7d714012eb51e65237b14b7706 100644 --- a/OpenPass_Source_Code/openPASS/Common/parameter.h +++ b/OpenPass_Source_Code/openPASS/Common/parameter.h @@ -9,9 +9,11 @@ *******************************************************************************/ #pragma once +#include <optional> +#include <string> +#include <utility> #include <variant> #include <vector> -#include <optional> #include "Common/stochasticDefinitions.h" diff --git a/OpenPass_Source_Code/openPASS/Common/vehicleComponentEvent.h b/OpenPass_Source_Code/openPASS/Common/vehicleComponentEvent.h index 6b4146b73084e3f1365222b0a33f69846ebd58e4..f5453d041692edcd43bdec25aa1f88debc72bf2d 100644 --- a/OpenPass_Source_Code/openPASS/Common/vehicleComponentEvent.h +++ b/OpenPass_Source_Code/openPASS/Common/vehicleComponentEvent.h @@ -32,12 +32,18 @@ public: VehicleComponentEvent(int time, const std::string &eventName, std::string source, - int agentId): + int agentId) : BasicEvent(time, eventName, - source), + source, + {agentId}, + {}), agentId(agentId) - {} + { + parameter.emplace("Source", source); + parameter.emplace("State", eventName); + } + VehicleComponentEvent(const VehicleComponentEvent&) = delete; VehicleComponentEvent(VehicleComponentEvent&&) = delete; VehicleComponentEvent& operator=(const VehicleComponentEvent&) = delete; diff --git a/OpenPass_Source_Code/openPASS/Common/worldDefinitions.h b/OpenPass_Source_Code/openPASS/Common/worldDefinitions.h index 9608f847ba70d71d5600a0156e12e42a9d7b6f73..b5f9fe4cbe79073a0c5e3c61c601955b5e5d3378 100644 --- a/OpenPass_Source_Code/openPASS/Common/worldDefinitions.h +++ b/OpenPass_Source_Code/openPASS/Common/worldDefinitions.h @@ -10,6 +10,8 @@ #pragma once +#include <limits> + #include "globalDefinitions.h" #include <set> #include "boost/graph/adjacency_list.hpp" diff --git a/OpenPass_Source_Code/openPASS/Components/Action_BrakeLight_Basic/action_brakelight_basic.cpp b/OpenPass_Source_Code/openPASS/Components/Action_BrakeLight_Basic/action_brakelight_basic.cpp index 84bdbd4a164546650e98e3781c60bb33f39a90db..f25c140d82c2ebd3d828c90f8d216c19c7991467 100644 --- a/OpenPass_Source_Code/openPASS/Components/Action_BrakeLight_Basic/action_brakelight_basic.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Action_BrakeLight_Basic/action_brakelight_basic.cpp @@ -35,7 +35,7 @@ extern "C" ACTION_BRAKELIGHT_BASICSHARED_EXPORT ModelInterface *OpenPASS_CreateI StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -53,7 +53,7 @@ extern "C" ACTION_BRAKELIGHT_BASICSHARED_EXPORT ModelInterface *OpenPASS_CreateI stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Action_BrakeLight_Basic/action_brakelight_basic_implementation.h b/OpenPass_Source_Code/openPASS/Components/Action_BrakeLight_Basic/action_brakelight_basic_implementation.h index f8a8d1ee3e28edb15182b627d43852a3ad328449..745b3a1aeaf5c45e0fc36bde3d35dbafe5d4b440 100644 --- a/OpenPass_Source_Code/openPASS/Components/Action_BrakeLight_Basic/action_brakelight_basic_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Action_BrakeLight_Basic/action_brakelight_basic_implementation.h @@ -13,7 +13,6 @@ #define ACTION_BRAKELIGHT_BASIC_IMPLEMENTATION_H #include "modelInterface.h" -#include "observationInterface.h" #include "primitiveSignals.h" /*! diff --git a/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriver.cpp b/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriver.cpp index 6221010bdc35704275508e474656692370f8d1bf..6e87aff3f8bed7ea33b5a66fa7271842d1514a09 100644 --- a/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriver.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriver.cpp @@ -35,7 +35,7 @@ extern "C" ACTION_LONGITUDINAL_DRIVER_SHARED_EXPORT ModelInterface *OpenPASS_Cre StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -53,7 +53,7 @@ extern "C" ACTION_LONGITUDINAL_DRIVER_SHARED_EXPORT ModelInterface *OpenPASS_Cre stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriverImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriverImplementation.cpp index 7804f7a7329a4864eb6f5df66f52a6e7c078ac80..0cc3b4b13fda47327545ba1d73676e5a72c006dc 100644 --- a/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriverImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriverImplementation.cpp @@ -68,4 +68,8 @@ void ActionLongitudinalDriverImplementation::Trigger(int time) GetAgent()->SetEffBrakePedal(in_brakePedalPos); //! Set gear GetAgent()->SetGear(in_gear); + + GetPublisher()->Publish("AccelerationPedalPosition", in_accPedalPos); + GetPublisher()->Publish("BrakePedalPosition", in_brakePedalPos); + GetPublisher()->Publish("Gear", in_gear); } diff --git a/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriverImplementation.h b/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriverImplementation.h index 1bdb61d98d76595a168c797223a413f3ed685888..0bac3a1f3facefdd20e42cadf079674c3c6bbb78 100644 --- a/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriverImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Action_LongitudinalDriver/action_longitudinalDriverImplementation.h @@ -35,7 +35,6 @@ #define ACTION_LONGITUDINAL_DRIVER_IMPLEMENTATION_H #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" #include "Common/primitiveSignals.h" //! \ingroup Action_LongitudinalDriver diff --git a/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasks.cpp b/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasks.cpp index d60126a11d4344de400b7ef1f4293c99f863ac3c..4a13f71159419c0b56273007eedfdea0471f6603 100644 --- a/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasks.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasks.cpp @@ -35,7 +35,7 @@ extern "C" ACTION_SECONDARY_DRIVER_TASKS_SHARED_EXPORT ModelInterface *OpenPASS_ StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -53,7 +53,7 @@ extern "C" ACTION_SECONDARY_DRIVER_TASKS_SHARED_EXPORT ModelInterface *OpenPASS_ stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasksImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasksImplementation.cpp index b6e8f96539ecc6ef08ffca656ec58a84b682bf06..91bacb337432a9a668861700618555845a195b20 100644 --- a/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasksImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasksImplementation.cpp @@ -65,12 +65,15 @@ void ActionSecondaryDriverTasksImplementation::Trigger(int time) { Q_UNUSED(time); - if (GetAgent()->GetEffBrakePedal()>0) + if (GetAgent()->GetEffBrakePedal() > 0.0) { GetAgent()->SetBrakeLight(true); - }else + GetPublisher()->Publish("BrakeLight", true); + } + else { GetAgent()->SetBrakeLight(false); + GetPublisher()->Publish("BrakeLight", false); } GetAgent()->SetIndicatorState(in_IndicatorState); @@ -78,4 +81,23 @@ void ActionSecondaryDriverTasksImplementation::Trigger(int time) GetAgent()->SetHighBeamLight(in_highBeamLightSwitch); GetAgent()->SetHorn(in_hornSwitch); GetAgent()->SetFlasher(in_flasherSwitch); + + GetPublisher()->Publish("IndicatorState", static_cast<int>(in_IndicatorState)); + + LightState effectiveLightState = LightState::Off; + + if (in_flasherSwitch) + { + effectiveLightState = LightState::Flash; + } + else if (in_highBeamLightSwitch) + { + effectiveLightState = LightState::HighBeam; + } + else if (in_headLightSwitch) + { + effectiveLightState = LightState::LowBeam; + } + + GetPublisher()->Publish("LightStatus", static_cast<int>(effectiveLightState)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasksImplementation.h b/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasksImplementation.h index cb1fc08eefc85e906fc7ba173c15d3b2c052f2f4..214b3321552534ac08df37687d5b56a424aad789 100644 --- a/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasksImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Action_SecondaryDriverTasks/action_secondaryDriverTasksImplementation.h @@ -17,7 +17,6 @@ #define ACTION_SECONDARY_DRIVER_TASKS_IMPLEMENTATION_H #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" #include "Common/primitiveSignals.h" /*! \addtogroup Action_SecondaryDriverTasks diff --git a/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdater.cpp b/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdater.cpp index e125252d0883888655407fcd797ad675ae3b0116..248ec6883ce9fb6cb8dedfcb737e2bd6dcb0640f 100644 --- a/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdater.cpp +++ b/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdater.cpp @@ -13,60 +13,61 @@ //----------------------------------------------------------------------------- #include "agentUpdater.h" + #include "agentUpdaterImplementation.h" -const std::string Version = "0.0.1"; +const static std::string VERSION = "0.2.0"; static const CallbackInterface *Callbacks = nullptr; extern "C" AGENT_UPDATER_SHARED_EXPORT const std::string &OpenPASS_GetVersion() { - return Version; + return VERSION; } extern "C" AGENT_UPDATER_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( - std::string componentName, - bool isInit, - int priority, - int offsetTime, - int responseTime, - int cycleTime, - StochasticsInterface *stochastics, - WorldInterface *world, - const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, - AgentInterface *agent, - const CallbackInterface *callbacks) + std::string componentName, + bool isInit, + int priority, + int offsetTime, + int responseTime, + int cycleTime, + StochasticsInterface *stochastics, + WorldInterface *world, + const ParameterInterface *parameters, + PublisherInterface * const publisher, + AgentInterface *agent, + const CallbackInterface *callbacks) { Callbacks = callbacks; try { - return (ModelInterface*)(new (std::nothrow) AgentUpdaterImplementation( - componentName, - isInit, - priority, - offsetTime, - responseTime, - cycleTime, - stochastics, - world, - parameters, - observations, - callbacks, - agent)); + return (ModelInterface *)(new (std::nothrow) AgentUpdaterImplementation( + componentName, + isInit, + priority, + offsetTime, + responseTime, + cycleTime, + stochastics, + world, + parameters, + publisher, + callbacks, + agent)); } - catch(const std::runtime_error &ex) + catch (const std::runtime_error &ex) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, ex.what()); } return nullptr; } - catch(...) + catch (...) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, "unexpected exception"); } @@ -77,30 +78,30 @@ extern "C" AGENT_UPDATER_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( extern "C" AGENT_UPDATER_SHARED_EXPORT void OpenPASS_DestroyInstance(ModelInterface *implementation) { - delete (AgentUpdaterImplementation*)implementation; + delete (AgentUpdaterImplementation *)implementation; } extern "C" AGENT_UPDATER_SHARED_EXPORT bool OpenPASS_UpdateInput(ModelInterface *implementation, - int localLinkId, - const std::shared_ptr<SignalInterface const> &data, - int time) + int localLinkId, + const std::shared_ptr<SignalInterface const> &data, + int time) { try { implementation->UpdateInput(localLinkId, data, time); } - catch(const std::runtime_error &ex) + catch (const std::runtime_error &ex) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, ex.what()); } return false; } - catch(...) + catch (...) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, "unexpected exception"); } @@ -112,26 +113,26 @@ extern "C" AGENT_UPDATER_SHARED_EXPORT bool OpenPASS_UpdateInput(ModelInterface } extern "C" AGENT_UPDATER_SHARED_EXPORT bool OpenPASS_UpdateOutput(ModelInterface *implementation, - int localLinkId, - std::shared_ptr<SignalInterface const> &data, - int time) + int localLinkId, + std::shared_ptr<SignalInterface const> &data, + int time) { try { implementation->UpdateOutput(localLinkId, data, time); } - catch(const std::runtime_error &ex) + catch (const std::runtime_error &ex) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, ex.what()); } return false; } - catch(...) + catch (...) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, "unexpected exception"); } @@ -143,24 +144,24 @@ extern "C" AGENT_UPDATER_SHARED_EXPORT bool OpenPASS_UpdateOutput(ModelInterface } extern "C" AGENT_UPDATER_SHARED_EXPORT bool OpenPASS_Trigger(ModelInterface *implementation, - int time) + int time) { try { implementation->Trigger(time); } - catch(const std::runtime_error &ex) + catch (const std::runtime_error &ex) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, ex.what()); } return false; } - catch(...) + catch (...) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, "unexpected exception"); } diff --git a/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdaterImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdaterImplementation.cpp index 69fb48c9cea77a34133493ee6c444997dc75e741..508f6ec989d1cd7ac2b2061ed681604ede86cc57 100644 --- a/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdaterImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdaterImplementation.cpp @@ -17,10 +17,8 @@ #include "agentUpdaterImplementation.h" #include <qglobal.h> -void AgentUpdaterImplementation::UpdateInput(int localLinkId, const std::shared_ptr<SignalInterface const> &data, int time) +void AgentUpdaterImplementation::UpdateInput(int localLinkId, const std::shared_ptr<SignalInterface const> &data, [[maybe_unused]] int time) { - Q_UNUSED(time); - if (localLinkId == 0) { // from DynamicsPrioritizer @@ -50,16 +48,14 @@ void AgentUpdaterImplementation::UpdateInput(int localLinkId, const std::shared_ } } -void AgentUpdaterImplementation::UpdateOutput(int localLinkId, std::shared_ptr<SignalInterface const> &data, int time) +void AgentUpdaterImplementation::UpdateOutput([[maybe_unused]] int localLinkId, + [[maybe_unused]] std::shared_ptr<SignalInterface const> &data, + [[maybe_unused]] int time) { - Q_UNUSED(localLinkId); - Q_UNUSED(data); - Q_UNUSED(time); } -void AgentUpdaterImplementation::Trigger(int time) +void AgentUpdaterImplementation::Trigger([[maybe_unused]] int time) { - Q_UNUSED(time); AgentInterface *agent = GetAgent(); agent->SetAcceleration(acceleration); @@ -70,5 +66,16 @@ void AgentUpdaterImplementation::Trigger(int time) agent->SetYawRate(yawRate); agent->SetSteeringWheelAngle(steeringWheelAngle); agent->SetCentripetalAcceleration(centripetalAcceleration); - agent->SetDistanceTraveled(travelDistance + agent->GetDistanceTraveled()); + + GetPublisher()->Publish("XPosition", positionX); + GetPublisher()->Publish("YPosition", positionY); + GetPublisher()->Publish("VelocityEgo", velocity); + GetPublisher()->Publish("AccelerationEgo", acceleration); + GetPublisher()->Publish("YawAngle", yaw); + GetPublisher()->Publish("YawRate", yawRate); + GetPublisher()->Publish("SteeringAngle", steeringWheelAngle); + + totalTravelDistance += travelDistance; + + GetPublisher()->Publish("TotalDistanceTraveled", totalTravelDistance); } diff --git a/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdaterImplementation.h b/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdaterImplementation.h index d8fe76c9dc4c7a6454073674d495c4e8b7465d33..a5ea24b18c5de4ba33ecbb5a1552173c0cf5a208 100644 --- a/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdaterImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/AgentUpdater/agentUpdaterImplementation.h @@ -32,7 +32,7 @@ #pragma once #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" +#include "Interfaces/publisherInterface.h" #include "Common/dynamicsSignal.h" /** @@ -55,7 +55,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : UnrestrictedModelInterface( @@ -68,7 +68,7 @@ public: stochastics, world, parameters, - observations, + publisher, callbacks, agent) {} @@ -126,4 +126,5 @@ private: double steeringWheelAngle {0.0}; double centripetalAcceleration {0.0}; double travelDistance {0.0}; + double totalTravelDistance {0.0}; }; diff --git a/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModel.cpp b/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModel.cpp index 057c968df82dbb84620a1e79b9056e051944883d..ecffda47de4febbd3701b956a82b859e046b1668 100644 --- a/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModel.cpp +++ b/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModel.cpp @@ -34,7 +34,7 @@ extern "C" ALGORITHM_AGENTFOLLOWINGDRIVERMODEL_SHARED_EXPORT ModelInterface *Ope StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -52,7 +52,7 @@ extern "C" ALGORITHM_AGENTFOLLOWINGDRIVERMODEL_SHARED_EXPORT ModelInterface *Ope stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModelImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModelImplementation.cpp index f295b55414c06dfc5032ca5c2d1706b824008a18..b5a4ea5194cf60793c8252e000e25b6e8d598ab6 100644 --- a/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModelImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModelImplementation.cpp @@ -27,7 +27,7 @@ AlgorithmAgentFollowingDriverModelImplementation::AlgorithmAgentFollowingDriverM StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : SensorInterface( @@ -40,7 +40,7 @@ AlgorithmAgentFollowingDriverModelImplementation::AlgorithmAgentFollowingDriverM stochastics, world, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModelImplementation.h b/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModelImplementation.h index 6fb9667b8fd47cca4c1d428281b969f7688a840b..1806b6fc6be8ac863c8b7947df8de03d1f0f9424 100644 --- a/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModelImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/AlgorithmAgentFollowingDriverModel/AlgorithmAgentFollowingDriverModelImplementation.h @@ -24,7 +24,6 @@ class AgentInterface; class StochasticsInterface; -class ObservationInterface; class ParameterInterface; class WorldInterface; @@ -55,7 +54,7 @@ public: //! \param [in] stochastics Stochastics instance //! \param [in] world World interface //! \param [in] parameters Paramaters - //! \param [in] observations Observation instance + //! \param [in] pubslisher Publisher instance //! \param [in] callbacks Callbacks //! \param [in] agent Agent AlgorithmAgentFollowingDriverModelImplementation( @@ -68,7 +67,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBraking.cpp b/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBraking.cpp index 7e80f127438ca99936ed18bf68e5495fe38f5fa0..cabf6bbf249b0d81e7c89d09651e1075aae402be 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBraking.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBraking.cpp @@ -13,29 +13,30 @@ //----------------------------------------------------------------------------- #include "algorithm_autonomousEmergencyBraking.h" + #include "algorithm_autonomousEmergencyBrakingImplementation.h" -const std::string Version = "0.0.1"; +const static std::string VERSION = "0.2.0"; static const CallbackInterface *Callbacks = nullptr; extern "C" ALGORITHM_AEB_SHARED_EXPORT const std::string &OpenPASS_GetVersion() { - return Version; + return VERSION; } extern "C" ALGORITHM_AEB_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( - std::string componentName, - bool isInit, - int priority, - int offsetTime, - int responseTime, - int cycleTime, - StochasticsInterface *stochastics, - WorldInterface *world, - const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, - AgentInterface *agent, - const CallbackInterface *callbacks) + std::string componentName, + bool isInit, + int priority, + int offsetTime, + int responseTime, + int cycleTime, + StochasticsInterface *stochastics, + WorldInterface *world, + const ParameterInterface *parameters, + PublisherInterface * const publisher, + AgentInterface *agent, + const CallbackInterface *callbacks) { Q_UNUSED(world); @@ -43,31 +44,31 @@ extern "C" ALGORITHM_AEB_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( try { - return (ModelInterface*)(new (std::nothrow) AlgorithmAutonomousEmergencyBrakingImplementation( - componentName, - isInit, - priority, - offsetTime, - responseTime, - cycleTime, - stochastics, - parameters, - observations, - callbacks, - agent)); + return (ModelInterface *)(new (std::nothrow) AlgorithmAutonomousEmergencyBrakingImplementation( + componentName, + isInit, + priority, + offsetTime, + responseTime, + cycleTime, + stochastics, + parameters, + publisher, + callbacks, + agent)); } - catch(const std::runtime_error &ex) + catch (const std::runtime_error &ex) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, ex.what()); } return nullptr; } - catch(...) + catch (...) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, "unexpected exception"); } @@ -78,30 +79,30 @@ extern "C" ALGORITHM_AEB_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( extern "C" ALGORITHM_AEB_SHARED_EXPORT void OpenPASS_DestroyInstance(ModelInterface *implementation) { - delete (AlgorithmAutonomousEmergencyBrakingImplementation*)implementation; + delete (AlgorithmAutonomousEmergencyBrakingImplementation *)implementation; } extern "C" ALGORITHM_AEB_SHARED_EXPORT bool OpenPASS_UpdateInput(ModelInterface *implementation, - int localLinkId, - const std::shared_ptr<SignalInterface const> &data, - int time) + int localLinkId, + const std::shared_ptr<SignalInterface const> &data, + int time) { try { implementation->UpdateInput(localLinkId, data, time); } - catch(const std::runtime_error &ex) + catch (const std::runtime_error &ex) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, ex.what()); } return false; } - catch(...) + catch (...) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, "unexpected exception"); } @@ -113,26 +114,26 @@ extern "C" ALGORITHM_AEB_SHARED_EXPORT bool OpenPASS_UpdateInput(ModelInterface } extern "C" ALGORITHM_AEB_SHARED_EXPORT bool OpenPASS_UpdateOutput(ModelInterface *implementation, - int localLinkId, - std::shared_ptr<SignalInterface const> &data, - int time) + int localLinkId, + std::shared_ptr<SignalInterface const> &data, + int time) { try { implementation->UpdateOutput(localLinkId, data, time); } - catch(const std::runtime_error &ex) + catch (const std::runtime_error &ex) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, ex.what()); } return false; } - catch(...) + catch (...) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, "unexpected exception"); } @@ -144,24 +145,24 @@ extern "C" ALGORITHM_AEB_SHARED_EXPORT bool OpenPASS_UpdateOutput(ModelInterface } extern "C" ALGORITHM_AEB_SHARED_EXPORT bool OpenPASS_Trigger(ModelInterface *implementation, - int time) + int time) { try { implementation->Trigger(time); } - catch(const std::runtime_error &ex) + catch (const std::runtime_error &ex) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, ex.what()); } return false; } - catch(...) + catch (...) { - if(Callbacks != nullptr) + if (Callbacks != nullptr) { Callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, "unexpected exception"); } diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBrakingImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBrakingImplementation.cpp index 06f9a30090418084006ab56837a4aa704378f923..d51c152005a832d1d8fb7555c94d6301938aac6f 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBrakingImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBrakingImplementation.cpp @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2019 in-tech GmbH +* Copyright (c) 2019, 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -12,23 +12,16 @@ /** @file AlgorithmAEBmplementation.cpp */ //----------------------------------------------------------------------------- +#include "algorithm_autonomousEmergencyBrakingImplementation.h" + #include <limits> #include <memory> -#include <QtGlobal> -#include <QCoreApplication> - -#include "Interfaces/parameterInterface.h" - #include "Common/commonTools.h" #include "Common/eventTypes.h" - #include "Components/SensorFusion_OSI/sensorFusionQuery.h" - -#include "algorithm_autonomousEmergencyBrakingImplementation.h" #include "boundingBoxCalculation.h" - AlgorithmAutonomousEmergencyBrakingImplementation::AlgorithmAutonomousEmergencyBrakingImplementation( std::string componentName, bool isInit, @@ -36,11 +29,11 @@ AlgorithmAutonomousEmergencyBrakingImplementation::AlgorithmAutonomousEmergencyB int offsetTime, int responseTime, int cycleTime, - StochasticsInterface* stochastics, - const ParameterInterface* parameters, - const std::map<int, ObservationInterface*>* observations, - const CallbackInterface* callbacks, - AgentInterface* agent) : + StochasticsInterface *stochastics, + const ParameterInterface *parameters, + PublisherInterface * const publisher, + const CallbackInterface *callbacks, + AgentInterface *agent) : AlgorithmInterface( componentName, isInit, @@ -50,7 +43,7 @@ AlgorithmAutonomousEmergencyBrakingImplementation::AlgorithmAutonomousEmergencyB cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent) { @@ -67,26 +60,28 @@ AlgorithmAutonomousEmergencyBrakingImplementation::AlgorithmAutonomousEmergencyB try { - observer = GetObservations()->at(0); - if (observer == nullptr) { throw std::runtime_error(""); } + if (GetPublisher() == nullptr) + { + throw std::runtime_error(""); + } } catch (...) { - const std::string msg = COMPONENTNAME + " invalid observation module setup"; + const std::string msg = COMPONENTNAME + " invalid publisher module setup"; LOG(CbkLogLevel::Error, msg); throw std::runtime_error(msg); } } -void AlgorithmAutonomousEmergencyBrakingImplementation::ParseParameters(const ParameterInterface* parameters) +void AlgorithmAutonomousEmergencyBrakingImplementation::ParseParameters(const ParameterInterface *parameters) { ttcBrake = parameters->GetParametersDouble().at("TTC"); brakingAcceleration = parameters->GetParametersDouble().at("Acceleration"); collisionDetectionLongitudinalBoundary = parameters->GetParametersDouble().at("CollisionDetectionLongitudinalBoundary"); collisionDetectionLateralBoundary = parameters->GetParametersDouble().at("CollisionDetectionLateralBoundary"); - const auto& sensorList = parameters->GetParameterLists().at("SensorLinks"); - for (const auto& sensorLink : sensorList) + const auto &sensorList = parameters->GetParameterLists().at("SensorLinks"); + for (const auto &sensorLink : sensorList) { if (sensorLink->GetParametersString().at("InputId") == "Camera") { @@ -96,13 +91,11 @@ void AlgorithmAutonomousEmergencyBrakingImplementation::ParseParameters(const Pa } void AlgorithmAutonomousEmergencyBrakingImplementation::UpdateInput(int localLinkId, - const std::shared_ptr<SignalInterface const>& data, int time) + const std::shared_ptr<SignalInterface const> &data, + [[maybe_unused]] int time) { - Q_UNUSED(time); - std::stringstream log; - log << COMPONENTNAME << " (component " << GetComponentName() << ", agent " << GetAgent()->GetId() << - ", input data for local link " << localLinkId << ": "; + log << COMPONENTNAME << " (component " << GetComponentName() << ", agent " << GetAgent()->GetId() << ", input data for local link " << localLinkId << ": "; LOG(CbkLogLevel::Debug, log.str()); //from SensorFusion @@ -129,17 +122,16 @@ void AlgorithmAutonomousEmergencyBrakingImplementation::UpdateInput(int localLin } void AlgorithmAutonomousEmergencyBrakingImplementation::UpdateOutput(int localLinkId, - std::shared_ptr<SignalInterface const>& data, int time) + std::shared_ptr<SignalInterface const> &data, + [[maybe_unused]] int time) { - Q_UNUSED(time); - if (localLinkId == 0) { try { data = std::make_shared<AccelerationSignal const>(componentState, activeAcceleration); } - catch (const std::bad_alloc&) + catch (const std::bad_alloc &) { const std::string msg = COMPONENTNAME + " could not instantiate signal"; LOG(CbkLogLevel::Debug, msg); @@ -155,18 +147,19 @@ void AlgorithmAutonomousEmergencyBrakingImplementation::UpdateOutput(int localLi } } -void AlgorithmAutonomousEmergencyBrakingImplementation::Trigger(int time) +void AlgorithmAutonomousEmergencyBrakingImplementation::Trigger([[maybe_unused]] int time) { const auto ttc = CalculateTTC(); + if (componentState == ComponentState::Disabled && ShouldBeActivated(ttc)) { componentState = ComponentState::Acting; - UpdateAcceleration(time); + UpdateAcceleration(); } - else if(componentState == ComponentState::Acting && ShouldBeDeactivated(ttc)) + else if (componentState == ComponentState::Acting && ShouldBeDeactivated(ttc)) { componentState = ComponentState::Disabled; - UpdateAcceleration(time); + UpdateAcceleration(); } } @@ -180,7 +173,7 @@ bool AlgorithmAutonomousEmergencyBrakingImplementation::ShouldBeDeactivated(cons return ttc > (ttcBrake * 1.5); } -double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateObjectTTC(const osi3::BaseMoving& baseMoving) +double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateObjectTTC(const osi3::BaseMoving &baseMoving) { TtcCalculations::TtcParameters own; own.length = GetAgent()->GetLength() + collisionDetectionLongitudinalBoundary; @@ -194,7 +187,7 @@ double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateObjectTTC(con own.accelerationY = 0.0; own.yaw = 0.0; own.yawRate = GetAgent()->GetYawRate(); - own.yawAcceleration = 0.0; // GetAgent()->GetYawAcceleration() not implemented yet + own.yawAcceleration = 0.0; // GetAgent()->GetYawAcceleration() not implemented yet TtcCalculations::TtcParameters opponent; opponent.length = baseMoving.dimension().length() + collisionDetectionLongitudinalBoundary; opponent.width = baseMoving.dimension().width() + collisionDetectionLateralBoundary; @@ -211,7 +204,7 @@ double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateObjectTTC(con return TtcCalculations::CalculateObjectTTC(own, opponent, ttcBrake * 1.5, GetCycleTime()); } -double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateObjectTTC(const osi3::BaseStationary& baseStationary) +double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateObjectTTC(const osi3::BaseStationary &baseStationary) { TtcCalculations::TtcParameters own; own.length = GetAgent()->GetLength() + collisionDetectionLongitudinalBoundary; @@ -225,17 +218,17 @@ double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateObjectTTC(con own.accelerationY = 0.0; own.yaw = 0.0; own.yawRate = GetAgent()->GetYawRate(); - own.yawAcceleration = 0.0; // GetAgent()->GetYawAcceleration() not implemented yet + own.yawAcceleration = 0.0; // GetAgent()->GetYawAcceleration() not implemented yet TtcCalculations::TtcParameters opponent; opponent.length = baseStationary.dimension().length() + collisionDetectionLongitudinalBoundary; opponent.width = baseStationary.dimension().width() + collisionDetectionLateralBoundary; - opponent.frontLength = 0.5 * opponent.length; - opponent.backLength = 0.5 * opponent.length; + opponent.frontLength = 0.5 * opponent.length; + opponent.backLength = 0.5 * opponent.length; opponent.position = {baseStationary.position().x(), baseStationary.position().y()}; - opponent.velocityX = - GetAgent()->GetVelocity(); + opponent.velocityX = -GetAgent()->GetVelocity(); opponent.velocityY = 0.0; - opponent.accelerationX = - GetAgent()->GetAcceleration(); + opponent.accelerationX = -GetAgent()->GetAcceleration(); opponent.accelerationY = 0.0; opponent.yaw = baseStationary.orientation().yaw(); opponent.yawRate = 0.0; @@ -247,7 +240,7 @@ double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateObjectTTC(con double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateTTC() { double ttc = std::numeric_limits<double>::max(); - for (const auto& detectedObject : detectedMovingObjects) + for (const auto &detectedObject : detectedMovingObjects) { double objectTtc = CalculateObjectTTC(detectedObject.base()); if (objectTtc < ttc) @@ -255,7 +248,7 @@ double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateTTC() ttc = objectTtc; } } - for (const auto& detectedObject : detectedStationaryObjects) + for (const auto &detectedObject : detectedStationaryObjects) { double objectTtc = CalculateObjectTTC(detectedObject.base()); if (objectTtc < ttc) @@ -267,29 +260,22 @@ double AlgorithmAutonomousEmergencyBrakingImplementation::CalculateTTC() return ttc; } -void AlgorithmAutonomousEmergencyBrakingImplementation::UpdateAcceleration(const int time) +void AlgorithmAutonomousEmergencyBrakingImplementation::SetAcceleration(double setValue) { - std::shared_ptr<VehicleComponentEvent> event; + activeAcceleration = setValue; + GetPublisher()->Publish(COMPONENTNAME, ComponentEvent({{"ComponentState", openpass::utils::to_string(componentState)}})); +} - if(componentState == ComponentState::Acting && activeAcceleration != brakingAcceleration) - { - activeAcceleration = brakingAcceleration; - event = std::make_shared<VehicleComponentEvent>(time, - "AEBActive", - COMPONENTNAME, - GetAgent()->GetId()); - } - else if (componentState == ComponentState::Disabled && activeAcceleration != 0.0) +void AlgorithmAutonomousEmergencyBrakingImplementation::UpdateAcceleration() +{ + if (componentState == ComponentState::Acting && + (activeAcceleration - brakingAcceleration) != 0.0) { - activeAcceleration = 0.0; - event = std::make_shared<VehicleComponentEvent>(time, - "AEBInactive", - COMPONENTNAME, - GetAgent()->GetId()); + SetAcceleration(brakingAcceleration); } - - if(event.get()) + else if (componentState == ComponentState::Disabled && + activeAcceleration != 0.0) { - observer->InsertEvent(event); + SetAcceleration(0.0); } } diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBrakingImplementation.h b/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBrakingImplementation.h index a7933629ae3906e62d82f5a89273e84fe57be767..9ed850502cb67ee296775f1c68f0f1bf94aa26bd 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBrakingImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_AEB/algorithm_autonomousEmergencyBrakingImplementation.h @@ -34,12 +34,13 @@ #include <vector> -#include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" #include "Common/accelerationSignal.h" -#include "Common/vehicleComponentEvent.h" #include "Common/primitiveSignals.h" #include "Common/sensorDataSignal.h" +#include "Common/vehicleComponentEvent.h" +#include "Interfaces/modelInterface.h" +#include "Interfaces/parameterInterface.h" +#include "Interfaces/publisherInterface.h" #include "osi3/osi_sensordata.pb.h" class AlgorithmAutonomousEmergencyBrakingImplementation : public AlgorithmInterface @@ -54,16 +55,16 @@ public: int offsetTime, int responseTime, int cycleTime, - StochasticsInterface* stochastics, - const ParameterInterface* parameters, - const std::map<int, ObservationInterface*>* observations, - const CallbackInterface* callbacks, - AgentInterface* agent); - AlgorithmAutonomousEmergencyBrakingImplementation(const AlgorithmAutonomousEmergencyBrakingImplementation&) = delete; - AlgorithmAutonomousEmergencyBrakingImplementation(AlgorithmAutonomousEmergencyBrakingImplementation&&) = delete; - AlgorithmAutonomousEmergencyBrakingImplementation& operator=(const AlgorithmAutonomousEmergencyBrakingImplementation&) = + StochasticsInterface *stochastics, + const ParameterInterface *parameters, + PublisherInterface * const publisher, + const CallbackInterface *callbacks, + AgentInterface *agent); + AlgorithmAutonomousEmergencyBrakingImplementation(const AlgorithmAutonomousEmergencyBrakingImplementation &) = delete; + AlgorithmAutonomousEmergencyBrakingImplementation(AlgorithmAutonomousEmergencyBrakingImplementation &&) = delete; + AlgorithmAutonomousEmergencyBrakingImplementation &operator=(const AlgorithmAutonomousEmergencyBrakingImplementation &) = delete; - AlgorithmAutonomousEmergencyBrakingImplementation& operator=(AlgorithmAutonomousEmergencyBrakingImplementation&&) = + AlgorithmAutonomousEmergencyBrakingImplementation &operator=(AlgorithmAutonomousEmergencyBrakingImplementation &&) = delete; virtual ~AlgorithmAutonomousEmergencyBrakingImplementation() = default; @@ -79,7 +80,7 @@ public: * \param[in] data Referenced signal (copied by sending component) * \param[in] time Current scheduling time */ - virtual void UpdateInput(int localLinkId, const std::shared_ptr<SignalInterface const>& data, int time); + virtual void UpdateInput(int localLinkId, const std::shared_ptr<SignalInterface const> &data, int time); /*! * \brief Update outputs. @@ -93,7 +94,7 @@ public: * \param[out] data Referenced signal (copied by this component) * \param[in] time Current scheduling time */ - virtual void UpdateOutput(int localLinkId, std::shared_ptr<SignalInterface const>& data, int time); + virtual void UpdateOutput(int localLinkId, std::shared_ptr<SignalInterface const> &data, int time); /*! * \brief Process data within component. @@ -122,7 +123,7 @@ private: * \param parameters ParameterInterface containing braking information * ------------------------------------------------------------------------ */ - void ParseParameters(const ParameterInterface* parameters); + void ParseParameters(const ParameterInterface *parameters); /*! * \brief Calculates the minimim ttc (time to collision) of all objects the linked sensors @@ -137,14 +138,14 @@ private: * \param baseMoving osi BaseMoving of other object * \return ttc */ - double CalculateObjectTTC(const osi3::BaseMoving& baseMoving); + double CalculateObjectTTC(const osi3::BaseMoving &baseMoving); /*! * \brief Calculates the ttc between a stationary object and the own agent * \param baseStationary osi BaseStationary of other object * \return ttc */ - double CalculateObjectTTC(const osi3::BaseStationary& baseStationary); + double CalculateObjectTTC(const osi3::BaseStationary &baseStationary); /*! * \brief ShouldBeActivated Determines if the Autonomous Emergency Braking system @@ -166,28 +167,28 @@ private: bool ShouldBeDeactivated(double ttc) const; /*! - * \brief Sets the current acceleration of the system + * \brief Checks if current acceleration of the system needs to be updated * - * The acceleration is determined by the currently active stage. After a - * stage gets activated the acceralation moves to the defined acceleration of - * this stage by a parametrized gradient. - * - * \param time current timeStep + * The acceleration is determined by the currently active stage. + */ + void UpdateAcceleration(); + + /*! + * \brief Sets the current acceleration of the system */ - void UpdateAcceleration(const int time); + void SetAcceleration(double setValue); std::vector<int> sensors; ///!< Collection of sensor input ids - double collisionDetectionLongitudinalBoundary {0.0}; ///!< Additional length added to the vehicle boundary when checking for collision detection - double collisionDetectionLateralBoundary {0.0}; ///!< Additional width added to the vehicle boundary when checking for collision detection + double collisionDetectionLongitudinalBoundary{0.0}; ///!< Additional length added to the vehicle boundary when checking for collision detection + double collisionDetectionLateralBoundary{0.0}; ///!< Additional width added to the vehicle boundary when checking for collision detection - ObservationInterface* observer = nullptr; ///!< Observer containing the eventnetwork into which (de-)activation events are inserted - std::vector<osi3::DetectedMovingObject> detectedMovingObjects; ///!< Collection of moving objects detected by connected sensors + std::vector<osi3::DetectedMovingObject> detectedMovingObjects; ///!< Collection of moving objects detected by connected sensors std::vector<osi3::DetectedStationaryObject> detectedStationaryObjects; ///!< Collection of stationary objects detected by connected sensors ComponentState componentState = ComponentState::Disabled; ///!< Current state of the AEB component - double ttcBrake{0.0}; ///!< The minimum Time-To-Collision before the AEB component activates + double ttcBrake{0.0}; ///!< The minimum Time-To-Collision before the AEB component activates double brakingAcceleration{0.0}; ///!< The acceleration provided by the AEB component when activated (should be negative) - double activeAcceleration {0.0}; ///!< The current acceleration actively provided by the AEB component (should be 0.0 when off) + double activeAcceleration{0.0}; ///!< The current acceleration actively provided by the AEB component (should be 0.0 when off) }; diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_CruiseControlByDistance/algorithm_cruisecontrolbydistance.cpp b/OpenPass_Source_Code/openPASS/Components/Algorithm_CruiseControlByDistance/algorithm_cruisecontrolbydistance.cpp index 2f3404b3e76890ad948bd5a4ed8084b37e05812c..c9317f4ed5a1e8a18b0015a8bdcb4ce71bcb3f9d 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_CruiseControlByDistance/algorithm_cruisecontrolbydistance.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_CruiseControlByDistance/algorithm_cruisecontrolbydistance.cpp @@ -35,7 +35,7 @@ extern "C" ALGORITHM_CRUISECONTROLBYDISTANCESHARED_EXPORT ModelInterface *OpenPA StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -54,7 +54,7 @@ extern "C" ALGORITHM_CRUISECONTROLBYDISTANCESHARED_EXPORT ModelInterface *OpenPA cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent->GetAgentId())); } diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_CruiseControlByDistance/algorithm_cruisecontrolbydistance_implementation.h b/OpenPass_Source_Code/openPASS/Components/Algorithm_CruiseControlByDistance/algorithm_cruisecontrolbydistance_implementation.h index 43787868b50f965a5e938858ebf246fcc3a608ba..4942f2f5db15ca7c7cc20cd73e59c86cb4e966a1 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_CruiseControlByDistance/algorithm_cruisecontrolbydistance_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_CruiseControlByDistance/algorithm_cruisecontrolbydistance_implementation.h @@ -106,7 +106,7 @@ public: int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, int agentId) : AlgorithmInterface( @@ -118,7 +118,7 @@ public: cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agentId) { diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapper.cpp b/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapper.cpp index 3e40be9d67b34f013c8a6fba673d7b2ce2b915d2..858d9de1ccc1daf738870f878f46e355c5b2d1b0 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapper.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapper.cpp @@ -28,7 +28,7 @@ extern "C" ALGORITHM_FMUWRAPPER_SHARED_EXPORT ModelInterface *OpenPASS_CreateIns StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -43,7 +43,7 @@ extern "C" ALGORITHM_FMUWRAPPER_SHARED_EXPORT ModelInterface *OpenPASS_CreateIns world, stochastics, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapper.h b/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapper.h index c8bc4784a5c882e542c973a55eab6703115e6c35..84e4abe944bbbc766220c9eec78cdba4b73a6f09 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapper.h +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapper.h @@ -24,7 +24,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks); diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapperImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapperImplementation.cpp index 69530e55bdfb977554287297a7c1220e642c6532..29bab2b29cf1c01c640a34d24ff1e2194caf2770 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapperImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapperImplementation.cpp @@ -35,7 +35,7 @@ AlgorithmFmuWrapperImplementation::AlgorithmFmuWrapperImplementation(std::string WorldInterface* world, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface* agent) : UnrestrictedModelInterface(componentName, @@ -47,7 +47,7 @@ AlgorithmFmuWrapperImplementation::AlgorithmFmuWrapperImplementation(std::string stochastics, world, parameters, - observations, + publisher, callbacks, agent), startTime { 0 }, diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapperImplementation.h b/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapperImplementation.h index d39826c782262106a1ed90c74a060c00b7f32854..4d177432d3940eb7f2d7628786a913d7f5ad8bea 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapperImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_FmuWrapper/AlgorithmFmuWrapperImplementation.h @@ -47,7 +47,7 @@ public: WorldInterface* world, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface* agent); diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_Lateral/algorithm_lateral.cpp b/OpenPass_Source_Code/openPASS/Components/Algorithm_Lateral/algorithm_lateral.cpp index 901be34ba0701d5fb7c75c8a6737108efdf40d9b..173fe213b3ebff99c2d175922ae573f60886901d 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_Lateral/algorithm_lateral.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_Lateral/algorithm_lateral.cpp @@ -35,7 +35,7 @@ extern "C" ALGORITHM_LATERAL_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstan StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -54,7 +54,7 @@ extern "C" ALGORITHM_LATERAL_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstan cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_Lateral/algorithm_lateralImplementation.h b/OpenPass_Source_Code/openPASS/Components/Algorithm_Lateral/algorithm_lateralImplementation.h index efecd4c615e278ba38b72aefc89e8f27a2f88b77..5415025dc65ec8394fb3b87f9c55b720ae67e67d 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_Lateral/algorithm_lateralImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_Lateral/algorithm_lateralImplementation.h @@ -12,7 +12,6 @@ #pragma once #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" #include "Common/primitiveSignals.h" /** \addtogroup Algorithm_Lateral @@ -102,7 +101,7 @@ public: int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : AlgorithmInterface( @@ -114,7 +113,7 @@ public: cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent) {} diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_Longitudinal/algorithm_longitudinal.cpp b/OpenPass_Source_Code/openPASS/Components/Algorithm_Longitudinal/algorithm_longitudinal.cpp index 84a1e58d2b8bb4a4a0c273f1279ba86fa3292b40..35ec0f0d0a9f516e0ef4c07a5c4344e1e0769252 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_Longitudinal/algorithm_longitudinal.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_Longitudinal/algorithm_longitudinal.cpp @@ -35,7 +35,7 @@ extern "C" ALGORITHM_LONGITUDINAL_SHARED_EXPORT ModelInterface *OpenPASS_CreateI StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -54,7 +54,7 @@ extern "C" ALGORITHM_LONGITUDINAL_SHARED_EXPORT ModelInterface *OpenPASS_CreateI cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Algorithm_Longitudinal/algorithm_longitudinalImplementation.h b/OpenPass_Source_Code/openPASS/Components/Algorithm_Longitudinal/algorithm_longitudinalImplementation.h index 4f1eb89f8a774cf6e646b4155feafc3060ab1384..f61de965d7af2eb3ad2bcfd174d9d11c9358c4a8 100644 --- a/OpenPass_Source_Code/openPASS/Components/Algorithm_Longitudinal/algorithm_longitudinalImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Algorithm_Longitudinal/algorithm_longitudinalImplementation.h @@ -68,7 +68,6 @@ #pragma once #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" #include "Common/primitiveSignals.h" #include "algorithm_longitudinalCalculations.h" #include "Components/Sensor_Driver/Signals/sensorDriverSignal.h" @@ -98,7 +97,7 @@ public: int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : AlgorithmInterface( @@ -110,7 +109,7 @@ public: cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components/ComponentController/componentController.cpp b/OpenPass_Source_Code/openPASS/Components/ComponentController/componentController.cpp index 89557d14f5823f1b814dac9f821e17c8fa2f6709..a1a4cb388a3a1bbeaa64113fd4a1b01be85fc60c 100644 --- a/OpenPass_Source_Code/openPASS/Components/ComponentController/componentController.cpp +++ b/OpenPass_Source_Code/openPASS/Components/ComponentController/componentController.cpp @@ -33,7 +33,7 @@ extern "C" COMPONENT_CONTROLLER_SHARED_EXPORT ModelInterface *OpenPASS_CreateIns StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks, SimulationSlave::EventNetworkInterface * const eventNetwork) @@ -52,7 +52,7 @@ extern "C" COMPONENT_CONTROLLER_SHARED_EXPORT ModelInterface *OpenPASS_CreateIns stochastics, world, parameters, - observations, + publisher, callbacks, agent, eventNetwork)); diff --git a/OpenPass_Source_Code/openPASS/Components/ComponentController/componentControllerImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/ComponentController/componentControllerImplementation.cpp index 7059ad98c7e20f743bca398a5be9311ccb6e1fa7..4c7ef88d4e909acda1b1e74c81d0ab2b05d24c71 100644 --- a/OpenPass_Source_Code/openPASS/Components/ComponentController/componentControllerImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/ComponentController/componentControllerImplementation.cpp @@ -19,7 +19,6 @@ #include "Interfaces/eventNetworkInterface.h" #include "Common/eventTypes.h" #include "Common/componentStateChangeEvent.h" -#include "Common/componentWarningEvent.h" ComponentControllerImplementation::ComponentControllerImplementation(std::string componentName, bool isInit, @@ -30,7 +29,7 @@ ComponentControllerImplementation::ComponentControllerImplementation(std::string StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent, SimulationSlave::EventNetworkInterface* const eventNetwork) : @@ -44,7 +43,7 @@ ComponentControllerImplementation::ComponentControllerImplementation(std::string stochastics, world, parameters, - observations, + publisher, callbacks, agent, eventNetwork), @@ -52,11 +51,9 @@ ComponentControllerImplementation::ComponentControllerImplementation(std::string { } -void ComponentControllerImplementation::UpdateInput(int localLinkId, const std::shared_ptr<SignalInterface const>& data, int time) +void ComponentControllerImplementation::UpdateInput(int localLinkId, const std::shared_ptr<SignalInterface const>& data, [[maybe_unused]] int time) { - Q_UNUSED(time); - - const auto signal = SignalCast<AgentCompToCompCtrlSignal const>(data, localLinkId); + const auto signal = SignalCast<AgentCompToCompCtrlSignal>(data, localLinkId); if (stateManager.LocalLinkIdIsRegistered(localLinkId)) { @@ -69,7 +66,7 @@ void ComponentControllerImplementation::UpdateInput(int localLinkId, const std:: ComponentType componentType = signal->GetComponentType(); if(componentType == ComponentType::VehicleComponent) { - const auto castedSignal = SignalCast<VehicleCompToCompCtrlSignal const>(signal, localLinkId); + const auto castedSignal = SignalCast<VehicleCompToCompCtrlSignal>(signal, localLinkId); componentStateInformation = std::make_shared<AdasComponentStateInformation>(castedSignal->GetComponentType(), castedSignal->GetAgentComponentName(), castedSignal->GetCurrentState(), @@ -94,10 +91,8 @@ void ComponentControllerImplementation::UpdateInput(int localLinkId, const std:: } } -void ComponentControllerImplementation::UpdateOutput(int localLinkId, std::shared_ptr<SignalInterface const>& data, int time) +void ComponentControllerImplementation::UpdateOutput(int localLinkId, std::shared_ptr<SignalInterface const>& data, [[maybe_unused]] int time) { - Q_UNUSED(time); - ComponentState maxReachableState = ComponentState::Undefined; if (stateManager.LocalLinkIdIsRegistered(localLinkId)) @@ -128,10 +123,8 @@ void ComponentControllerImplementation::UpdateOutput(int localLinkId, std::share * Each trigger, pull ComponentChangeEvents for this agent and pass the list of them * to the stateManager for proper handling of changes of component max reachable state */ -void ComponentControllerImplementation::Trigger(int time) +void ComponentControllerImplementation::Trigger([[maybe_unused]] int time) { - Q_UNUSED(time); - // get the event list and filter by ComponentChangeEvents and this agent's id const auto stateChangeEventList = GetEventNetwork()->GetActiveEventCategory(EventDefinitions::EventCategory::ComponentStateChange); const auto agentId = GetAgent()->GetId(); diff --git a/OpenPass_Source_Code/openPASS/Components/ComponentController/componentControllerImplementation.h b/OpenPass_Source_Code/openPASS/Components/ComponentController/componentControllerImplementation.h index 172c26bd0a7a3ef2e5e88c2a65b3e10b0a8dae39..3db02b981e81e2efa35a5514fe0d0a610cc4e265 100644 --- a/OpenPass_Source_Code/openPASS/Components/ComponentController/componentControllerImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/ComponentController/componentControllerImplementation.h @@ -42,7 +42,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent, SimulationSlave::EventNetworkInterface * const eventNetwork); @@ -91,19 +91,17 @@ public: virtual void Trigger(int time); private: - template <typename T> - const std::shared_ptr<T const> SignalCast(std::shared_ptr<SignalInterface const> const& baseSignal, int linkId) + template <typename T, typename Signal> + const std::shared_ptr<T const> SignalCast(Signal&& signal, int linkId) { - const auto castedSignal = std::dynamic_pointer_cast<T const>(baseSignal); - - if (!castedSignal) + if (const auto castedSignal = std::dynamic_pointer_cast<T const>(std::forward<Signal>(signal))) { - const std::string msg = COMPONENTNAME + " invalid signaltype on link " + std::to_string(linkId); - LOG(CbkLogLevel::Debug, msg); - throw std::runtime_error(msg); + return castedSignal; } - return castedSignal; + const std::string msg = COMPONENTNAME + " invalid signaltype on link " + std::to_string(linkId); + LOG(CbkLogLevel::Debug, msg); + throw std::runtime_error(msg); } std::map<int, std::string> driverInputChannels; diff --git a/OpenPass_Source_Code/openPASS/Components/ComponentController/condition.cpp b/OpenPass_Source_Code/openPASS/Components/ComponentController/condition.cpp index 5f813ae2b958975c06ec3d4201609d252f5554c6..b1aeafc29b2cf829c95705477a7c2fd02456a3e5 100644 --- a/OpenPass_Source_Code/openPASS/Components/ComponentController/condition.cpp +++ b/OpenPass_Source_Code/openPASS/Components/ComponentController/condition.cpp @@ -7,50 +7,29 @@ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -#include <QtGlobal> - #include "condition.h" using namespace ComponentControl; -FixedComponentStateExpression::FixedComponentStateExpression(ComponentState value) : value(value) +ComponentState FixedComponentStateExpression::Get(const StateMapping &) const { - -} - -ComponentState FixedComponentStateExpression::Get(const std::map<std::string, std::pair<ComponentType, ComponentState>> &componentNameToComponentTypeAndStateMap) const -{ - Q_UNUSED(componentNameToComponentTypeAndStateMap); return value; } -VehicleComponentStateExpression::VehicleComponentStateExpression(const std::string& component) : component(component) -{ - -} - -ComponentState VehicleComponentStateExpression::Get(const std::map<std::string, std::pair<ComponentType, ComponentState>> &componentNameToComponentTypeAndStateMap) const +ComponentState VehicleComponentStateExpression::Get(const StateMapping &componentNameToComponentTypeAndStateMap) const { try { auto componentInformation = componentNameToComponentTypeAndStateMap.at(component); return componentInformation.second; } - catch (const std::out_of_range& e) + catch ([[maybe_unused]] const std::out_of_range & e) { - Q_UNUSED(e); return ComponentState::Undefined; } } - -ComponentStateEquality::ComponentStateEquality(std::unique_ptr<ComponentStateExpression> expression1, std::unique_ptr<ComponentStateExpression> expression2) -{ - this->expression1 = std::move(expression1); - this->expression2 = std::move(expression2); -} - -bool ComponentStateEquality::IsFullfilled(const std::map<std::string, std::pair<ComponentType, ComponentState>> &componentNameToComponentTypeAndStateMap) const +bool ComponentStateEquality::IsFullfilled(const StateMapping &componentNameToComponentTypeAndStateMap) const { return expression1->Get(componentNameToComponentTypeAndStateMap) == expression2->Get(componentNameToComponentTypeAndStateMap); } diff --git a/OpenPass_Source_Code/openPASS/Components/ComponentController/condition.h b/OpenPass_Source_Code/openPASS/Components/ComponentController/condition.h index 48b21dc4f794a09ad48a1a310ff262035e8ef656..8f14b3bc8f6479b49b1a59962bdfbb344dca40a9 100644 --- a/OpenPass_Source_Code/openPASS/Components/ComponentController/condition.h +++ b/OpenPass_Source_Code/openPASS/Components/ComponentController/condition.h @@ -9,15 +9,16 @@ *******************************************************************************/ #pragma once -#include <QtGlobal> #include <memory> +#include "Common/globalDefinitions.h" #include "Interfaces/signalInterface.h" #include "componentControllerCommon.h" -#include "Common/globalDefinitions.h" namespace ComponentControl { +using StateMapping = std::map<std::string, std::pair<ComponentType, ComponentState>>; + /*! * \brief This class represents a Condition based on all the information the ComponentController has gathered. * @@ -34,7 +35,7 @@ public: * \brief Returns wether this Condition is fullfilled. * \param componentNameToComponentTypeAndStatesMap Information the ComponentController has gathered */ - virtual bool IsFullfilled(const std::map<std::string, std::pair<ComponentType, ComponentState>> &componentNameToComponentTypeAndStatesMap) const = 0; + virtual bool IsFullfilled(const StateMapping &componentNameToComponentTypeAndStatesMap) const = 0; }; /*! @@ -54,7 +55,7 @@ public: * \param componentNameToComponentTypeAndStatesMap Information the ComponentController has gathered * \return ComponentState this expression evaluates to */ - virtual ComponentState Get(const std::map<std::string, std::pair<ComponentType, ComponentState>> &componentNameToComponentTypeAndStateMap) const = 0; + virtual ComponentState Get(const StateMapping &componentNameToComponentTypeAndStateMap) const = 0; }; /*! @@ -67,9 +68,12 @@ public: /*! * \param value The fixed ComponentState */ - FixedComponentStateExpression(ComponentState value); + FixedComponentStateExpression(ComponentState value) : + value(value) + { + } - ComponentState Get(const std::map<std::string, std::pair<ComponentType, ComponentState>> &componentNameToComponentTypeAndStateMap) const override; + ComponentState Get(const StateMapping &componentNameToComponentTypeAndStateMap) const override; private: ComponentState value; @@ -85,9 +89,12 @@ public: /*! * \param component Name of the component of which the state is evaluated */ - VehicleComponentStateExpression(const std::string& component); + VehicleComponentStateExpression(const std::string &component) : + component(component) + { + } - ComponentState Get(const std::map<std::string, std::pair<ComponentType, ComponentState>> &componentNameToComponentTypeAndStateMap) const override; + ComponentState Get(const StateMapping &componentNameToComponentTypeAndStateMap) const override; private: const std::string component; @@ -103,9 +110,13 @@ private: class ComponentStateEquality : public Condition { public: - ComponentStateEquality(std::unique_ptr<ComponentStateExpression> expression1, std::unique_ptr<ComponentStateExpression> expression2); + ComponentStateEquality(std::unique_ptr<ComponentStateExpression> expression1, std::unique_ptr<ComponentStateExpression> expression2) + { + this->expression1 = std::move(expression1); + this->expression2 = std::move(expression2); + } - bool IsFullfilled(const std::map<std::string, std::pair<ComponentType, ComponentState>> &componentNameToComponentTypeAndStateMap) const override; + bool IsFullfilled(const StateMapping &componentNameToComponentTypeAndStateMap) const override; private: std::unique_ptr<ComponentStateExpression> expression1; diff --git a/OpenPass_Source_Code/openPASS/Components/ComponentController/stateManager.cpp b/OpenPass_Source_Code/openPASS/Components/ComponentController/stateManager.cpp index cb3a17c98cdbf446c092f0636fcc13153119972e..9fcf4e2b69fb172627e6752735491c26da08e157 100644 --- a/OpenPass_Source_Code/openPASS/Components/ComponentController/stateManager.cpp +++ b/OpenPass_Source_Code/openPASS/Components/ComponentController/stateManager.cpp @@ -102,18 +102,18 @@ void StateManager::FlagComponentMaxReachableStateSetByEvent(const int localLinkI void StateManager::UpdateMaxReachableStatesForRegisteredComponents(const std::list<std::shared_ptr<ComponentChangeEvent const>>& componentStateChangeEventListFilteredByAgent) { - for (const auto stateChangeEvent : componentStateChangeEventListFilteredByAgent) + for (const auto& stateChangeEvent : componentStateChangeEventListFilteredByAgent) { try { const auto localLinkId = GetComponentLocalLinkIdByName(stateChangeEvent->GetComponentName()); - UpdateComponentMaxReachableState(localLinkId, ComponentStateMapping.at(stateChangeEvent->GetGoalStateName())); + UpdateComponentMaxReachableState(localLinkId, stateChangeEvent->GetGoalState()); FlagComponentMaxReachableStateSetByEvent(localLinkId); } catch (const std::out_of_range& error) { const std::string errorMessage = error.what(); - const std::string warning = errorMessage + "The event will be ignored."; + const std::string warning = errorMessage + " The event will be ignored."; LOG(CbkLogLevel::Warning, warning); } } @@ -155,15 +155,15 @@ bool StateManager::LocalLinkIdIsRegistered(const int localLinkId) const return (vehicleComponentStateInformations.find(localLinkId) != vehicleComponentStateInformations.end()); } -std::map<std::string, std::pair<ComponentType, ComponentState>> - StateManager::GetVehicleComponentNamesToTypeAndStateMap() +std::map<std::string, std::pair<ComponentType, ComponentState>> StateManager::GetVehicleComponentNamesToTypeAndStateMap() { std::map<std::string, std::pair<ComponentType, ComponentState>> vehicleComponentStates; - for (const auto& vehicleComponentStateInformationIterator : vehicleComponentStateInformations) + for (const auto &vehicleComponentStateInformationIterator : vehicleComponentStateInformations) { - const auto& vehicleComponentStateInformation = vehicleComponentStateInformationIterator.second; - vehicleComponentStates.insert({ vehicleComponentStateInformation->GetComponentName(), { vehicleComponentStateInformation->GetComponentType(), vehicleComponentStateInformation->GetCurrentState() } }); + const auto &vehicleComponentStateInformation = vehicleComponentStateInformationIterator.second; + vehicleComponentStates.insert({vehicleComponentStateInformation->GetComponentName(), + {vehicleComponentStateInformation->GetComponentType(), vehicleComponentStateInformation->GetCurrentState()}}); } return vehicleComponentStates; diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collision.cpp b/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collision.cpp index 6dae3a642c8eca2e48e73704ea15ca3b476698d1..920d738a946eb0d1f98b7a57e9fdb3cb7a929364 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collision.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collision.cpp @@ -34,7 +34,7 @@ extern "C" DYNAMICS_COLLISION_SHARED_EXPORT ModelInterface *OpenPASS_CreateInsta StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -52,7 +52,7 @@ extern "C" DYNAMICS_COLLISION_SHARED_EXPORT ModelInterface *OpenPASS_CreateInsta stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collisionImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collisionImplementation.cpp index d8e442e549a8538a9874aaaa0afe1eade85217b8..ec973db80c344d9061dd704b7fcd46513738b7cc 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collisionImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collisionImplementation.cpp @@ -29,7 +29,7 @@ DynamicsCollisionImplementation::DynamicsCollisionImplementation(std::string com StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : UnrestrictedModelInterface { componentName, @@ -41,7 +41,7 @@ DynamicsCollisionImplementation::DynamicsCollisionImplementation(std::string com stochastics, world, parameters, - observations, + publisher, callbacks, agent }, dynamicsSignal{} diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collisionImplementation.h b/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collisionImplementation.h index 6d02000941cdb351c36c9be3ab5eccc1e7cce9af..54a8cf7ca2c0b5d1b5533285b22802192f1e54b6 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collisionImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_Collision/dynamics_collisionImplementation.h @@ -56,7 +56,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); DynamicsCollisionImplementation(const DynamicsCollisionImplementation&) = delete; diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_Longitudinal_Basic/dynamics_longitudinal_basic.cpp b/OpenPass_Source_Code/openPASS/Components/Dynamics_Longitudinal_Basic/dynamics_longitudinal_basic.cpp index b1a14c7398226cc61fc9a153d3a1f72d281cd1f5..ca43b8fbd1ad51abf111103270fac3d28ef6506a 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_Longitudinal_Basic/dynamics_longitudinal_basic.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_Longitudinal_Basic/dynamics_longitudinal_basic.cpp @@ -35,7 +35,7 @@ extern "C" DYNAMICS_LONGITUDINAL_BASICSHARED_EXPORT ModelInterface *OpenPASS_Cre StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -53,7 +53,7 @@ extern "C" DYNAMICS_LONGITUDINAL_BASICSHARED_EXPORT ModelInterface *OpenPASS_Cre stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_Longitudinal_Basic/dynamics_longitudinal_basic_implementation.h b/OpenPass_Source_Code/openPASS/Components/Dynamics_Longitudinal_Basic/dynamics_longitudinal_basic_implementation.h index 8466cbd463a404e19a1376fe113271aabde75369..cb7d74d3fa3b32c69d1a45d063bcf2a06c80e146 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_Longitudinal_Basic/dynamics_longitudinal_basic_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_Longitudinal_Basic/dynamics_longitudinal_basic_implementation.h @@ -13,7 +13,6 @@ #define DYNAMICS_LONGITUDINAL_BASIC_IMPLEMENTATION_H #include "modelInterface.h" -#include "observationInterface.h" #include "primitiveSignals.h" //----------------------------------------------------------------------------- @@ -83,7 +82,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : DynamicsInterface( @@ -96,7 +95,7 @@ public: stochastics, world, parameters, - observations, + publisher, callbacks, agent) {} diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDriving.cpp b/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDriving.cpp index f130782c71e42af7d6e9efe30ef9fb06dfce65be..0e010040531d5e475b92a2d37e9f6cd303ca7f02 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDriving.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDriving.cpp @@ -35,7 +35,7 @@ extern "C" DYNAMICS_REGULAR_DRIVING_SHARED_EXPORT ModelInterface *OpenPASS_Creat StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -53,7 +53,7 @@ extern "C" DYNAMICS_REGULAR_DRIVING_SHARED_EXPORT ModelInterface *OpenPASS_Creat stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDrivingImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDrivingImplementation.cpp index 6ed853d084e9e1bc3ca91fb5dab541c0804682e8..a293db7d4cf24b9c7b49e0df60863de7f8acad61 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDrivingImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDrivingImplementation.cpp @@ -238,7 +238,7 @@ double DynamicsRegularDrivingImplementation::GetAccVehicle(double accPedalPos, d else // Gas { double engineMoment = GetEngineMoment(accPedalPos, gear); - observation->Insert(time, GetAgent()->GetId(), LoggingGroup::Vehicle, "EngineMoment", std::to_string(engineMoment)); + GetPublisher()->Publish("EngineMoment", engineMoment); resultAcc = GetAccFromEngineMoment(xVel, engineMoment, gear, GetCycleTime()); } @@ -291,7 +291,7 @@ void DynamicsRegularDrivingImplementation::Trigger(int time) // convert steering wheel angle to steering angle of front wheels [degree] double steering_angle_degrees = TrafficHelperFunctions::ValueInBounds(-vehicleModelParameters.maximumSteeringWheelAngleAmplitude, in_steeringWheelAngle, vehicleModelParameters.maximumSteeringWheelAngleAmplitude) / vehicleModelParameters.steeringRatio; dynamicsSignal.steeringWheelAngle = TrafficHelperFunctions::ValueInBounds(-vehicleModelParameters.maximumSteeringWheelAngleAmplitude, in_steeringWheelAngle, vehicleModelParameters.maximumSteeringWheelAngleAmplitude); - observation->Insert(time, GetAgent()->GetId(), LoggingGroup::Vehicle, "SteeringAngle", std::to_string(steering_angle_degrees)); + GetPublisher()->Publish("SteeringAngle", steering_angle_degrees); // calculate curvature (Ackermann model; reference point of yawing = rear axle!) [radiant] double steeringCurvature = std::tan(DegreeToRadiant * steering_angle_degrees) / vehicleModelParameters.wheelbase; // change of yaw angle due to ds and curvature [radiant] diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDrivingImplementation.h b/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDrivingImplementation.h index 3021fc748919bd216cf757fac201fb38071fb4cd..8634fb5d80976ec4a07fef087e65294af39f3e2d 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDrivingImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_RegularDriving/dynamics_regularDrivingImplementation.h @@ -116,7 +116,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : DynamicsInterface( @@ -129,20 +129,16 @@ public: stochastics, world, parameters, - observations, + publisher, callbacks, agent), dynamicsSignal {ComponentState::Acting} { - try + if (GetPublisher() == nullptr) { - this->observation = observations->at(0); - } - catch (const std::out_of_range&) - { - std::string msg = "DynamicsRegularDriving requires an Observer"; + std::string msg = "DynamicsRegularDriving requires a publisher"; LOG(CbkLogLevel::Error, msg); - throw std::out_of_range(msg); + throw std::runtime_error(msg); } } DynamicsRegularDrivingImplementation(const DynamicsRegularDrivingImplementation&) = delete; @@ -271,9 +267,6 @@ private: * @{ */ - //! pointer to observation at observations map element 0 - ObservationInterface* observation; - //! The minimal velocity of the agent [m/s]. const double VLowerLimit = 0; diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/dynamics_trajectoryFollower.cpp b/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/dynamics_trajectoryFollower.cpp index d318208699ca5d6fe5219030972575e8f7172d83..673bf32a9b0628a14399469b9f0a0dcb3579fbd6 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/dynamics_trajectoryFollower.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/dynamics_trajectoryFollower.cpp @@ -12,55 +12,54 @@ /** \file dynamics_trajectoryFollower.cpp */ //----------------------------------------------------------------------------- +#include "dynamics_trajectoryFollower.h" + #include <QCoreApplication> #include "Interfaces/parameterInterface.h" -#include "dynamics_trajectoryFollower.h" #include "trajectoryFollowerImplementation.h" -const std::string Version = "0.1.0"; -static const CallbackInterface* Callbacks = nullptr; +const static std::string VERSION = "0.2.0"; +static const CallbackInterface *Callbacks = nullptr; -extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT const std::string& OpenPASS_GetVersion() +extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT const std::string &OpenPASS_GetVersion() { - return Version; + return VERSION; } -extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT ModelInterface* OpenPASS_CreateInstance( +extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( std::string componentName, bool isInit, int priority, int offsetTime, int responseTime, int cycleTime, - StochasticsInterface* stochastics, - WorldInterface* world, - const ParameterInterface* parameters, - const std::map<int, ObservationInterface*>* observations, - AgentInterface* agent, - const CallbackInterface* callbacks, - SimulationSlave::EventNetworkInterface * const eventNetwork) + StochasticsInterface *stochastics, + WorldInterface *world, + const ParameterInterface *parameters, + PublisherInterface * const publisher, + AgentInterface *agent, + const CallbackInterface *callbacks) { Callbacks = callbacks; try { - return (ModelInterface*)(new (std::nothrow) TrajectoryFollowerImplementation( - componentName, - isInit, - priority, - offsetTime, - responseTime, - cycleTime, - stochastics, - world, - parameters, - observations, - callbacks, - agent, - eventNetwork)); + return (ModelInterface *)(new (std::nothrow) TrajectoryFollowerImplementation( + componentName, + isInit, + priority, + offsetTime, + responseTime, + cycleTime, + stochastics, + world, + parameters, + publisher, + callbacks, + agent)); } - catch (const std::runtime_error& ex) + catch (const std::runtime_error &ex) { if (Callbacks != nullptr) { @@ -80,22 +79,22 @@ extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT ModelInterface* OpenPASS_C } } -extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT void OpenPASS_DestroyInstance(ModelInterface* implementation) +extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT void OpenPASS_DestroyInstance(ModelInterface *implementation) { delete implementation; } extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT bool OpenPASS_UpdateInput( - ModelInterface* implementation, + ModelInterface *implementation, int localLinkId, - const std::shared_ptr<SignalInterface const>& data, + const std::shared_ptr<SignalInterface const> &data, int time) { try { implementation->UpdateInput(localLinkId, data, time); } - catch (const std::runtime_error& ex) + catch (const std::runtime_error &ex) { if (Callbacks != nullptr) { @@ -118,16 +117,16 @@ extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT bool OpenPASS_UpdateInput( } extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT bool OpenPASS_UpdateOutput( - ModelInterface* implementation, + ModelInterface *implementation, int localLinkId, - std::shared_ptr<SignalInterface const>& data, + std::shared_ptr<SignalInterface const> &data, int time) { try { implementation->UpdateOutput(localLinkId, data, time); } - catch (const std::runtime_error& ex) + catch (const std::runtime_error &ex) { if (Callbacks != nullptr) { @@ -150,14 +149,14 @@ extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT bool OpenPASS_UpdateOutput } extern "C" DYNAMICS_TRAJECTORY_FOLLOWER_SHARED_EXPORT bool OpenPASS_Trigger( - ModelInterface* implementation, + ModelInterface *implementation, int time) { try { implementation->Trigger(time); } - catch (const std::runtime_error& ex) + catch (const std::runtime_error &ex) { if (Callbacks != nullptr) { diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/trajectoryFollowerImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/trajectoryFollowerImplementation.cpp index 256053e51811819c1ded35cf85a244cedf5511e6..4355c6b575fad6a4402c923e622a7c1d36e2bdbd 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/trajectoryFollowerImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/trajectoryFollowerImplementation.cpp @@ -12,30 +12,30 @@ /** \file trajectoryFollowerImplementation.cpp */ //----------------------------------------------------------------------------- +#include "trajectoryFollowerImplementation.h" + #include <memory> -#include <qglobal.h> -#include "trajectoryFollowerImplementation.h" +#include <qglobal.h> -#include "Interfaces/parameterInterface.h" -#include "Interfaces/observationInterface.h" #include "Common/componentStateChangeEvent.h" #include "Common/trajectorySignal.h" +#include "Interfaces/parameterInterface.h" +#include "Interfaces/publisherInterface.h" TrajectoryFollowerImplementation::TrajectoryFollowerImplementation(std::string componentName, - bool isInit, - int priority, - int offsetTime, - int responseTime, - int cycleTime, - StochasticsInterface* stochastics, - WorldInterface* world, - const ParameterInterface* parameters, - const std::map<int, ObservationInterface*>* observations, - const CallbackInterface* callbacks, - AgentInterface* agent, - SimulationSlave::EventNetworkInterface * const eventNetwork) : - UnrestrictedEventModelInterface( + bool isInit, + int priority, + int offsetTime, + int responseTime, + int cycleTime, + StochasticsInterface *stochastics, + WorldInterface *world, + const ParameterInterface *parameters, + PublisherInterface * const publisher, + const CallbackInterface *callbacks, + AgentInterface *agent) : + UnrestrictedModelInterface( componentName, isInit, priority, @@ -45,10 +45,9 @@ TrajectoryFollowerImplementation::TrajectoryFollowerImplementation(std::string c stochastics, world, parameters, - observations, + publisher, callbacks, - agent, - eventNetwork), + agent), cycleTimeInSeconds{static_cast<double>(cycleTime) / 1000.0} { dynamicsOutputSignal.positionX = 0; @@ -58,7 +57,7 @@ TrajectoryFollowerImplementation::TrajectoryFollowerImplementation(std::string c ParseParameters(parameters); } -void TrajectoryFollowerImplementation::ParseParameters(const ParameterInterface* parameters) +void TrajectoryFollowerImplementation::ParseParameters(const ParameterInterface *parameters) { try { @@ -66,15 +65,15 @@ void TrajectoryFollowerImplementation::ParseParameters(const ParameterInterface* enforceTrajectory = boolParameters.at("EnforceTrajectory"); automaticDeactivation = boolParameters.at("AutomaticDeactivation"); } - catch (const std::out_of_range& error) + catch (const std::out_of_range &error) { LOG(CbkLogLevel::Error, error.what()); throw std::runtime_error(error.what()); } } -void TrajectoryFollowerImplementation::UpdateInput(int localLinkId, const std::shared_ptr<SignalInterface const>& data, - int time) +void TrajectoryFollowerImplementation::UpdateInput(int localLinkId, const std::shared_ptr<SignalInterface const> &data, + int time) { Q_UNUSED(time); @@ -105,7 +104,7 @@ void TrajectoryFollowerImplementation::UpdateInput(int localLinkId, const std::s if (!enforceTrajectory) { const std::shared_ptr<ComponentStateSignalInterface const> stateSignal = - std::dynamic_pointer_cast<ComponentStateSignalInterface const>(data); + std::dynamic_pointer_cast<ComponentStateSignalInterface const>(data); if (stateSignal != nullptr && stateSignal->componentState == ComponentState::Acting) { const std::shared_ptr<AccelerationSignal const> signal = std::dynamic_pointer_cast<AccelerationSignal const>(data); @@ -136,13 +135,13 @@ void TrajectoryFollowerImplementation::UpdateInput(int localLinkId, const std::s } else { - const std::string msg = COMPONENTNAME + " invalid signaltype"; + const std::string msg = std::string(COMPONENTNAME) + " invalid signaltype"; LOG(CbkLogLevel::Error, msg); throw std::runtime_error(msg); } } -void TrajectoryFollowerImplementation::UpdateOutput(int localLinkId, std::shared_ptr<SignalInterface const>& data, int time) +void TrajectoryFollowerImplementation::UpdateOutput(int localLinkId, std::shared_ptr<SignalInterface const> &data, int time) { Q_UNUSED(time); @@ -153,14 +152,14 @@ void TrajectoryFollowerImplementation::UpdateOutput(int localLinkId, std::shared dynamicsOutputSignal.componentState = componentState; data = std::make_shared<DynamicsSignal const>(dynamicsOutputSignal); } - catch (const std::bad_alloc&) + catch (const std::bad_alloc &) { ThrowCouldNotInstantiateSignalError(); } } else { - const std::string msg = COMPONENTNAME + " invalid link"; + const std::string msg = std::string(COMPONENTNAME) + " invalid link"; LOG(CbkLogLevel::Debug, msg); throw std::runtime_error(msg); } @@ -176,6 +175,12 @@ ComponentState TrajectoryFollowerImplementation::GetState() const return componentState; } +void TrajectoryFollowerImplementation::SetComponentState(const ComponentState newState) +{ + componentState = newState; + GetPublisher()->Publish(COMPONENTNAME, ComponentEvent({{"ComponentState", openpass::utils::to_string(componentState)}})); +} + void TrajectoryFollowerImplementation::UpdateState(const ComponentState newState) { // only update state if the newstate differs from the current state @@ -185,25 +190,13 @@ void TrajectoryFollowerImplementation::UpdateState(const ComponentState newState { if (canBeActivated) { - componentState = newState; - std::shared_ptr<VehicleComponentEvent> event = std::make_shared<VehicleComponentEvent>(currentTime, - "TrajectoryFollowerActivated", - GetComponentName(), - GetAgent()->GetId()); - - GetObservations()->at(0)->InsertEvent(event); + SetComponentState(newState); } } else if (newState == ComponentState::Disabled) { canBeActivated = false; - componentState = newState; - std::shared_ptr<VehicleComponentEvent> event = std::make_shared<VehicleComponentEvent>(currentTime, - "TrajectoryFollowerDeactivated", - GetComponentName(), - GetAgent()->GetId()); - - GetObservations()->at(0)->InsertEvent(event); + SetComponentState(newState); } else { @@ -212,16 +205,16 @@ void TrajectoryFollowerImplementation::UpdateState(const ComponentState newState } } -[[ noreturn ]] void TrajectoryFollowerImplementation::ThrowCouldNotInstantiateSignalError() +[[noreturn]] void TrajectoryFollowerImplementation::ThrowCouldNotInstantiateSignalError() { - const std::string msg = COMPONENTNAME + " could not instantiate signal"; + const std::string msg = std::string(COMPONENTNAME) + " could not instantiate signal"; LOG(CbkLogLevel::Debug, msg); throw std::runtime_error(msg); } -[[ noreturn ]] void TrajectoryFollowerImplementation::ThrowInvalidSignalTypeError() +[[noreturn]] void TrajectoryFollowerImplementation::ThrowInvalidSignalTypeError() { - const std::string msg = COMPONENTNAME + " invalid signaltype"; + const std::string msg = std::string(COMPONENTNAME) + " invalid signaltype"; LOG(CbkLogLevel::Debug, msg); throw std::runtime_error(msg); } @@ -233,7 +226,7 @@ void TrajectoryFollowerImplementation::HandleEndOfTrajectory() dynamicsOutputSignal.travelDistance = 0; dynamicsOutputSignal.yawRate = 0; - if(automaticDeactivation) + if (automaticDeactivation) { UpdateState(ComponentState::Disabled); } @@ -266,7 +259,7 @@ void TrajectoryFollowerImplementation::TriggerWithActiveAccelerationInput() previousPosition = *previousTrajectoryIterator; - if(nextTrajectoryIterator != trajectory.points.end()) + if (nextTrajectoryIterator != trajectory.points.end()) { nextPosition = *nextTrajectoryIterator; } @@ -296,7 +289,7 @@ void TrajectoryFollowerImplementation::TriggerWithInactiveAccelerationInput() double remainingTime = cycleTimeInSeconds; double timeBetweenCoordinates = nextCoordinate.time - previousTimestamp; - double deltaS {0}; + double deltaS{0}; while (timeBetweenCoordinates <= remainingTime && nextTrajectoryIterator != trajectory.points.end()) @@ -322,8 +315,8 @@ void TrajectoryFollowerImplementation::TriggerWithInactiveAccelerationInput() } } - const auto& previousPosition = previousCoordinate; - const auto& nextPosition = nextCoordinate; + const auto &previousPosition = previousCoordinate; + const auto &nextPosition = nextCoordinate; percentageTraveledBetweenCoordinates = remainingTime / timeBetweenCoordinates; Common::Vector2d direction = CalculateScaledVector(previousPosition, nextPosition, percentageTraveledBetweenCoordinates); @@ -352,11 +345,11 @@ void TrajectoryFollowerImplementation::CalculateNextTimestep(int time) lastVelocity = dynamicsOutputSignal.velocity; if (previousTrajectoryIterator != trajectory.points.end() && - nextTrajectoryIterator != trajectory.points.end()) + nextTrajectoryIterator != trajectory.points.end()) { if (initialization) { - UpdateDynamics(*previousTrajectoryIterator, {0,0}, 0, 0, 0); + UpdateDynamics(*previousTrajectoryIterator, {0, 0}, 0, 0, 0); lastCoordinateTimestamp = previousTrajectoryIterator->time; initialization = false; return; @@ -379,7 +372,7 @@ void TrajectoryFollowerImplementation::CalculateNextTimestep(int time) Common::Vector2d TrajectoryFollowerImplementation::CalculateScaledVector(const TrajectoryPoint &previousPosition, const TrajectoryPoint &nextPosition, const double &factor) { - Common::Vector2d result (nextPosition.x - previousPosition.x, nextPosition.y - previousPosition.y); + Common::Vector2d result(nextPosition.x - previousPosition.x, nextPosition.y - previousPosition.y); result.Scale(factor); return result; @@ -387,10 +380,10 @@ Common::Vector2d TrajectoryFollowerImplementation::CalculateScaledVector(const T double TrajectoryFollowerImplementation::CalculateScaledDeltaYawAngle(const TrajectoryPoint &previousPosition, const TrajectoryPoint &nextPosition, const double &factor) { - return (nextPosition.yaw - previousPosition.yaw) * factor;; + return (nextPosition.yaw - previousPosition.yaw) * factor; + ; } - TrajectoryPoint TrajectoryFollowerImplementation::CalculateStartPosition(const TrajectoryPoint &previousPosition, const TrajectoryPoint &nextPosition) { const auto startDirection = CalculateScaledVector(previousPosition, nextPosition, percentageTraveledBetweenCoordinates); diff --git a/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/trajectoryFollowerImplementation.h b/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/trajectoryFollowerImplementation.h index 3af720cd933b875054bb80f949f1dbe56dc343b0..80b403955703034e3cc51ff084ba67ad46787430 100644 --- a/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/trajectoryFollowerImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Dynamics_TrajectoryFollower/trajectoryFollowerImplementation.h @@ -54,16 +54,16 @@ #pragma once -#include "Interfaces/modelInterface.h" -#include "Interfaces/eventNetworkInterface.h" -#include "Common/openScenarioDefinitions.h" - -#include "Common/vector2d.h" #include "Common/accelerationSignal.h" -#include "Common/vehicleComponentEvent.h" #include "Common/dynamicsSignal.h" #include "Common/globalDefinitions.h" #include "Common/lateralSignal.h" +#include "Common/openScenarioDefinitions.h" +#include "Common/vector2d.h" +#include "Common/vehicleComponentEvent.h" +#include "Interfaces/eventNetworkInterface.h" +#include "Interfaces/modelInterface.h" +#include "Interfaces/publisherInterface.h" using openScenario::Trajectory; using openScenario::TrajectoryPoint; @@ -73,10 +73,10 @@ using openScenario::TrajectoryPoint; * * \ingroup Dynamics_TrajectoryFollower */ -class TrajectoryFollowerImplementation : public UnrestrictedEventModelInterface +class TrajectoryFollowerImplementation : public UnrestrictedModelInterface { public: - const std::string COMPONENTNAME = "Dynamics_TrajectoryFollower"; + static constexpr char COMPONENTNAME[] = "Dynamics_TrajectoryFollower"; TrajectoryFollowerImplementation(std::string componentName, bool isInit, @@ -87,16 +87,9 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, - AgentInterface *agent, - SimulationSlave::EventNetworkInterface * const eventNetwork); - - TrajectoryFollowerImplementation(const TrajectoryFollowerImplementation&) = delete; - TrajectoryFollowerImplementation(TrajectoryFollowerImplementation&&) = delete; - TrajectoryFollowerImplementation& operator=(const TrajectoryFollowerImplementation&) = delete; - TrajectoryFollowerImplementation& operator=(TrajectoryFollowerImplementation&&) = delete; - virtual ~TrajectoryFollowerImplementation() = default; + AgentInterface *agent); /*! * \brief Update Inputs @@ -144,32 +137,33 @@ public: void CalculateNextTimestep(int time); private: - bool initialization {true}; + const double cycleTimeInSeconds{0.0}; + + bool initialization{true}; bool enforceTrajectory{false}; bool automaticDeactivation{false}; - bool inputAccelerationActive {false}; + bool inputAccelerationActive{false}; int currentTime{0}; - double inputAcceleration {0.0}; - const double cycleTimeInSeconds {0.0}; + double inputAcceleration{0.0}; DynamicsSignal dynamicsOutputSignal{}; Trajectory trajectory{}; - std::vector<TrajectoryPoint>::iterator previousTrajectoryIterator {}; - std::vector<TrajectoryPoint>::iterator nextTrajectoryIterator {}; + std::vector<TrajectoryPoint>::iterator previousTrajectoryIterator{}; + std::vector<TrajectoryPoint>::iterator nextTrajectoryIterator{}; - double lastCoordinateTimestamp {0}; - double lastVelocity {0.0}; + double lastCoordinateTimestamp{0}; + double lastVelocity{0.0}; TrajectoryPoint lastWorldPosition; - double percentageTraveledBetweenCoordinates {0}; + double percentageTraveledBetweenCoordinates{0}; - ComponentState componentState {ComponentState::Disabled}; + ComponentState componentState{ComponentState::Disabled}; bool canBeActivated{true}; - [[ noreturn ]] void ThrowCouldNotInstantiateSignalError(); - [[ noreturn ]] void ThrowInvalidSignalTypeError(); + [[noreturn]] void ThrowCouldNotInstantiateSignalError(); + [[noreturn]] void ThrowInvalidSignalTypeError(); ComponentState GetState() const; void UpdateState(const ComponentState newState); @@ -188,6 +182,8 @@ private: void TriggerWithActiveAccelerationInput(); void TriggerWithInactiveAccelerationInput(); + void SetComponentState(const ComponentState newState); + void UpdateDynamics(const TrajectoryPoint &previousPosition, const Common::Vector2d &direction, double deltaYawAngle, diff --git a/OpenPass_Source_Code/openPASS/Components/LimiterAccelerationVehicleComponents/limiterAccelerationVehicleComponents.cpp b/OpenPass_Source_Code/openPASS/Components/LimiterAccelerationVehicleComponents/limiterAccelerationVehicleComponents.cpp index cba91924d33006321b8f5b578f5b151a64b4e945..3fe78be7fb04804590d5e7b5bd36b6e4d932f9b8 100644 --- a/OpenPass_Source_Code/openPASS/Components/LimiterAccelerationVehicleComponents/limiterAccelerationVehicleComponents.cpp +++ b/OpenPass_Source_Code/openPASS/Components/LimiterAccelerationVehicleComponents/limiterAccelerationVehicleComponents.cpp @@ -33,7 +33,7 @@ extern "C" LIMITER_ACCELERATION_VEHICLE_COMPONENTS_SHARED_EXPORT ModelInterface StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -51,7 +51,7 @@ extern "C" LIMITER_ACCELERATION_VEHICLE_COMPONENTS_SHARED_EXPORT ModelInterface stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/LimiterAccelerationVehicleComponents/limiterAccelerationVehicleComponentsImplementation.h b/OpenPass_Source_Code/openPASS/Components/LimiterAccelerationVehicleComponents/limiterAccelerationVehicleComponentsImplementation.h index e085c3e841f80452956950289fd6196daa5a6301..430a20d753bff15cce984991c55f5432bbb0f2e5 100644 --- a/OpenPass_Source_Code/openPASS/Components/LimiterAccelerationVehicleComponents/limiterAccelerationVehicleComponentsImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/LimiterAccelerationVehicleComponents/limiterAccelerationVehicleComponentsImplementation.h @@ -42,7 +42,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : UnrestrictedModelInterface( @@ -55,7 +55,7 @@ public: stochastics, world, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActions.cpp b/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActions.cpp index f46c02ba77d1a2adba254abc7e13dcb2a5913e0f..ce3468091133bf8925750a80dc1bedd89d2ed740 100644 --- a/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActions.cpp +++ b/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActions.cpp @@ -33,7 +33,7 @@ extern "C" OPENSCENARIO_ACTIONS_SHARED_EXPORT ModelInterface *OpenPASS_CreateIns StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks, SimulationSlave::EventNetworkInterface * const eventNetwork) @@ -52,7 +52,7 @@ extern "C" OPENSCENARIO_ACTIONS_SHARED_EXPORT ModelInterface *OpenPASS_CreateIns stochastics, world, parameters, - observations, + publisher, callbacks, agent, eventNetwork)); diff --git a/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActionsImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActionsImplementation.cpp index 1ae66facfc4434f5f39ce5d5fd3464deed9b49d6..a04becd27c898c66994ed0b3df82d5292bf20dc4 100644 --- a/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActionsImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActionsImplementation.cpp @@ -31,7 +31,7 @@ OpenScenarioActionsImplementation::OpenScenarioActionsImplementation(std::string StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent, SimulationSlave::EventNetworkInterface* const eventNetwork) : @@ -45,7 +45,7 @@ OpenScenarioActionsImplementation::OpenScenarioActionsImplementation(std::string stochastics, world, parameters, - observations, + publisher, callbacks, agent, eventNetwork), diff --git a/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActionsImplementation.h b/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActionsImplementation.h index 434bb50c2278b74b85ba1fd0f51e4ef8834b47a8..b4d310f8c76996e859f2acedcb0a42344d18fa67 100644 --- a/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActionsImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/OpenScenarioActions/openScenarioActionsImplementation.h @@ -37,7 +37,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent, SimulationSlave::EventNetworkInterface * const eventNetwork); diff --git a/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicle.cpp b/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicle.cpp index 9de8b0f64d2dec5d9b2b4578d755c6f7a4e08447..bbc6149148f9b39d4c8bdced33108907ba7661cb 100644 --- a/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicle.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicle.cpp @@ -37,7 +37,7 @@ extern "C" PARAMETERS_VEHICLE_SHARED_EXPORT ModelInterface *OpenPASS_CreateInsta StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -55,7 +55,7 @@ extern "C" PARAMETERS_VEHICLE_SHARED_EXPORT ModelInterface *OpenPASS_CreateInsta stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicleImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicleImplementation.cpp index 625782b968c8e973727b8899d31ce7fe55735def..42dfd6cd1dccb8eacd35f686cacb891f713de87e 100644 --- a/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicleImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicleImplementation.cpp @@ -29,7 +29,7 @@ ParametersVehicleImplementation::ParametersVehicleImplementation( StochasticsInterface* stochastics, WorldInterface* world, const ParameterInterface* parameters, - const std::map<int, ObservationInterface*>* observations, + PublisherInterface * const publisher, const CallbackInterface* callbacks, AgentInterface* agent) : SensorInterface( @@ -42,7 +42,7 @@ ParametersVehicleImplementation::ParametersVehicleImplementation( stochastics, world, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicleImplementation.h b/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicleImplementation.h index 2f50def506596acfa5201a8b3eeffa68694f41a2..0aa700b88d1874626bc70774a35c8d6185e30d80 100644 --- a/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicleImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Parameters_Vehicle/parameters_vehicleImplementation.h @@ -12,7 +12,6 @@ #pragma once #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" #include "Common/primitiveSignals.h" /** \addtogroup Parameters_Vehicle @@ -90,7 +89,7 @@ public: StochasticsInterface* stochastics, WorldInterface* world, const ParameterInterface* parameters, - const std::map<int, ObservationInterface*>* observations, + PublisherInterface * const publisher, const CallbackInterface* callbacks, AgentInterface* agent); ParametersVehicleImplementation(const ParametersVehicleImplementation&) = delete; diff --git a/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusion.cpp b/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusion.cpp index 09109b6f5ea1143e9ab59727c7b6b7a800eba207..29334eab4421eafa7707a26ebb33d65b65f6b4f4 100644 --- a/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusion.cpp +++ b/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusion.cpp @@ -33,7 +33,7 @@ extern "C" SENSOR_FUSION_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -51,7 +51,7 @@ extern "C" SENSOR_FUSION_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusionImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusionImplementation.cpp index 2df9d2a12eddf58ebdd1b061d33126bd26c5d1a5..47695bfe56f89b41104a7f1fad31af4197ed0088 100644 --- a/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusionImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusionImplementation.cpp @@ -25,7 +25,7 @@ SensorFusionImplementation::SensorFusionImplementation( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : UnrestrictedModelInterface( @@ -38,7 +38,7 @@ SensorFusionImplementation::SensorFusionImplementation( stochastics, world, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusionImplementation.h b/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusionImplementation.h index e63c7fbb5f231fc7aad98eded3704df4288892e5..2047acc65c9caddf7d6a27cf106f42416e828ed8 100644 --- a/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusionImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/SensorFusion_OSI/sensorFusionImplementation.h @@ -68,7 +68,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance.cpp b/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance.cpp index ef381607ede49d46d53a0736fd2d8453bcd579b1..62bbee1e68e5f3ba71f8dd655e11c4f59ae59993 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance.cpp @@ -34,7 +34,7 @@ extern "C" SENSOR_DISTANCE_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -51,7 +51,7 @@ extern "C" SENSOR_DISTANCE_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance_implementation.cpp b/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance_implementation.cpp index bee554bd01f707f38276578e1128245bea3ef5f8..e2a14dd5b870ee1c6946a336108616267d2d0dfa 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance_implementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance_implementation.cpp @@ -22,7 +22,7 @@ Sensor_Distance_Implementation::Sensor_Distance_Implementation(int componentId, int cycleTime, StochasticsInterface *stochastics, WorldInterface *world, - const ParameterInterface *parameters, const std::map<int, ObservationInterface *> *observations, + const ParameterInterface *parameters, PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : SensorInterface(componentId, @@ -34,7 +34,7 @@ Sensor_Distance_Implementation::Sensor_Distance_Implementation(int componentId, stochastics, world, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance_implementation.h b/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance_implementation.h index 15b0ee0852c4511b723e652ec79fa8c487dbd912..37ed33903344eb659e07da774503366c3a3735ec 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_Distance/sensor_distance_implementation.h @@ -14,7 +14,6 @@ #include <math.h> #include "modelInterface.h" -#include "observationInterface.h" /*! * \addtogroup Components_Basic openPASS components basic @@ -79,7 +78,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); virtual ~Sensor_Distance_Implementation() = default; diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driver.cpp b/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driver.cpp index 079a0d202f2f1bbcee5f6971c3f1e8682145b1a3..e78cdaf036baa935904a4955fa70ffaa132746ba 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driver.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driver.cpp @@ -34,7 +34,7 @@ extern "C" SENSOR_DRIVER_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -52,7 +52,7 @@ Callbacks = callbacks; stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driverImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driverImplementation.cpp index 841b2b149c86001bd4dd0679609242db607ed303..7474b1d2250f0ace6195232cf7f8d0a133bca9c0 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driverImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driverImplementation.cpp @@ -31,7 +31,7 @@ SensorDriverImplementation::SensorDriverImplementation( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : SensorInterface( @@ -44,7 +44,7 @@ SensorDriverImplementation::SensorDriverImplementation( stochastics, world, parameters, - observations, + publisher, callbacks, agent), egoAgent(agent->GetEgoAgent()), diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driverImplementation.h b/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driverImplementation.h index b80a4e3a37a361149f179bc09d82d69e2745a830..82bdf2ba391140110914affca9b56ead96b40263 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driverImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_Driver/sensor_driverImplementation.h @@ -14,7 +14,6 @@ #include "Signals/sensor_driverDefinitions.h" #include "Common/primitiveSignals.h" #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" #include "sensor_driverCalculations.h" /** \addtogroup Sensor_Driver @@ -38,7 +37,7 @@ * data | Referenced signal (copied by sending component) * isInit | Query whether the component was just initialized * localLinkId | Corresponds to "id" of "ComponentInput" -* observations | Interface which has to be provided by observation modules +* publisher | Publishing instance provided by the framework * offsetTime | Offset time of the component * parameters | Interface provides access to the configuration parameters * priority | Priority of the component @@ -73,7 +72,7 @@ public: //! \param [in] stochastics Provides access to the stochastics functionality of the framework //! \param [in] world Provides access to world representation //! \param [in] parameters Interface provides access to the configuration parameters - //! \param [in] observations Interface which has to be provided by observation modules + //! \param [in] pubisher Instance provided by the framework //! \param [in] callbacks Interface for callbacks to framework //! \param [in] agent This interface provides access to agent parameters, properties, attributes and dynamic states SensorDriverImplementation(std::string componentName, @@ -85,7 +84,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/objectDetectorBase.cpp b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/objectDetectorBase.cpp index 082d9774a02a03e006deda02759727d4109090fe..2c25565c0c6e9771a41cb2056669428fc2ca11f4 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/objectDetectorBase.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/objectDetectorBase.cpp @@ -31,7 +31,7 @@ ObjectDetectorBase::ObjectDetectorBase( StochasticsInterface* stochastics, WorldInterface* world, const ParameterInterface* parameters, - const std::map<int, ObservationInterface*>* observations, + PublisherInterface * const publisher, const CallbackInterface* callbacks, AgentInterface* agent) : SensorInterface( @@ -44,7 +44,7 @@ ObjectDetectorBase::ObjectDetectorBase( stochastics, world, parameters, - observations, + publisher, callbacks, agent) { @@ -62,12 +62,11 @@ ObjectDetectorBase::ObjectDetectorBase( try { - _observer = GetObservations()->at(0); - if (_observer == nullptr) { throw std::runtime_error(""); } + if (GetPublisher() == nullptr) { throw std::runtime_error(""); } } catch (...) { - const std::string msg = COMPONENTNAME + " invalid observation module setup"; + const std::string msg = COMPONENTNAME + " invalid publisher module setup"; LOG(CbkLogLevel::Error, msg); throw std::runtime_error(msg); } diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/objectDetectorBase.h b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/objectDetectorBase.h index d286f0a73112e86f870c38cd493f7dd137a023cd..0e8c9d5463da57f4c2e3b6b6e08262994acdc77f 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/objectDetectorBase.h +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/objectDetectorBase.h @@ -39,7 +39,6 @@ #pragma once #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" #include "Interfaces/profilesInterface.h" #include "Common/primitiveSignals.h" #include "Common/vector3d.h" @@ -72,7 +71,7 @@ public: StochasticsInterface* stochastics, WorldInterface* world, const ParameterInterface* parameters, - const std::map<int, ObservationInterface*>* observations, + PublisherInterface * const publisher, const CallbackInterface* callbacks, AgentInterface* agent); @@ -230,7 +229,6 @@ protected: osi3::SensorData sensorData; - ObservationInterface* _observer = nullptr; openpass::sensors::Position position; int id; double failureProbability; diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorGeometric2D.cpp b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorGeometric2D.cpp index 55e5ceeab5c299c129cef76c83923e5f64c7c955..2f51911dd8f3b596dd7be93c67a3f45d9f56d5ba 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorGeometric2D.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorGeometric2D.cpp @@ -29,7 +29,7 @@ SensorGeometric2D::SensorGeometric2D( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : ObjectDetectorBase( @@ -42,7 +42,7 @@ SensorGeometric2D::SensorGeometric2D( stochastics, world, parameters, - observations, + publisher, callbacks, agent) { @@ -119,16 +119,8 @@ void SensorGeometric2D::Observe(const int time, const SensorDetectionResults& re return object.id().value(); }); - _observer->Insert(time, - GetAgent()->GetId(), - LoggingGroup::SensorExtended, - "Sensor" + std::to_string(id) + "_VisibleAgents", - CreateAgentIdListString(visibleIds)); - _observer->Insert(time, - GetAgent()->GetId(), - LoggingGroup::SensorExtended, - "Sensor" + std::to_string(id) + "_DetectedAgents", - CreateAgentIdListString(detectedIds)); + GetPublisher()->Publish("Sensor" + std::to_string(id) + "_VisibleAgents", CreateAgentIdListString(visibleIds)); + GetPublisher()->Publish("Sensor" + std::to_string(id) + "_DetectedAgents", CreateAgentIdListString(detectedIds)); } std::string SensorGeometric2D::CreateAgentIdListString(const std::vector<OWL::Id>& owlIds) const diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorGeometric2D.h b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorGeometric2D.h index 5871b10999492df5d337a43f151bd826a3bc53f2..46330570bf8f61ea3e3b7001082c711f9de74c53 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorGeometric2D.h +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorGeometric2D.h @@ -57,7 +57,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorObjectDetectorFactory.cpp b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorObjectDetectorFactory.cpp index 74e078de9de5d77a92d1c34aac15e8ea64f89317..d252dc5e65f43bef2b9388307bf3b319aed4334a 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorObjectDetectorFactory.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_OSI/sensorObjectDetectorFactory.cpp @@ -34,7 +34,7 @@ extern "C" SENSOR_OBJECT_DETECTOR_SHARED_EXPORT ModelInterface *OpenPASS_CreateI StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -56,7 +56,7 @@ extern "C" SENSOR_OBJECT_DETECTOR_SHARED_EXPORT ModelInterface *OpenPASS_CreateI stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordState.cpp b/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordState.cpp index 6bf4ef1840f5a20c6955bd04889a9b6050e2f280..3c748aa9f07d85deed07ea04440f5e124a9ad43a 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordState.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordState.cpp @@ -34,7 +34,7 @@ extern "C" SENSOR_RECORD_STATE_SHARED_EXPORT ModelInterface *OpenPASS_CreateInst StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -52,7 +52,7 @@ Callbacks = callbacks; stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordStateImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordStateImplementation.cpp index 6c2f59cb5a8c4f4ac504a4b00130f4986c002712..526b8957313cd371478e2a4d8969b0e7ea931a34 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordStateImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordStateImplementation.cpp @@ -32,7 +32,7 @@ SensorRecordStateImplementation::SensorRecordStateImplementation( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : SensorInterface( @@ -45,27 +45,16 @@ SensorRecordStateImplementation::SensorRecordStateImplementation( stochastics, world, parameters, - observations, + publisher, callbacks, agent) { - agentId = GetAgent()->GetId(); - - try - { - observerInstance = GetObservations()->at(0); - if(observerInstance == nullptr) - { - throw std::runtime_error(""); - } - } - catch(...) + if (GetPublisher() == nullptr) { - const std::string msg = COMPONENTNAME + " invalid observation module setup"; + const std::string msg = COMPONENTNAME + " invalid publisher module setup"; LOG(CbkLogLevel::Error, msg); throw std::runtime_error(msg); } - } void SensorRecordStateImplementation::UpdateInput(int, const std::shared_ptr<SignalInterface const> &, int) @@ -76,118 +65,16 @@ void SensorRecordStateImplementation::UpdateOutput(int ,std::shared_ptr<SignalIn { } -void SensorRecordStateImplementation::Trigger(int time) -{ - timeMSec = time; - - ObserveEgo(); -} - -void SensorRecordStateImplementation::ObserveEgo() +void SensorRecordStateImplementation::Trigger([[maybe_unused]] int time) { - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Trace, - "XPosition", - std::to_string(GetAgent()->GetPositionX())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Trace, - "YPosition", - std::to_string(GetAgent()->GetPositionY())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Trace, - "YawAngle", - std::to_string(GetAgent()->GetYaw())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Visualization, - "VelocityEgo", - std::to_string(GetAgent()->GetVelocity())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Visualization, - "AccelerationEgo", - std::to_string(GetAgent()->GetAcceleration())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Visualization, - "BrakeLight", - GetAgent()->GetBrakeLight() ? "1" : "0"); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Visualization, - "IndicatorState", - std::to_string(static_cast<int>(GetAgent()->GetIndicatorState()))); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Visualization, - "LightStatus", - std::to_string(static_cast<int>(GetAgent()->GetLightState()))); - const auto& egoAgent = GetAgent()->GetEgoAgent(); + GetPublisher()->Publish("PositionRoute", egoAgent.GetMainLocatePosition().roadPosition.s); + GetPublisher()->Publish("TCoordinate", egoAgent.GetPositionLateral()); + GetPublisher()->Publish("Lane", egoAgent.GetLaneIdFromRelative(0)); + GetPublisher()->Publish("Road", egoAgent.GetRoadId()); - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::RoadPosition, - "PositionRoute", - std::to_string(egoAgent.GetMainLocatePosition().roadPosition.s)); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::RoadPosition, - "TCoordinate", - std::to_string(egoAgent.GetPositionLateral())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::RoadPosition, - "Lane", - std::to_string(egoAgent.GetLaneIdFromRelative(0))); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::RoadPosition, - "Road", - egoAgent.GetRoadId()); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::RoadPositionExtended, - "SecondaryLanes", - SecondaryLanesToString(egoAgent.GetRoadId())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Vehicle, - "YawRate", - std::to_string(GetAgent()->GetYawRate())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Vehicle, - "AccelerationPedalPosition", - std::to_string(GetAgent()->GetEffAccelPedal())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Vehicle, - "BrakePedalPosition", - std::to_string(GetAgent()->GetEffBrakePedal())); - - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::Vehicle, - "Gear", - std::to_string(GetAgent()->GetGear())); + const auto& secondaryLanes = GetAgent()->GetObjectPosition().touchedRoads.at(egoAgent.GetRoadId()).lanes; + GetPublisher()->Publish("SecondaryLanes", secondaryLanes); int frontAgentId = -1; const auto frontAgents = egoAgent.GetAgentsInRange(0, std::numeric_limits<double>::max(), 0); @@ -197,25 +84,5 @@ void SensorRecordStateImplementation::ObserveEgo() frontAgentId = frontAgents.front()->GetId(); } - observerInstance->Insert(timeMSec, - agentId, - LoggingGroup::RoadPosition, - "AgentInFront", - std::to_string(frontAgentId)); -} - -std::string SensorRecordStateImplementation::SecondaryLanesToString(const std::string& roadId) -{ - const auto secondaryList = GetAgent()->GetObjectPosition().touchedRoads.at(roadId).lanes; - std::string listOfSecondaryLanes{""}; - for (auto objectIt = secondaryList.cbegin(); objectIt != secondaryList.cend(); objectIt++) - { - listOfSecondaryLanes += std::to_string(*objectIt); - - if (std::next(objectIt) != secondaryList.cend()) - { - listOfSecondaryLanes += ";"; - } - } - return listOfSecondaryLanes; + GetPublisher()->Publish("AgentInFront", frontAgentId); } diff --git a/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordStateImplementation.h b/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordStateImplementation.h index b0bc2597ab8c6d631af00efa15f526f783b88cee..d24bb9710d79576a43ace4059c62ce82c3c8c098 100644 --- a/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordStateImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/Sensor_RecordState/sensor_recordStateImplementation.h @@ -13,7 +13,6 @@ #pragma once #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" /*! * \brief records the state of the agent. @@ -23,7 +22,6 @@ * \ingroup SensorRecordState */ -//ToDo This module needs a major refactoring, when the new observation/logging concept is implemented. Until then it uses the first ObservationInterface of the ObservationNetwork. class SensorRecordStateImplementation : public SensorInterface { public: @@ -39,7 +37,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); @@ -88,30 +86,6 @@ public: * \param[in] time Current scheduling time */ void Trigger(int time); - -private: - - int agentId = 0; - int timeMSec = 0; - ObservationInterface* observerInstance {nullptr}; - - /*! - * \brief Translates secondaray covered lanes into a string. - * - * This function uses AgentInterface::GetSecondaryCoveredLanes and translates it into a string. - * - * \param[in] roadId id if the road for which lanes should be writen - * @return secondary lanes as string. - */ - std::string SecondaryLanesToString(const std::string& roadId); - - /*! - * \brief Sends all output relevant agent variables to the observer. - * - * Sends all output relevant agent variables to the observer. - * Which are later on logged. - */ - void ObserveEgo(); }; diff --git a/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizer.cpp b/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizer.cpp index 21bbc53942888117b8c5d17ef9632f741da834e6..57d29e6d8895c6ca297b4399b0b0af75cf973fc8 100644 --- a/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizer.cpp +++ b/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizer.cpp @@ -34,7 +34,7 @@ extern "C" SIGNAL_PRIORITIZER_SHARED_EXPORT ModelInterface *OpenPASS_CreateInsta StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -53,7 +53,7 @@ extern "C" SIGNAL_PRIORITIZER_SHARED_EXPORT ModelInterface *OpenPASS_CreateInsta cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizerImplementation.cpp b/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizerImplementation.cpp index 938f4c9b9ecc5033bad44cd8d77ef71170f2e73b..3099023afca3803b8c384b9fa05c7939a6555d0b 100644 --- a/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizerImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizerImplementation.cpp @@ -27,7 +27,7 @@ SignalPrioritizerImplementation::SignalPrioritizerImplementation( int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : AlgorithmInterface ( @@ -39,7 +39,7 @@ SignalPrioritizerImplementation::SignalPrioritizerImplementation( cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizerImplementation.h b/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizerImplementation.h index d3582c56c7a96df4fc59ff36945ce8e7ba65185f..ca9cfcd8dd141bbb58bd28f962ac514766ac66d9 100644 --- a/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizerImplementation.h +++ b/OpenPass_Source_Code/openPASS/Components/SignalPrioritizer/signalPrioritizerImplementation.h @@ -58,7 +58,7 @@ public: int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector.cpp index 777fe933869739c219bda55479ff967170bb1fae..018db6ad07d554ff8f21947c9dc4fda864b3fe87 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector.cpp @@ -36,7 +36,7 @@ extern "C" ALGORITHM_SELECTOR_SHARED_EXPORT ModelInterface *OpenPASS_CreateInsta StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -57,7 +57,7 @@ extern "C" ALGORITHM_SELECTOR_SHARED_EXPORT ModelInterface *OpenPASS_CreateInsta cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent->GetAgentId())); } diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector_implementation.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector_implementation.cpp index 56b161903a2a1819436e09494fe5c21164195f4b..69977e1762d9988b14946236f4ceb1d7d38a5203 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector_implementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector_implementation.cpp @@ -20,7 +20,7 @@ Algorithm_Selector_Implementation::Algorithm_Selector_Implementation(int compone int responseTime, int cycleTime, StochasticsInterface *stochastics, - const ParameterInterface *parameters, const std::map<int, ObservationInterface *> *observations, + const ParameterInterface *parameters, PublisherInterface * const publisher, const CallbackInterface *callbacks, int agentId) : AlgorithmInterface(componentId, @@ -31,7 +31,7 @@ Algorithm_Selector_Implementation::Algorithm_Selector_Implementation(int compone cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agentId) { diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector_implementation.h b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector_implementation.h index 305e2bd27dba09075a92379c1c2bc237ffaae3d0..d1338770502e97ef00ccd2cc94fcb5856573d1ec 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_Selector/algorithm_selector_implementation.h @@ -20,7 +20,6 @@ #include <fstream> #include <QTextStream> #include "modelInterface.h" -#include "observationInterface.h" #include "primitiveSignals.h" #include "vectorSignals.h" #include "componentPorts.h" @@ -79,7 +78,7 @@ public: int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, int agentId); virtual ~Algorithm_Selector_Implementation(); diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower.cpp index 0646157441c89b8375d76c21691e74dee53fcfdf..363f3e0eefb40ebaf539fa739632f63912f503f8 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower.cpp @@ -56,7 +56,7 @@ ModelInterface *OpenPASS_CreateInstance(int componentId, StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -77,7 +77,7 @@ ModelInterface *OpenPASS_CreateInstance(int componentId, cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent->GetAgentId())); } diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower_implementation.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower_implementation.cpp index 5b8e7078b323c7fff10ec0cec8ce6499a9781294..dd95d1d0bbed1fcda24a85546a61c566d5d89d08 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower_implementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower_implementation.cpp @@ -30,7 +30,7 @@ Algorithm_TrajectoryFollower_Implementation::Algorithm_TrajectoryFollower_Implem int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, int agentId) : AlgorithmInterface(componentId, @@ -41,7 +41,7 @@ Algorithm_TrajectoryFollower_Implementation::Algorithm_TrajectoryFollower_Implem cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agentId) { diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower_implementation.h b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower_implementation.h index 578ea56d9f4837c3123a48a223cdb45bac223fb6..0e25c1f53987ecc284eb4cdaea4cdc3e75d4664d 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Algorithm_TrajectoryFollower/algorithm_trajectoryFollower_implementation.h @@ -75,7 +75,7 @@ public: int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, int agentId); //! Destructor diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision.cpp index b77362c90661138acb83bbb762e9381115bfdf2b..7c0fd07a3e42657bd58eeb4ddacaaa6d81cf98f7 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision.cpp @@ -60,7 +60,7 @@ extern "C" DYNAMICS_COLLISIONSHARED_EXPORT DynamicsInterface *OpenPASS_CreateIns StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *evaluations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -79,7 +79,7 @@ extern "C" DYNAMICS_COLLISIONSHARED_EXPORT DynamicsInterface *OpenPASS_CreateIns stochastics, world, parameters, - evaluations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision_implementation.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision_implementation.cpp index fae1f77540c9247825b23f5770e8e30d7f693f2e..de459907631d8d87653c99d67c0b50b7ea189595 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision_implementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision_implementation.cpp @@ -21,7 +21,7 @@ Dynamics_Collision_Implementation::Dynamics_Collision_Implementation(int compone StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *evaluations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : DynamicsInterface(componentId, @@ -33,7 +33,7 @@ Dynamics_Collision_Implementation::Dynamics_Collision_Implementation(int compone stochastics, world, parameters, - evaluations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision_implementation.h b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision_implementation.h index f4b75a7c395bdb328d3bcea3a066cf709c7caff6..a150751a84f800b2b8aa3da314864e53215c61ef 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_Collision/dynamics_collision_implementation.h @@ -14,7 +14,6 @@ #include <vector> #include "modelInterface.h" -#include "observationInterface.h" #include "primitiveSignals.h" #include "postCrashDynamic.h" #include "componentPorts.h" @@ -75,7 +74,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *evaluations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); //----------------------------------------------------------------------------- diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory.cpp index 1fae87a5ee65cc90e21fdc3e63924b5a079cc5d5..3e66b3b73e42d575007e9684e9e0392d065991a9 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory.cpp @@ -60,7 +60,7 @@ extern "C" DYNAMICS_COPYTRAJECTORYSHARED_EXPORT DynamicsInterface *OpenPASS_Crea StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *evaluations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -79,7 +79,7 @@ extern "C" DYNAMICS_COPYTRAJECTORYSHARED_EXPORT DynamicsInterface *OpenPASS_Crea stochastics, world, parameters, - evaluations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory_implementation.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory_implementation.cpp index 539595366f9d73061a0b2d0e07cf4942d6837115..a2c134b09ccd7cd58706204ba232970e53215a0d 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory_implementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory_implementation.cpp @@ -22,7 +22,7 @@ Dynamics_CopyTrajectory_Implementation::Dynamics_CopyTrajectory_Implementation(i StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *evaluations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : DynamicsInterface(componentId, @@ -34,7 +34,7 @@ Dynamics_CopyTrajectory_Implementation::Dynamics_CopyTrajectory_Implementation(i stochastics, world, parameters, - evaluations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory_implementation.h b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory_implementation.h index 5c7834e70514912d02cb19a671bc4f72495967d7..9e84cb8b0e42182f1baf2c2129404f00e580ac6f 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_CopyTrajectory/dynamics_copyTrajectory_implementation.h @@ -14,7 +14,6 @@ #include <vector> #include "modelInterface.h" -#include "observationInterface.h" /** \addtogroup Components_PCM openPASS components pcm * @{ @@ -60,7 +59,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *evaluations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); //----------------------------------------------------------------------------- diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack.cpp index 503f5f19f376d072a4ca43bb67e412db90060e3a..0bdcd88e6c40d70aba97db2fac9b8d14bb05cc07 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack.cpp @@ -59,7 +59,7 @@ extern "C" DYNAMICS_TWOTRACKSHARED_EXPORT DynamicsInterface *OpenPASS_CreateInst StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -81,7 +81,7 @@ extern "C" DYNAMICS_TWOTRACKSHARED_EXPORT DynamicsInterface *OpenPASS_CreateInst stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack_implementation.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack_implementation.cpp index 97e7074583defd58e9239dcc3413b05c5e618d9e..b860c203f1261641eaeace9d664b30ad4961300e 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack_implementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack_implementation.cpp @@ -53,7 +53,7 @@ Dynamics_TwoTrack_Implementation::Dynamics_TwoTrack_Implementation( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : DynamicsInterface( @@ -66,7 +66,7 @@ Dynamics_TwoTrack_Implementation::Dynamics_TwoTrack_Implementation( stochastics, world, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack_implementation.h b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack_implementation.h index 6a0bcb3cd7a79cace4f2aa9bc58342eb13f1f153..21283ea2893755e4228c78c05ad01f4fb0fd9ddb 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Dynamics_TwoTrack/dynamics_twotrack_implementation.h @@ -13,7 +13,6 @@ #define DYNAMICS_TWOTRACK_IMPLEMENTATION_H #include "modelInterface.h" -#include "observationInterface.h" #include "primitiveSignals.h" #include "vectorSignals.h" #include "vector2d.h" @@ -71,7 +70,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); Dynamics_TwoTrack_Implementation(const Dynamics_TwoTrack_Implementation &) = delete; diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor.cpp index 46a529ccf8f70ad2c8789182b329d0a4329880b7..91d90482bf5b2df6557d6b6b60612bc779dc1815 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor.cpp @@ -35,7 +35,7 @@ extern "C" EGO_SENSOR_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance(int StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -57,7 +57,7 @@ extern "C" EGO_SENSOR_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance(int stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor_implementation.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor_implementation.cpp index e47398d192096dd531b277405b7b885c40bfd46e..546abbdf943c4e2dbd1081e4a9f8dd114daba419 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor_implementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor_implementation.cpp @@ -22,7 +22,7 @@ EgoSensor_Implementation::EgoSensor_Implementation(int componentId, StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *evaluations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : SensorInterface(componentId, @@ -34,7 +34,7 @@ EgoSensor_Implementation::EgoSensor_Implementation(int componentId, stochastics, world, parameters, - evaluations, + publisher, callbacks, agent), isInitDone(false) diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor_implementation.h b/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor_implementation.h index 1216fb2984c5625c6a9fa55393448080a947d026..c3809551849f05614227e0c6c1c9e51681068516 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components_PCM/EgoSensor/egoSensor_implementation.h @@ -14,7 +14,6 @@ #include <math.h> #include "modelInterface.h" -#include "observationInterface.h" #include "primitiveSignals.h" #include "componentPorts.h" @@ -64,7 +63,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *evaluations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); //----------------------------------------------------------------------------- diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent.cpp index 85d509f453b1a744253ee2aa5d3bbb6f4f7779ff..f84ad649aac7e1098f953db764fbf7c1fb192535 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent.cpp @@ -31,7 +31,7 @@ extern "C" INIT_AGENTSHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -52,7 +52,7 @@ extern "C" INIT_AGENTSHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } catch (const std::runtime_error &ex) { diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent_implementation.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent_implementation.cpp index b42794ff8b066f26db3c56be3b0b6408237a35af..6e58776248a0042b26b8ddeb1ac28e8f60cfead7 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent_implementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent_implementation.cpp @@ -23,7 +23,7 @@ Init_Agent_Implementation::Init_Agent_Implementation( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : InitInterface( @@ -36,7 +36,7 @@ Init_Agent_Implementation::Init_Agent_Implementation( stochastics, world, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent_implementation.h b/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent_implementation.h index ff89acda64a7fa7063e00b32153f99a157734b09..60ddd6098117d4a84973ee268f7a4560521983a9 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Init_Agent/init_agent_implementation.h @@ -13,7 +13,6 @@ #define INIT_AGENT_IMPLEMENTATION_H #include "modelInterface.h" -#include "observationInterface.h" #include "pcm_trajectory.h" #include "trajectorySignal.h" #include "primitiveSignals.h" @@ -51,7 +50,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); Init_Agent_Implementation(const Init_Agent_Implementation &) = delete; diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision.cpp index 6e59d7574dea1c17ae9fc397780c7b76c21d8e32..8551a0d1a1df450152cb91b60296f612d30f5824 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision.cpp @@ -36,7 +36,7 @@ extern "C" SENSOR_COLLISION_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstanc StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -57,7 +57,7 @@ extern "C" SENSOR_COLLISION_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstanc stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision_implementation.cpp b/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision_implementation.cpp index d807d5180e2c2cd15b9e9eecdf586caff009bc68..08bae58fe6d75a613ab4789d8f87a2ebb867d5bd 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision_implementation.cpp +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision_implementation.cpp @@ -21,7 +21,7 @@ Sensor_Collision_Implementation::Sensor_Collision_Implementation(int componentId int cycleTime, StochasticsInterface *stochastics, WorldInterface *world, - const ParameterInterface *parameters, const std::map<int, ObservationInterface *> *observations, + const ParameterInterface *parameters, PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : SensorInterface(componentId, @@ -33,7 +33,7 @@ Sensor_Collision_Implementation::Sensor_Collision_Implementation(int componentId stochastics, world, parameters, - observations, + publisher, callbacks, agent) { diff --git a/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision_implementation.h b/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision_implementation.h index ceea6abb4f627a16db79e00589df176b977d671e..7c247f063e4e2dbf698a333dcf35487269237365 100644 --- a/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision_implementation.h +++ b/OpenPass_Source_Code/openPASS/Components_PCM/Sensor_Collision/sensor_collision_implementation.h @@ -19,7 +19,6 @@ #include <fstream> #include <QTextStream> #include "modelInterface.h" -#include "observationInterface.h" #include "primitiveSignals.h" #include "postCrashDynamic.h" #include "componentPorts.h" @@ -76,7 +75,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent); diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/CoreShare/xmlParser.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/CoreShare/xmlParser.cpp index f6c8f83f0b68f2967ae0dcd12f2a48141e356643..a925e8338cb58a5456ef757f2f960c7d613c9919 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/CoreShare/xmlParser.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/CoreShare/xmlParser.cpp @@ -12,6 +12,8 @@ #include <optional> #include <sstream> +#include "Common/commonTools.h" + #include "xmlParser.h" namespace SimulationCommon @@ -308,6 +310,12 @@ bool ParseAttribute<>(QDomElement element, const std::string &attributeName, std return ParseAttributeDoubleVector(element, attributeName, &result); } +template<> +bool ParseAttribute<>(QDomElement element, const std::string &attributeName, std::vector<std::string>& result) +{ + return ParseAttributeStringVector(element, attributeName, &result); +} + template<> bool ParseAttribute<int>(QDomElement element, const std::string &attributeName, int& result) { @@ -437,6 +445,31 @@ bool ParseAttributeBool(QDomElement element, const std::string &attributeName, b return true; } +bool ParseAttributeStringVector(QDomElement element, const std::string &attributeName, std::vector<std::string> *result) +{ + if (!element.hasAttribute(QString::fromStdString(attributeName))) + { + return false; + } + + QDomAttr attribute = element.attributeNode(QString::fromStdString(attributeName)); + if (attribute.isNull()) + { + return false; + } + + try + { + *result = CommonHelper::TokenizeString(attribute.value().toStdString(), ','); + } + catch(...) + { + return false; + } + + return true; +} + bool ParseAttributeDoubleVector(QDomElement element, const std::string &attributeName, std::vector<double> *result) { if(!element.hasAttribute(QString::fromStdString(attributeName))) diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/CoreShare/xmlParser.h b/OpenPass_Source_Code/openPASS/CoreFramework/CoreShare/xmlParser.h index 02d11586efb19ca957b239edf64aa384f480af14..2ace9a830dc5ab5c0abf746c0d8a5603bc56f6d6 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/CoreShare/xmlParser.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/CoreShare/xmlParser.h @@ -17,15 +17,15 @@ #pragma once #include <string> -#include <QFile> -#include <QDomDocument> #include <unordered_map> -#include "log.h" + +#include <QDomDocument> +#include <QFile> #include "Interfaces/roadInterface/roadElementTypes.h" +#include "log.h" -namespace SimulationCommon -{ +namespace SimulationCommon { extern bool GetFirstChildElement(QDomElement rootElement, const std::string &tag, QDomElement &result); @@ -37,7 +37,7 @@ extern bool ParseCurrentInt(QDomElement currentElement, int &result); /// Tempalted wrapper for Parse* functions template <typename T> -bool Parse(QDomElement rootElement, const std::string &tag, T & result); +bool Parse(QDomElement rootElement, const std::string &tag, T &result); extern bool ParseString(QDomElement rootElement, const std::string &tag, std::string &result); @@ -59,20 +59,16 @@ extern bool ParseAttributeInt(QDomElement element, const std::string &attributeN extern bool ParseAttributeBool(QDomElement element, const std::string &attributeName, bool &result); -extern bool ParseAttributeDoubleVector(QDomElement element, const std::string &attributeName, std::vector<double>* result); - -extern bool ParseAttributeIntVector(QDomElement element, const std::string &attributeName, std::vector<int>* result); +extern bool ParseAttributeStringVector(QDomElement element, const std::string &attributeName, std::vector<std::string> *result); -extern bool ParseAttributeBoolVector(QDomElement element, const std::string &attributeName, std::vector<bool>* result); +extern bool ParseAttributeDoubleVector(QDomElement element, const std::string &attributeName, std::vector<double> *result); -//template <typename T> -//bool ParseAttributeType(QDomElement element, const std::string &attributeName, T &result); +extern bool ParseAttributeIntVector(QDomElement element, const std::string &attributeName, std::vector<int> *result); -bool ParseType(const std::string& element, RoadElementOrientation& orientation); -bool ParseType(const std::string& element, RoadObjectType& objectType); +extern bool ParseAttributeBoolVector(QDomElement element, const std::string &attributeName, std::vector<bool> *result); -//template <typename T> -//bool assignIfMatching(std::string element, T& enumeration, std::string match, T value); +bool ParseType(const std::string &element, RoadElementOrientation &orientation); +bool ParseType(const std::string &element, RoadObjectType &objectType); /*! * \brief Parses the value of an XML attribute into the provided container. @@ -86,7 +82,7 @@ bool ParseType(const std::string& element, RoadObjectType& objectType); * \return True on successful parsing, false otherwise. */ template <typename T> -bool ParseAttribute(QDomElement element, const std::string &attributeName, T& result); +bool ParseAttribute(QDomElement element, const std::string &attributeName, T &result); //! Returns true if the given element has an attribute of the given name @@ -95,13 +91,13 @@ bool HasAttribute(QDomElement element, const std::string &attributeName); template <typename T> bool ParseAttributeType(QDomElement element, const std::string &attributeName, T &result) { - if(!element.hasAttribute(QString::fromStdString(attributeName))) + if (!element.hasAttribute(QString::fromStdString(attributeName))) { return false; } QDomAttr attribute = element.attributeNode(QString::fromStdString(attributeName)); - if(attribute.isNull()) + if (attribute.isNull()) { return false; } @@ -110,9 +106,10 @@ bool ParseAttributeType(QDomElement element, const std::string &attributeName, T } template <typename T> -bool assignIfMatching(const std::string& element, T& enumeration, const std::string& match, const T& value) +bool assignIfMatching(const std::string &element, T &enumeration, const std::string &match, const T &value) { - if(element == match){ + if (element == match) + { enumeration = value; return true; } @@ -143,24 +140,24 @@ bool ImportProbabilityMap(QDomElement parentElement, double probabilitySum = 0.0; QDomElement childElement; - if(!GetFirstChildElement(parentElement, tag.toStdString(), childElement)) + if (!GetFirstChildElement(parentElement, tag.toStdString(), childElement)) { LOG_INTERN(LogLevel::Error) << "At least one element is required."; return false; } - while(!childElement.isNull()) + while (!childElement.isNull()) { T keyValue; double probability; - if(!ParseAttribute<T>(childElement, key, keyValue)) + if (!ParseAttribute<T>(childElement, key, keyValue)) { LOG_INTERN(LogLevel::Error) << "Key is invalid."; return false; } - if(!ParseAttributeDouble(childElement, "Probability", probability)) + if (!ParseAttributeDouble(childElement, "Probability", probability)) { LOG_INTERN(LogLevel::Error) << "Probability is invalid."; return false; @@ -174,13 +171,13 @@ bool ImportProbabilityMap(QDomElement parentElement, } //Checks probabilities - if(mustAddUpToOne && std::abs(probabilitySum - 1.0) > 1e-6) + if (mustAddUpToOne && std::abs(probabilitySum - 1.0) > 1e-6) { LOG_INTERN(LogLevel::Error) << "Probabilities do not add up to 1.0."; return false; } - if(probabilitySum > 1.0 + 1e-6) + if (probabilitySum > 1.0 + 1e-6) { LOG_INTERN(LogLevel::Error) << "Probabilities add up to more than 1.0."; return false; @@ -189,16 +186,15 @@ bool ImportProbabilityMap(QDomElement parentElement, return true; } - } // namespace SimulationCommon [[maybe_unused]] static void ThrowIfFalse(bool success, const QDomElement element, const std::string &message) { if (!success) { - LogErrorAndThrow("Could not import element " + element.tagName().toStdString() - + " (line " + std::to_string(element.lineNumber()) - + ", column " + std::to_string(element.columnNumber()) - + "): " + message); + LogErrorAndThrow("Could not import element " + element.tagName().toStdString() + + " (line " + std::to_string(element.lineNumber()) + + ", column " + std::to_string(element.columnNumber()) + "): " + + message); } } diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassMaster/OpenPassMaster.pro b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassMaster/OpenPassMaster.pro index cfec0555844acff92a42907c4c3bd6c3ba0f8558..27a9b43a13deb0eaf514236d94f2a3d5abc2d36e 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassMaster/OpenPassMaster.pro +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassMaster/OpenPassMaster.pro @@ -35,6 +35,7 @@ INCLUDEPATH += \ SOURCES += \ $$SRC_CORESHARE \ + ../../Common/vector2d.cpp \ framework/main.cpp \ framework/processManager.cpp \ importer/masterConfigImporter.cpp diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/OpenPassSlave.pro b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/OpenPassSlave.pro index 4738cd1bacfcbd07e6bc91aa8c5b32a4f7d21a61..1fcd91fd2810ff10ebd66fc4b0f9a3f61e85e152 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/OpenPassSlave.pro +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/OpenPassSlave.pro @@ -41,13 +41,14 @@ defineReplace(getFiles) { } SUBDIRS += \ - observationInterface \ framework \ importer \ importer/road \ modelElements \ modelInterface \ scheduler \ + dataStoreInterface \ + observationInterface \ spawnPointInterface \ stochasticsInterface \ worldInterface \ diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStore.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStore.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0e360d6a0a2190cfadf40a475cc9cec951a271c --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStore.cpp @@ -0,0 +1,79 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#include "dataStoreInterface/dataStore.h" + +namespace SimulationSlave { + +using namespace openpass::type; + +bool DataStore::Instantiate() +{ + if (!dataStoreBinding) + { + return false; + } + else if (!implementation) + { + implementation = dataStoreBinding->Instantiate(); + if (!implementation) + { + return false; + } + } + return true; +} + +bool DataStore::isInstantiated() const +{ + return implementation != nullptr; +} + +void DataStore::PutCyclic(const Timestamp time, const EntityId agentId, const Key &key, const Value &value) +{ + return implementation->PutCyclic(time, agentId, key, value); +} + +void DataStore::PutAcyclic(const Timestamp time, const EntityId agentId, const Key &key, const Acyclic &acyclic) +{ + return implementation->PutAcyclic(time, agentId, key, acyclic); +} + +void DataStore::PutStatic(const Key &key, const Value &value, bool persist) +{ + return implementation->PutStatic(key, value, persist); +} + +void DataStore::Clear() +{ + return implementation->Clear(); +} + +std::unique_ptr<CyclicResultInterface> DataStore::GetCyclic(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key &key) const +{ + return implementation->GetCyclic(time, entityId, key); +} + +std::unique_ptr<AcyclicResultInterface> DataStore::GetAcyclic(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key &key) const +{ + return implementation->GetAcyclic(time, entityId, key); +} + +Values DataStore::GetStatic(const Key &key) const +{ + return implementation->GetStatic(key); +} + +Keys DataStore::GetKeys(const Key &key) const +{ + return implementation->GetKeys(key); +} + +} // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStore.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStore.h new file mode 100644 index 0000000000000000000000000000000000000000..032c718d5848e4b0eacd673386540a8974bd7ee6 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStore.h @@ -0,0 +1,56 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +//----------------------------------------------------------------------------- +//! @file dataStore.h +//! @brief This file provides the interface to a data store implementation +//----------------------------------------------------------------------------- + +#pragma once + +#include "Interfaces/dataStoreInterface.h" +#include "dataStoreBinding.h" + +namespace SimulationSlave { + +class DataStore : public DataStoreInterface +{ +public: + DataStore(DataStoreBinding *dataStoreBinding) : + dataStoreBinding(dataStoreBinding) + { + } + + DataStore(const DataStore &) = delete; + DataStore(DataStore &&) = delete; + DataStore &operator=(const DataStore &) = delete; + DataStore &operator=(DataStore &&) = delete; + ~DataStore() override = default; + + bool Instantiate() override; + bool isInstantiated() const override; + + void PutCyclic(const openpass::type::Timestamp time, const openpass::type::EntityId entityId, const Key &key, const Value &value) override; + void PutAcyclic(const openpass::type::Timestamp time, const openpass::type::EntityId entityId, const Key &key, const Acyclic &acyclic) override; + void PutStatic(const Key &key, const Value &value, bool persist) override; + + void Clear() override; + + std::unique_ptr<CyclicResultInterface> GetCyclic(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key &key) const override; + std::unique_ptr<AcyclicResultInterface> GetAcyclic(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key &key) const override; + Values GetStatic(const Key &key) const override; + Keys GetKeys(const Key &key) const override; + +private: + DataStoreBinding *dataStoreBinding = nullptr; + DataStoreInterface *implementation = nullptr; +}; + +} // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreBinding.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreBinding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3eb4827115f4695d62f1b45776d022646eac7498 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreBinding.cpp @@ -0,0 +1,63 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#include "dataStoreBinding.h" +#include "dataStoreLibrary.h" + +namespace SimulationSlave +{ + +DataStoreBinding::DataStoreBinding(std::string libraryPath, + const openpass::common::RuntimeInformation& runtimeInformation, + CallbackInterface *callbacks) : + libraryPath{libraryPath}, + callbacks{callbacks}, + runtimeInformation{runtimeInformation} +{ +} + +DataStoreBinding::~DataStoreBinding() +{ + Unload(); +} + +DataStoreInterface* DataStoreBinding::Instantiate() +{ + if (!library) + { + library = new (std::nothrow) DataStoreLibrary(libraryPath, callbacks); + + if (!library) + { + return nullptr; + } + + if (!library->Init()) + { + delete library; + library = nullptr; + return nullptr; + } + } + + return library->CreateDataStore(runtimeInformation); +} + +void DataStoreBinding::Unload() +{ + if (library) + { + library->ReleaseDataStore(); + delete library; + library = nullptr; + } +} + +} // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreBinding.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreBinding.h new file mode 100644 index 0000000000000000000000000000000000000000..f6ce38ff97974ad46e2a7f096230d0b4a5d043f8 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreBinding.h @@ -0,0 +1,58 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +//----------------------------------------------------------------------------- +//! @file dataStoreBinding.h +//! @brief This file contains the interface to the dataStore library. +//----------------------------------------------------------------------------- + +#pragma once + +#include "Common/runtimeInformation.h" +#include "Interfaces/dataStoreInterface.h" + +class CallbackInterface; + +namespace SimulationSlave { + +class DataStoreLibrary; +class FrameworkConfig; + +class DataStoreBinding +{ +public: + DataStoreBinding(std::string libraryPath, const openpass::common::RuntimeInformation& runtimeInformation, CallbackInterface* callbacks); + DataStoreBinding(const DataStoreBinding&) = delete; + DataStoreBinding(DataStoreBinding&&) = delete; + DataStoreBinding& operator=(const DataStoreBinding&) = delete; + DataStoreBinding& operator=(DataStoreBinding&&) = delete; + virtual ~DataStoreBinding(); + + //----------------------------------------------------------------------------- + //! Gets the dataStore instance library and stores it, + //! then creates a new dataStoreInterface of the library. + //! + //! @return dataStoreInterface created from the library + //----------------------------------------------------------------------------- + DataStoreInterface* Instantiate(); + + //----------------------------------------------------------------------------- + //! Unloads the stochasticsInterface binding by deleting the library. + //----------------------------------------------------------------------------- + void Unload(); + +private: + const std::string libraryPath; + DataStoreLibrary* library = nullptr; + CallbackInterface* callbacks; + const openpass::common::RuntimeInformation& runtimeInformation; +}; + +} // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreLibrary.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreLibrary.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf4fbd7aeb15f830f0724d4f066c05c25eb179c3 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreLibrary.cpp @@ -0,0 +1,167 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#include "dataStoreLibrary.h" + +#include "CoreFramework/CoreShare/log.h" +#include "CoreFramework/CoreShare/parameters.h" +#include "framework/parameterbuilder.h" + + +namespace SimulationSlave +{ + +bool DataStoreLibrary::Init() +{ + library = new (std::nothrow) QLibrary(QString::fromStdString(dataStoreLibraryPath)); + + if (!library) + { + return false; + } + + if (!library->load()) + { + LOG_INTERN(LogLevel::Error) << library->errorString().toStdString(); + delete library; + library = nullptr; + return false; + } + + getVersionFunc = reinterpret_cast<DataStoreInterface_GetVersion>(library->resolve(DllGetVersionId.c_str())); + if (!getVersionFunc) + { + LOG_INTERN(LogLevel::Error) << "could not retrieve version information from DLL"; + return false; + } + + createInstanceFunc = reinterpret_cast<DataStoreInterface_CreateInstanceType>(library->resolve(DllCreateInstanceId.c_str())); + if (!createInstanceFunc) + { + LOG_INTERN(LogLevel::Error) << "could not create instance from DLL"; + return false; + } + + destroyInstanceFunc = reinterpret_cast<DataStoreInterface_DestroyInstanceType>(library->resolve(DllDestroyInstanceId.c_str())); + if (!destroyInstanceFunc) + { + LOG_INTERN(LogLevel::Warning) << "dataStore could not be released"; + return false; + } + + try + { + LOG_INTERN(LogLevel::DebugCore) << "loaded dataStore library " << library->fileName().toStdString() + << ", version " << getVersionFunc(); + } + catch (std::runtime_error const &ex) + { + LOG_INTERN(LogLevel::Error) << "could not retrieve version information from DLL: " << ex.what(); + return false; + } + catch (...) + { + LOG_INTERN(LogLevel::Error) << "could not retrieve version information from DLL"; + return false; + } + + return true; +} + +DataStoreLibrary::~DataStoreLibrary() +{ + if (dataStoreInterface) + { + LOG_INTERN(LogLevel::Warning) << "unloading library which is still in use"; + } + + if (library) + { + if (library->isLoaded()) + { + LOG_INTERN(LogLevel::DebugCore) << "unloading dataStore library "; + library->unload(); + } + + delete library; + library = nullptr; + } +} + +bool DataStoreLibrary::ReleaseDataStore() +{ + if (!dataStoreInterface) + { + return true; + } + + if (!library) + { + return false; + } + + try + { + destroyInstanceFunc(dataStoreInterface); + } + catch (std::runtime_error const &ex) + { + LOG_INTERN(LogLevel::Error) << "dataStore could not be released: " << ex.what(); + return false; + } + catch (...) + { + LOG_INTERN(LogLevel::Error) << "dataStore could not be released"; + return false; + } + + dataStoreInterface = nullptr; + + return true; +} + +DataStoreInterface* DataStoreLibrary::CreateDataStore(const openpass::common::RuntimeInformation& runtimeInformation) +{ + if (!library) + { + return nullptr; + } + + if (!library->isLoaded()) + { + if (!library->load()) + { + return nullptr; + } + } + + dataStoreInterface = nullptr; + + try + { + dataStoreInterface = createInstanceFunc(&runtimeInformation, callbacks); + } + catch (std::runtime_error const &ex) + { + LOG_INTERN(LogLevel::Error) << "could not create stochastics instance: " << ex.what(); + return nullptr; + } + catch (...) + { + LOG_INTERN(LogLevel::Error) << "could not create stochastics instance"; + return nullptr; + } + + return dataStoreInterface; +} + +} // namespace SimulationSlave + + diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreLibrary.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreLibrary.h new file mode 100644 index 0000000000000000000000000000000000000000..40fe45e15b1e4923fa2776e56e9255e908448227 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/dataStoreInterface/dataStoreLibrary.h @@ -0,0 +1,95 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +//----------------------------------------------------------------------------- +//! @file dataStoreLibrary.h +//! @brief This file contains the internal representation of the library of a +//! dataStoreInterface. +//----------------------------------------------------------------------------- + +#pragma once + +#include <QLibrary> + +#include "dataStoreBinding.h" + +#include "Interfaces/callbackInterface.h" + +namespace SimulationSlave +{ + +class DataStoreLibrary +{ +public: + typedef const std::string &(*DataStoreInterface_GetVersion)(); + typedef DataStoreInterface *(*DataStoreInterface_CreateInstanceType)( + const openpass::common::RuntimeInformation* runtimeInformation, CallbackInterface* callbacks); + typedef void (*DataStoreInterface_DestroyInstanceType)(DataStoreInterface *implementation); + + + DataStoreLibrary(const std::string &dataStoreLibraryPath, CallbackInterface *callbacks) : + dataStoreLibraryPath(dataStoreLibraryPath), + callbacks(callbacks) + { + } + + DataStoreLibrary(const DataStoreLibrary&) = delete; + DataStoreLibrary(DataStoreLibrary&&) = delete; + DataStoreLibrary& operator=(const DataStoreLibrary&) = delete; + DataStoreLibrary& operator=(DataStoreLibrary&&) = delete; + + //----------------------------------------------------------------------------- + //! Destructor, deletes the stored library (unloads it if necessary) + //----------------------------------------------------------------------------- + virtual ~DataStoreLibrary(); + + //----------------------------------------------------------------------------- + //! Creates a QLibrary based on the path from the constructor and stores function + //! pointer for getting the library version, creating and destroying instances + //! and setting the stochasticsInterface item + //! (see typedefs for corresponding signatures). + //! + //! @return true on successful operation, false otherwise + //----------------------------------------------------------------------------- + bool Init(); + + //----------------------------------------------------------------------------- + //! Delete the DataStoreInterface and the library + //! + //! @return Flag if the release was successful + //----------------------------------------------------------------------------- + bool ReleaseDataStore(); + + //----------------------------------------------------------------------------- + //! Make sure that the library exists and is loaded, then call the "create instance" + //! function pointer, which instantiates a DataStoreInterface. The created Interface + //! is stored. + //! + //! @param[in] runtimeInformation Reference to the simulation slave runtime information + //! + //! @return DataStoreInterface created + //----------------------------------------------------------------------------- + DataStoreInterface* CreateDataStore(const openpass::common::RuntimeInformation& runtimeInformation); + +private: + const std::string DllGetVersionId = "OpenPASS_GetVersion"; + const std::string DllCreateInstanceId = "OpenPASS_CreateInstance"; + const std::string DllDestroyInstanceId = "OpenPASS_DestroyInstance"; + + const std::string dataStoreLibraryPath; + DataStoreInterface* dataStoreInterface = nullptr; + QLibrary* library = nullptr; + CallbackInterface* callbacks; + DataStoreInterface_GetVersion getVersionFunc{nullptr}; + DataStoreInterface_CreateInstanceType createInstanceFunc{nullptr}; + DataStoreInterface_DestroyInstanceType destroyInstanceFunc{nullptr}; +}; + +} // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentDataPublisher.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentDataPublisher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0cf40850b2e1fc0596480c7bd368d2d0b54f0491 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentDataPublisher.cpp @@ -0,0 +1,27 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#include "agentDataPublisher.h" + +#include "../scheduler/timeKeeper.h" //TODO René/Reinhard: this is troublesome + +namespace openpass::publisher { + +void AgentDataPublisher::Publish(const openpass::datastore::Key &key, const openpass::datastore::Value &value) +{ + dataStore->PutCyclic(openpass::scheduling::TimeKeeper::Now(), agentId, key, value); +} + +void AgentDataPublisher::Publish(const openpass::datastore::Key &key, const openpass::datastore::ComponentEvent &event) +{ + dataStore->PutAcyclic(openpass::scheduling::TimeKeeper::Now(), agentId, key, Acyclic(key, agentId, event.parameter)); +} + +} // namespace openpass::publisher diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentDataPublisher.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentDataPublisher.h new file mode 100644 index 0000000000000000000000000000000000000000..d15af771669c671bd21d0d2004bf25f125c0cc94 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentDataPublisher.h @@ -0,0 +1,36 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#pragma once + +#include "Interfaces/dataStoreInterface.h" +#include "Interfaces/publisherInterface.h" + +namespace openpass::publisher { + +///! Interface which has to be provided by observation modules +class AgentDataPublisher : public PublisherInterface +{ +public: + AgentDataPublisher(DataStoreWriteInterface *const dataStore, const int agentId) : + PublisherInterface{dataStore}, + agentId{agentId} + { + } + + void Publish(const openpass::datastore::Key &key, const openpass::datastore::Value &value) override; + + void Publish(const openpass::datastore::Key &key, const openpass::datastore::ComponentEvent &event) override; + +private: + const int agentId; +}; + +} // namespace openpass::publisher diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentFactory.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentFactory.cpp index bd6d7b7380caa8067efa81d667af366f8c532bd6..413214d90160a8a6bfea26fafd3ee10951798207 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentFactory.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentFactory.cpp @@ -12,20 +12,27 @@ #include <algorithm> #include <list> #include <sstream> + #include "agent.h" #include "agentFactory.h" #include "agentType.h" #include "channel.h" #include "channelBuffer.h" -#include "Interfaces/componentInterface.h" -#include "CoreFramework/CoreShare/log.h" + +#include "agentDataPublisher.h" #include "modelBinding.h" -#include "Interfaces/observationNetworkInterface.h" -#include "CoreFramework/CoreShare/parameters.h" #include "spawnPoint.h" #include "stochastics.h" + +#include "CoreFramework/CoreShare/log.h" +#include "CoreFramework/CoreShare/parameters.h" +#include "Interfaces/componentInterface.h" +#include "Interfaces/observationNetworkInterface.h" #include "Interfaces/worldInterface.h" + +class DataStoreInterface; + namespace SimulationSlave { @@ -33,12 +40,14 @@ AgentFactory::AgentFactory(ModelBinding *modelBinding, WorldInterface *world, Stochastics *stochastics, ObservationNetworkInterface *observationNetwork, - EventNetworkInterface *eventNetwork) : + EventNetworkInterface *eventNetwork, + DataStoreWriteInterface* dataStore) : modelBinding(modelBinding), world(world), stochastics(stochastics), observationNetwork(observationNetwork), - eventNetwork(eventNetwork) + eventNetwork(eventNetwork), + dataStore(dataStore) { } @@ -50,54 +59,54 @@ void AgentFactory::Clear() Agent* AgentFactory::AddAgent(AgentBlueprintInterface* agentBlueprint) { - Agent *agent = CreateAgent(lastAgentId, - agentBlueprint); - if(!agent) + auto agent = CreateAgent(lastAgentId, agentBlueprint); + + PublishProperties(*agent); + + if (!agent) { LOG_INTERN(LogLevel::Error) << "could not create agent"; return nullptr; } - if(!world->AddAgent(lastAgentId, agent->GetAgentAdapter())) + if (!world->AddAgent(lastAgentId, agent->GetAgentAdapter())) { LOG_INTERN(LogLevel::Error) << "could not add agent to network"; - delete agent; return nullptr; } lastAgentId++; - agentList.push_back(std::unique_ptr<Agent>(agent)); - return agent; + agentList.push_back(std::move(agent)); + + return agentList.back().get(); } -Agent *AgentFactory::CreateAgent(int id, - AgentBlueprintInterface* agentBlueprint) +std::unique_ptr<Agent> AgentFactory::CreateAgent(int id, AgentBlueprintInterface* agentBlueprint) { LOG_INTERN(LogLevel::DebugCore) << "instantiate agent (id " << id << ")"; - Agent *agent = new (std::nothrow) Agent(id, - world); - if(!agent) + auto agent = std::make_unique<Agent>(id, world); + + if (!agent) { return nullptr; } - if(!agent->Instantiate(agentBlueprint, - modelBinding, - stochastics, - observationNetwork, - eventNetwork)) + if (!agent->Instantiate(agentBlueprint, + modelBinding, + stochastics, + observationNetwork, + eventNetwork, + dataStore)) { LOG_INTERN(LogLevel::Error) << "agent could not be instantiated"; - delete agent; return nullptr; } // link agent internal components - if(!ConnectAgentLinks(agent)) + if (!ConnectAgentLinks(agent.get())) { LOG_INTERN(LogLevel::Error) << "agent channels could not be created"; - delete agent; return nullptr; } @@ -147,4 +156,55 @@ bool AgentFactory::ConnectAgentLinks(Agent *agent) return true; } +void AgentFactory::PublishProperties(const Agent& agent) +{ + const auto adapter = agent.GetAgentAdapter(); + const std::string keyPrefix = "Agents/" + std::to_string(agent.GetId()) + "/"; + dataStore->PutStatic(keyPrefix + "AgentTypeGroupName", AgentCategoryStrings[static_cast<int>(adapter->GetAgentCategory())]); + dataStore->PutStatic(keyPrefix + "AgentTypeName", adapter->GetAgentTypeName()); + dataStore->PutStatic(keyPrefix + "VehicleModelType", adapter->GetVehicleModelType()); + dataStore->PutStatic(keyPrefix + "DriverProfileName", adapter->GetDriverProfileName()); + + const auto& vehicleModelParameters = adapter->GetVehicleModelParameters(); + const double longitudinalPivotOffset = (vehicleModelParameters.length / 2.0) - vehicleModelParameters.distanceReferencePointToLeadingEdge; + dataStore->PutStatic(keyPrefix + "Vehicle/Width", vehicleModelParameters.width); + dataStore->PutStatic(keyPrefix + "Vehicle/Length", vehicleModelParameters.length); + dataStore->PutStatic(keyPrefix + "Vehicle/Height", vehicleModelParameters.height); + dataStore->PutStatic(keyPrefix + "Vehicle/LongitudinalPivotOffset", longitudinalPivotOffset); + + for (const auto& sensor : adapter->GetSensorParameters()) + { + const std::string sensorKeyPrefix = keyPrefix + "Vehicle/Sensors/" + std::to_string(sensor.id) + "/"; + dataStore->PutStatic(sensorKeyPrefix + "Type", sensor.profile.type); + dataStore->PutStatic(sensorKeyPrefix + "Mounting/Position/Longitudinal", sensor.position.longitudinal); + dataStore->PutStatic(sensorKeyPrefix + "Mounting/Position/Lateral", sensor.position.lateral); + dataStore->PutStatic(sensorKeyPrefix + "Mounting/Position/Height", sensor.position.height); + dataStore->PutStatic(sensorKeyPrefix + "Mounting/Orientation/Yaw", sensor.position.yaw); + dataStore->PutStatic(sensorKeyPrefix + "Mounting/Orientation/Pitch", sensor.position.pitch); + dataStore->PutStatic(sensorKeyPrefix + "Mounting/Orientation/Roll", sensor.position.roll); + + const auto& parameters = sensor.profile.parameter; + + if (auto latency = openpass::parameter::Get<double>(parameters, "Latency")) + { + dataStore->PutStatic(sensorKeyPrefix + "Parameters/Latency", latency.value()); + } + + if (auto openingAngleH = openpass::parameter::Get<double>(parameters, "OpeningAngleH")) + { + dataStore->PutStatic(sensorKeyPrefix + "Parameters/OpeningAngleH", openingAngleH.value()); + } + + if (auto openingAngleV = openpass::parameter::Get<double>(parameters, "OpeningAngleV")) + { + dataStore->PutStatic(sensorKeyPrefix + "Parameters/OpeningAngleV", openingAngleV.value()); + } + + if (auto detectionRange = openpass::parameter::Get<double>(parameters, "DetectionRange")) + { + dataStore->PutStatic(sensorKeyPrefix + "Parameters/Range", detectionRange.value()); + } + } +} + } // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentFactory.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentFactory.h index 71bb47efc62f2faf0c502db15f0afb356bceba6e..47c2d3ef4e9c6bfed3d4bb2ada5f8d019a921f04 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentFactory.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/agentFactory.h @@ -28,6 +28,8 @@ #include "Interfaces/eventNetworkInterface.h" #include "Interfaces/worldInterface.h" +class DataStoreWriteInterface; + namespace SimulationSlave { class Agent; @@ -46,8 +48,9 @@ public: WorldInterface *world, Stochastics *stochastics, ObservationNetworkInterface *observationNetwork, - SimulationSlave::EventNetworkInterface *eventNetwork); - virtual ~AgentFactory() = default; + SimulationSlave::EventNetworkInterface *eventNetwork, + DataStoreWriteInterface* dataStore); + virtual ~AgentFactory() override = default; virtual void Clear() override; virtual Agent *AddAgent(AgentBlueprintInterface* agentBlueprint) override; @@ -83,17 +86,20 @@ private: //! //! @return The created agent //----------------------------------------------------------------------------- - Agent* CreateAgent(int id, - AgentBlueprintInterface* agentBlueprint); + std::unique_ptr<Agent> CreateAgent(int id, AgentBlueprintInterface* agentBlueprint); - int lastAgentId {INITIAL_AGENT_ID}; + void PublishProperties(const Agent& agent); + ModelBinding *modelBinding; WorldInterface *world; Stochastics *stochastics; ObservationNetworkInterface *observationNetwork; EventNetworkInterface *eventNetwork; + DataStoreWriteInterface *dataStore; std::vector<std::unique_ptr<Agent>> agentList; + + int lastAgentId {INITIAL_AGENT_ID}; }; } // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/coreDataPublisher.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/coreDataPublisher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d945f19df2d9c8e9bccbff4938a5c943602662db --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/coreDataPublisher.cpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#include "coreDataPublisher.h" + +#include "scheduler/timeKeeper.h" + +namespace openpass::publisher { + +void CoreDataPublisher::Publish(const openpass::narrator::EventBase &event) +{ + dataStore->PutAcyclic(openpass::scheduling::TimeKeeper::Now(), openpass::type::CoreId, event.name, Acyclic(event)); +} + +} // namespace openpass::publisher diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/coreDataPublisher.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/coreDataPublisher.h new file mode 100644 index 0000000000000000000000000000000000000000..c38712bc29af9d7651bc87a800c36e2b2950f6d5 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/coreDataPublisher.h @@ -0,0 +1,30 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#pragma once + +#include "Interfaces/publisherInterface.h" +#include "framework/eventNetworkDataPublisher.h" + +namespace openpass::publisher { + +///! Interface which has to be provided by observation modules +class CoreDataPublisher : public PublisherInterface +{ +public: + CoreDataPublisher(DataStoreWriteInterface *const dataStore) : + PublisherInterface(dataStore) + { + } + + void Publish(const openpass::narrator::EventBase &event) override; +}; + +} // namespace openpass::publisher diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetwork.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetwork.cpp index e6191e599f9739f68d2c95ee5e9dfd2fef26d820..991ab6294c1d79fdcebcfb5e9c2ef034db29bd12 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetwork.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetwork.cpp @@ -18,7 +18,7 @@ using namespace EventDefinitions; namespace SimulationSlave { -Events* EventNetwork::GetActiveEvents() +Events *EventNetwork::GetActiveEvents() { return &activeEvents; } @@ -31,7 +31,7 @@ Events *EventNetwork::GetArchivedEvents() EventContainer EventNetwork::GetActiveEventCategory(const EventCategory eventCategory) { auto iterator = activeEvents.find(eventCategory); - if(iterator == activeEvents.end()) + if (iterator == activeEvents.end()) { return {}; } @@ -43,28 +43,57 @@ EventContainer EventNetwork::GetActiveEventCategory(const EventCategory eventCat void EventNetwork::RemoveOldEvents(int time) { - for(Events::iterator iterator = archivedEvents.begin(); iterator != archivedEvents.end(); iterator++) + for (Events::iterator iterator = archivedEvents.begin(); iterator != archivedEvents.end(); iterator++) { - while((*iterator).second.front()->GetEventTime() < time) + while ((*iterator).second.front()->GetEventTime() < time) { (*iterator).second.pop_front(); } } } +// This glue logic is only an intermediate state, as we intend to remove EventInterface in the future +void EventNetwork::Log(const std::shared_ptr<EventInterface> &event) +{ + openpass::narrator::Event narratorEvent(EventDefinitions::helper::GetAsString(event->GetCategory())); // USE THAT IN THE FUTURE INSTEAD OF EVENTINTERFACE + + // TODO: Named type issue (assigment missing) + for (auto agent : event->GetTriggeringAgents()) + { + narratorEvent.triggeringEntities.entities.push_back(agent); + } + + // TODO: Named type issue (assigment missing) + for (auto agent : event->GetActingAgents()) + { + narratorEvent.affectedEntities.entities.push_back(agent); + } + + narratorEvent.parameter = event->GetParameter(); + + publisher.Publish(narratorEvent); +} + void EventNetwork::InsertEvent(std::shared_ptr<EventInterface> event) { event->SetId(eventId); eventId++; activeEvents[event->GetCategory()].push_back(event); + + // This filter is currently necessary, as manipulators fire events too (which shall not be logged anymore) + if (event->GetCategory() == EventDefinitions::EventCategory::OpenSCENARIO || + event->GetCategory() == EventDefinitions::EventCategory::OpenPASS) + { + Log(event); + } } void EventNetwork::ClearActiveEvents() { - for(std::pair<EventCategory, std::list<std::shared_ptr<EventInterface>>> eventMapEntry : activeEvents) + for (std::pair<EventCategory, std::list<std::shared_ptr<EventInterface>>> eventMapEntry : activeEvents) { - if(archivedEvents.find(eventMapEntry.first) != archivedEvents.end()) + if (archivedEvents.find(eventMapEntry.first) != archivedEvents.end()) { std::list<std::shared_ptr<EventInterface>> *eventList = &(archivedEvents.at(eventMapEntry.first)); eventList->insert(eventList->end(), eventMapEntry.second.begin(), eventMapEntry.second.end()); @@ -90,7 +119,7 @@ void EventNetwork::Clear() void EventNetwork::AddCollision(const int agentId) { - if(runResult != nullptr) + if (runResult != nullptr) { runResult->AddCollisionId(agentId); } diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetwork.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetwork.h index 6906361a8b84ae6611e8780f74901f98ab879afa..be2b640305e0a568ba6329c84215c1e16871872a 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetwork.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetwork.h @@ -25,18 +25,17 @@ #include <map> #include <vector> -#include "Common/conditionalEvent.h" -#include "Common/componentStateChangeEvent.h" -#include "Common/componentWarningEvent.h" #include "Common/collisionEvent.h" +#include "Common/componentStateChangeEvent.h" +#include "Common/conditionalEvent.h" #include "Common/laneChangeEvent.h" #include "Common/vehicleComponentEvent.h" #include "Interfaces/eventNetworkInterface.h" #include "Interfaces/runResultInterface.h" #include "Interfaces/worldInterface.h" +#include "eventNetworkDataPublisher.h" -namespace SimulationSlave -{ +namespace SimulationSlave { using namespace EventDefinitions; //----------------------------------------------------------------------------- @@ -44,32 +43,34 @@ using namespace EventDefinitions; * * \ingroup EventNetwork */ //----------------------------------------------------------------------------- -class EventNetwork : public EventNetworkInterface +class EventNetwork final : public EventNetworkInterface { public: - EventNetwork() = default; - virtual ~EventNetwork() override = default; + EventNetwork(DataStoreWriteInterface *const dataStore) : + publisher{dataStore} + { + } /*! * \brief Returns the activeEvents. * * @return Map of activ events. */ - virtual Events *GetActiveEvents(); + virtual Events *GetActiveEvents() override; /*! * \brief Returns the archivedEvents. * * @return Map of archived events. */ - virtual Events *GetArchivedEvents(); + virtual Events *GetArchivedEvents() override; /*! * \brief Returns the active events of a specific category. * * @return List of active events. */ - virtual EventContainer GetActiveEventCategory(const EventCategory eventCategory); + virtual EventContainer GetActiveEventCategory(const EventCategory eventCategory) override; /*! * \brief Removes archived events which are older than a certain time stamp. @@ -79,7 +80,7 @@ public: * * @param[in] time Time stamp. */ - virtual void RemoveOldEvents(int time); + virtual void RemoveOldEvents(int time) override; /*! * \brief Inserts an event into the activeEvents. @@ -89,7 +90,7 @@ public: * * @param[in] event Shared pointer of the event. */ - virtual void InsertEvent(std::shared_ptr<EventInterface> event); + virtual void InsertEvent(std::shared_ptr<EventInterface> event) override; /*! * \brief Empties the active events map and stores them as archived events. @@ -97,12 +98,12 @@ public: * \details Empties the current active events and inserts them into the archived events. * This method gets called once per cycle time. */ - virtual void ClearActiveEvents(); + virtual void ClearActiveEvents() override; /*! * \brief Clears the event maps and resets pointers. */ - virtual void Clear(); + virtual void Clear() override; /*! * \brief Adds a collision id to the RunResult @@ -112,7 +113,7 @@ public: * * @param[in] agentId Id of the collision agent */ - virtual void AddCollision(const int agentId); + virtual void AddCollision(const int agentId) override; /*! * \brief Initalizes the EventNetwork @@ -122,15 +123,22 @@ public: * * @param[in] runResult Pointer to the runResult. */ - void Initialize(RunResultInterface *runResult); + virtual void Initialize(RunResultInterface *runResult) override; + + /*! + * \brief Publishes the event for logging + * \param[in] event + */ + void Log(const std::shared_ptr<EventInterface> &event); private: + openpass::publisher::EventNetworkDataPublisher publisher; + Events activeEvents; Events archivedEvents; - RunResultInterface *runResult {nullptr}; + RunResultInterface *runResult{nullptr}; - int eventId {0}; + int eventId{0}; }; } //namespace SimulationSlave - diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetworkDataPublisher.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetworkDataPublisher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b1095e7263a07d4b5dc442d5d6f28a7a1aa98ee --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetworkDataPublisher.cpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#include "eventNetworkDataPublisher.h" + +#include "scheduler/timeKeeper.h" + +namespace openpass::publisher { + +void EventNetworkDataPublisher::Publish(const openpass::narrator::EventBase &event) +{ + dataStore->PutAcyclic(openpass::scheduling::TimeKeeper::Now(), openpass::type::CoreId, event.name, Acyclic(event)); +} + +} // namespace openpass::publisher diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetworkDataPublisher.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetworkDataPublisher.h new file mode 100644 index 0000000000000000000000000000000000000000..847102ed3ce76b87601d1cb8ec6e642f2d66d02e --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/eventNetworkDataPublisher.h @@ -0,0 +1,52 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#pragma once + +#include "Interfaces/publisherInterface.h" + +namespace openpass::narrator { + +class Event : public EventBase +{ +public: + Event(std::string name) : + EventBase(std::move(name)) + { + } + + explicit operator Acyclic() const noexcept override + { + return Acyclic(name, triggeringEntities, affectedEntities, parameter); + } + + // Events shall have it's own specialized members (e.g. TrajectoryFile for TrajectoryEvents) + // Once we need it as acyclic, we convert it properly + // Right now, this is not possible, as we internally use the "old" EventInterface + [[deprecated("will be replaced by specializations of the type")]] openpass::datastore::Parameter parameter; +}; + +} // namespace openpass::narrator + +namespace openpass::publisher { + +///! Interface which has to be provided by observation modules +class EventNetworkDataPublisher : public PublisherInterface +{ +public: + EventNetworkDataPublisher(DataStoreWriteInterface *const dataStore) : + PublisherInterface(dataStore) + { + } + + void Publish(const openpass::narrator::EventBase &event) override; +}; + +} // namespace openpass::publisher diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/frameworkModuleContainer.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/frameworkModuleContainer.cpp index ed42be03ccbf024cef8a04f4797024906cfe92f0..5593637c1e05468ffb0183d09886764c6597c419 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/frameworkModuleContainer.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/frameworkModuleContainer.cpp @@ -8,82 +8,91 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -#include "frameworkModules.h" #include "frameworkModuleContainer.h" +#include "frameworkModules.h" + namespace SimulationSlave { FrameworkModuleContainer::FrameworkModuleContainer( FrameworkModules frameworkModules, - ConfigurationContainerInterface* configurationContainer, - const openpass::common::RuntimeInformation& runtimeInformation, - CallbackInterface* callbacks) : - stochasticsBinding(callbacks), - stochastics(&stochasticsBinding), - worldBinding(frameworkModules.worldLibrary, callbacks, &stochastics), - world(&worldBinding), - observationNetwork(&observationBindings), - eventDetectorBinding(callbacks), - eventDetectorNetwork(&eventDetectorBinding, &world), - manipulatorBinding(callbacks), - manipulatorNetwork(&manipulatorBinding, &world), - modelBinding(frameworkModules.libraryDir, runtimeInformation, callbacks), - agentFactory(&modelBinding, &world, &stochastics, &observationNetwork, &eventNetwork), - agentBlueprintProvider(configurationContainer, stochastics), - eventNetwork(), - spawnPointNetwork(&spawnPointBindings, &world, runtimeInformation) + ConfigurationContainerInterface *configurationContainer, + const openpass::common::RuntimeInformation &runtimeInformation, + CallbackInterface *callbacks) : + dataStoreBinding(frameworkModules.dataStoreLibrary, runtimeInformation, callbacks), + dataStore(&dataStoreBinding), + stochasticsBinding(callbacks), + stochastics(&stochasticsBinding), + worldBinding(frameworkModules.worldLibrary, callbacks, &stochastics), + world(&worldBinding), + observationNetwork(&observationBindings), + eventDetectorBinding(callbacks), + eventDetectorNetwork(&eventDetectorBinding, &world), + manipulatorBinding(callbacks), + manipulatorNetwork(&manipulatorBinding, &world), + modelBinding(frameworkModules.libraryDir, runtimeInformation, callbacks), + agentFactory(&modelBinding, &world, &stochastics, &observationNetwork, &eventNetwork, &dataStore), + agentBlueprintProvider(configurationContainer, stochastics), + eventNetwork(&dataStore), + spawnPointNetwork(&spawnPointBindings, &world, runtimeInformation) { - for(const auto& libraryInfo : frameworkModules.spawnPointLibraries) + for (const auto &libraryInfo : frameworkModules.spawnPointLibraries) { spawnPointBindings.emplace(libraryInfo.libraryName, SpawnPointBinding(callbacks)); } - for(const auto& libraryInfo : frameworkModules.observationLibraries) + + for (const auto& libraryInfo : frameworkModules.observationLibraries) { observationBindings.emplace(libraryInfo.libraryName, ObservationBinding(runtimeInformation, callbacks)); } } -AgentFactoryInterface* FrameworkModuleContainer::GetAgentFactory() +AgentBlueprintProviderInterface *FrameworkModuleContainer::GetAgentBlueprintProvider() +{ + return &agentBlueprintProvider; +} + +AgentFactoryInterface *FrameworkModuleContainer::GetAgentFactory() { return &agentFactory; } -AgentBlueprintProviderInterface* FrameworkModuleContainer::GetAgentBlueprintProvider() +DataStoreInterface *FrameworkModuleContainer::GetDataStore() { - return &agentBlueprintProvider; + return &dataStore; } -EventDetectorNetworkInterface* FrameworkModuleContainer::GetEventDetectorNetwork() +EventDetectorNetworkInterface *FrameworkModuleContainer::GetEventDetectorNetwork() { return &eventDetectorNetwork; } -EventNetworkInterface* FrameworkModuleContainer::GetEventNetwork() +EventNetworkInterface *FrameworkModuleContainer::GetEventNetwork() { return &eventNetwork; } -ManipulatorNetworkInterface* FrameworkModuleContainer::GetManipulatorNetwork() +ManipulatorNetworkInterface *FrameworkModuleContainer::GetManipulatorNetwork() { return &manipulatorNetwork; } -ObservationNetworkInterface* FrameworkModuleContainer::GetObservationNetwork() +ObservationNetworkInterface *FrameworkModuleContainer::GetObservationNetwork() { return &observationNetwork; } -SpawnPointNetworkInterface* FrameworkModuleContainer::GetSpawnPointNetwork() +SpawnPointNetworkInterface *FrameworkModuleContainer::GetSpawnPointNetwork() { return &spawnPointNetwork; } -StochasticsInterface* FrameworkModuleContainer::GetStochastics() +StochasticsInterface *FrameworkModuleContainer::GetStochastics() { return &stochastics; } -WorldInterface* FrameworkModuleContainer::GetWorld() +WorldInterface *FrameworkModuleContainer::GetWorld() { return &world; } diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/frameworkModuleContainer.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/frameworkModuleContainer.h index b50b24b02ea56870de8029ef25d4e8fe1f6e8e53..bcae28bbc69c5dcd13be27cd33ce0af8b9a738d6 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/frameworkModuleContainer.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/frameworkModuleContainer.h @@ -16,11 +16,13 @@ #pragma once -#include "worldInterface/world.h" +#include "Interfaces/agentBlueprintInterface.h" +#include "Interfaces/configurationContainerInterface.h" #include "Interfaces/frameworkModuleContainerInterface.h" - -#include "agentFactory.h" #include "agentBlueprintProvider.h" +#include "agentFactory.h" +#include "dataStore.h" +#include "dataStoreInterface/dataStoreBinding.h" #include "directories.h" #include "eventDetectorInterface/eventDetectorBinding.h" #include "eventDetectorNetwork.h" @@ -35,53 +37,40 @@ #include "spawnPointNetwork.h" #include "stochasticsInterface/stochastics.h" #include "stochasticsInterface/stochasticsBinding.h" - -#include "Interfaces/agentBlueprintInterface.h" -#include "Interfaces/configurationContainerInterface.h" +#include "worldInterface/world.h" namespace SimulationSlave { -//----------------------------------------------------------------------------- -/** \brief This class instantiates and stores all core framework modules -* \details -*/ -//----------------------------------------------------------------------------- -class FrameworkModuleContainer : public FrameworkModuleContainerInterface +class FrameworkModuleContainer final : public FrameworkModuleContainerInterface { public: FrameworkModuleContainer(FrameworkModules frameworkModules, - ConfigurationContainerInterface* configurationContainer, - const openpass::common::RuntimeInformation& runtimeInformation, - CallbackInterface* callbacks); - - virtual ~FrameworkModuleContainer() override = default; - - AgentFactoryInterface* GetAgentFactory() override; - - EventDetectorNetworkInterface* GetEventDetectorNetwork() override; - - EventNetworkInterface* GetEventNetwork() override; - - ManipulatorNetworkInterface* GetManipulatorNetwork() override; - - ObservationNetworkInterface* GetObservationNetwork() override; - - SpawnPointNetworkInterface* GetSpawnPointNetwork() override; - - StochasticsInterface* GetStochastics() override; - - WorldInterface* GetWorld() override; - - AgentBlueprintProviderInterface* GetAgentBlueprintProvider() override; + ConfigurationContainerInterface *configurationContainer, + const openpass::common::RuntimeInformation &runtimeInformation, + CallbackInterface *callbacks); + + AgentBlueprintProviderInterface *GetAgentBlueprintProvider() override; + AgentFactoryInterface *GetAgentFactory() override; + DataStoreInterface *GetDataStore() override; + EventDetectorNetworkInterface *GetEventDetectorNetwork() override; + EventNetworkInterface *GetEventNetwork() override; + ManipulatorNetworkInterface *GetManipulatorNetwork() override; + ObservationNetworkInterface *GetObservationNetwork() override; + SpawnPointNetworkInterface *GetSpawnPointNetwork() override; + StochasticsInterface *GetStochastics() override; + WorldInterface *GetWorld() override; private: + DataStoreBinding dataStoreBinding; + DataStore dataStore; + StochasticsBinding stochasticsBinding; Stochastics stochastics; WorldBinding worldBinding; World world; - std::map<std::string, ObservationBinding> observationBindings {}; + std::map<std::string, ObservationBinding> observationBindings; ObservationNetwork observationNetwork; EventDetectorBinding eventDetectorBinding; @@ -98,7 +87,7 @@ private: EventNetwork eventNetwork; - std::map<std::string, SpawnPointBinding> spawnPointBindings {}; + std::map<std::string, SpawnPointBinding> spawnPointBindings; SpawnPointNetwork spawnPointNetwork; }; diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/main.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/main.cpp index 36e4afcdc197eb329f3d83b90ed4de3f42f2c205..9c66427c936223f734240cf277dfb0035257785e 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/main.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/main.cpp @@ -111,6 +111,7 @@ int main(int argc, char* argv[]) { parsedArguments.logLevel, directories.libraryDir, + libraries.at("DataStoreLibrary"), libraries.at("EventDetectorLibrary"), libraries.at("ManipulatorLibrary"), configurationContainer.GetSlaveConfig()->GetObservationConfig(), diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/observationNetwork.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/observationNetwork.cpp index 78da753fc15459a71335a3cbcb9984341987db6a..cc1a946ea439754ff11dafd0b5108c2c33cac7c4 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/observationNetwork.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/observationNetwork.cpp @@ -42,7 +42,8 @@ bool ObservationNetwork::Instantiate(const ObservationInstanceCollection& observ StochasticsInterface* stochastics, WorldInterface* world, EventNetworkInterface* eventNetwork, - const std::string& sceneryPath) + const std::string& sceneryPath, + DataStoreReadInterface* dataStore) { for (auto& observationInstance : observationInstances) { @@ -57,13 +58,13 @@ bool ObservationNetwork::Instantiate(const ObservationInstanceCollection& observ auto& binding = bindingIter->second; openpass::parameter::ParameterSetLevel1 parameters{observationInstance.parameters}; - parameters.push_back({"SceneryFile", sceneryPath}); //Hotfix until sceneryPath is observable auto module = binding.Instantiate(observationInstance.libraryName, parameters, stochastics, world, - eventNetwork); + eventNetwork, + dataStore); modules.insert({observationInstance.id, module}); } diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/observationNetwork.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/observationNetwork.h index d247615fc984078248b1c40919eccba46287cbdb..40f1503bfd1f54f8fe35bb867745d89336ff4a44 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/observationNetwork.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/observationNetwork.h @@ -46,7 +46,8 @@ public: StochasticsInterface* stochastics, WorldInterface* world, EventNetworkInterface* eventNetwork, - const std::string& sceneryPath) override; + const std::string& sceneryPath, + DataStoreReadInterface* dataStore) override; virtual const std::map<int, ObservationModule*>& GetObservationModules() override; virtual bool InitAll() override; diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/runInstantiator.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/runInstantiator.cpp index e3655b50fd27cf6daa26380134c6b87b053dea27..e7a7371bf69bdc9ceb29a8814de92b9c5bfa5d69 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/runInstantiator.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/runInstantiator.cpp @@ -9,23 +9,25 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ +#include "runInstantiator.h" + #include <functional> #include <sstream> -#include "agentFactory.h" +#include "CoreFramework/CoreShare/log.h" #include "Interfaces/agentBlueprintProviderInterface.h" +#include "Interfaces/observationNetworkInterface.h" +#include "agentFactory.h" #include "agentType.h" #include "channel.h" #include "component.h" -#include "CoreFramework/CoreShare/log.h" -#include "Interfaces/observationNetworkInterface.h" +#include "dataStore.h" #include "observationModule.h" -#include "runInstantiator.h" +#include "parameters.h" #include "runResult.h" #include "scheduler.h" #include "spawnPointNetwork.h" #include "stochastics.h" -#include "parameters.h" #include "parameterbuilder.h" #include "sampler.h" @@ -35,53 +37,64 @@ namespace SimulationSlave { bool RunInstantiator::ExecuteRun() { - LOG_INTERN(LogLevel::DebugCore) << std::endl << "### execute run ###"; + LOG_INTERN(LogLevel::DebugCore) << std::endl + << "### execute run ###"; stopMutex.lock(); stopped = false; stopMutex.unlock(); - auto& scenario = *configurationContainer.GetScenario(); - auto& scenery = *configurationContainer.GetScenery(); - auto& slaveConfig = *configurationContainer.GetSlaveConfig(); - auto& experimentConfig = slaveConfig.GetExperimentConfig(); - auto& environmentConfig = slaveConfig.GetEnvironmentConfig(); + auto &scenario = *configurationContainer.GetScenario(); + auto &scenery = *configurationContainer.GetScenery(); + auto &slaveConfig = *configurationContainer.GetSlaveConfig(); + auto &experimentConfig = slaveConfig.GetExperimentConfig(); + auto &environmentConfig = slaveConfig.GetEnvironmentConfig(); if (!InitPreRun(scenario, scenery)) { - LOG_INTERN(LogLevel::DebugCore) << std::endl << "### initialization failed ###"; + LOG_INTERN(LogLevel::DebugCore) << std::endl + << "### initialization failed ###"; return false; } - Scheduler scheduler(world, spawnPointNetwork, eventDetectorNetwork, manipulatorNetwork, observationNetwork); - bool scheduler_state { false }; + dataStore.PutStatic("SceneryFile", scenario.GetSceneryPath(), true); + ThrowIfFalse(observationNetwork.InitAll(), "Failed to initialize ObservationNetwork"); + + openpass::scheduling::Scheduler scheduler(world, spawnPointNetwork, eventDetectorNetwork, manipulatorNetwork, observationNetwork); + bool scheduler_state{false}; for (auto invocation = 0; invocation < experimentConfig.numberOfInvocations; invocation++) { RunResult runResult; - LOG_INTERN(LogLevel::DebugCore) << std::endl << "### run number: " << invocation << " ###"; + LOG_INTERN(LogLevel::DebugCore) << std::endl + << "### run number: " << invocation << " ###"; auto seed = static_cast<std::uint32_t>(experimentConfig.randomSeed + invocation); if (!InitRun(seed, environmentConfig, runResult)) { - LOG_INTERN(LogLevel::DebugCore) << std::endl << "### run initialization failed ###"; + LOG_INTERN(LogLevel::DebugCore) << std::endl + << "### run initialization failed ###"; break; } - LOG_INTERN(LogLevel::DebugCore) << std::endl << "### run started ###"; + LOG_INTERN(LogLevel::DebugCore) << std::endl + << "### run started ###"; scheduler_state = scheduler.Run(0, scenario.GetEndTime(), runResult, eventNetwork); - if (scheduler_state == Scheduler::FAILURE) + if (scheduler_state == openpass::scheduling::Scheduler::FAILURE) { - LOG_INTERN(LogLevel::DebugCore) << std::endl << "### run aborted ###"; + LOG_INTERN(LogLevel::DebugCore) << std::endl + << "### run aborted ###"; break; } - LOG_INTERN(LogLevel::DebugCore) << std::endl << "### run successful ###"; + LOG_INTERN(LogLevel::DebugCore) << std::endl + << "### run successful ###"; observationNetwork.FinalizeRun(runResult); ClearRun(); } - LOG_INTERN(LogLevel::DebugCore) << std::endl << "### end of all runs ###"; + LOG_INTERN(LogLevel::DebugCore) << std::endl + << "### end of all runs ###"; bool observations_state = observationNetwork.FinalizeAll(); return (scheduler_state && observations_state); @@ -95,18 +108,22 @@ bool RunInstantiator::InitPreRun(ScenarioInterface& scenario, SceneryInterface& world.CreateScenery(&scenery); return true; } - catch(const std::exception& error) + catch (const std::exception &error) { - LOG_INTERN(LogLevel::Error) << std::endl << "### could not init: " << error.what() << "###"; + LOG_INTERN(LogLevel::Error) << std::endl + << "### could not init: " << error.what() << "###"; return false; } - LOG_INTERN(LogLevel::Error) << std::endl << "### exception caught, which is not of type std::exception! ###"; + LOG_INTERN(LogLevel::Error) << std::endl + << "### exception caught, which is not of type std::exception! ###"; return false; } void RunInstantiator::InitializeFrameworkModules(ScenarioInterface& scenario) { + ThrowIfFalse(dataStore.Instantiate(), + "Failed to instantiate DataStore"); ThrowIfFalse(stochastics.Instantiate(frameworkModules.stochasticsLibrary), "Failed to instantiate Stochastics"); ThrowIfFalse(world.Instantiate(), @@ -115,10 +132,8 @@ void RunInstantiator::InitializeFrameworkModules(ScenarioInterface& scenario) "Failed to instantiate EventDetectorNetwork"); ThrowIfFalse(manipulatorNetwork.Instantiate(frameworkModules.manipulatorLibrary, &scenario, &eventNetwork), "Failed to instantiate ManipulatorNetwork"); - ThrowIfFalse(observationNetwork.Instantiate(frameworkModules.observationLibraries, &stochastics, &world, &eventNetwork, scenario.GetSceneryPath()), + ThrowIfFalse(observationNetwork.Instantiate(frameworkModules.observationLibraries, &stochastics, &world, &eventNetwork, scenario.GetSceneryPath(), &dataStore), "Failed to instantiate ObservationNetwork"); - ThrowIfFalse(observationNetwork.InitAll(), - "Failed to initialize ObservationNetwork"); } void RunInstantiator::InitializeSpawnPointNetwork() @@ -127,11 +142,12 @@ void RunInstantiator::InitializeSpawnPointNetwork() bool existingSpawnProfiles = profileGroups.find(SPAWNER) != profileGroups.end(); ThrowIfFalse(spawnPointNetwork.Instantiate(frameworkModules.spawnPointLibraries, - &agentFactory, - &agentBlueprintProvider, - &stochastics, - configurationContainer.GetScenario(), - existingSpawnProfiles ? std::make_optional(profileGroups.at(SPAWNER)) : std::nullopt), "Failed to instantiate SpawnPointNetwork"); + &agentFactory, + &agentBlueprintProvider, + &stochastics, + configurationContainer.GetScenario(), + existingSpawnProfiles ? std::make_optional(profileGroups.at(SPAWNER)) : std::nullopt), + "Failed to instantiate SpawnPointNetwork"); } std::unique_ptr<ParameterInterface> RunInstantiator::SampleWorldParameters(const EnvironmentConfig& environmentConfig, StochasticsInterface* stochastics, const openpass::common::RuntimeInformation& runtimeInformation) @@ -144,8 +160,7 @@ std::unique_ptr<ParameterInterface> RunInstantiator::SampleWorldParameters(const { "Weather", Sampler::Sample(environmentConfig.weathers, stochastics) }} ); } - -bool RunInstantiator::InitRun(std::uint32_t seed, const EnvironmentConfig& environmentConfig, RunResult& runResult) +bool RunInstantiator::InitRun(std::uint32_t seed, const EnvironmentConfig &environmentConfig, RunResult &runResult) { try { @@ -160,13 +175,15 @@ bool RunInstantiator::InitRun(std::uint32_t seed, const EnvironmentConfig& envir eventNetwork.Initialize(&runResult); return true; } - catch(const std::exception& error) + catch (const std::exception &error) { - LOG_INTERN(LogLevel::Error) << std::endl << "### could not init run: " << error.what() << "###"; + LOG_INTERN(LogLevel::Error) << std::endl + << "### could not init run: " << error.what() << "###"; return false; } - LOG_INTERN(LogLevel::Error) << std::endl << "### exception caught, which is not of type std::exception! ###"; + LOG_INTERN(LogLevel::Error) << std::endl + << "### exception caught, which is not of type std::exception! ###"; return false; } @@ -177,6 +194,7 @@ void RunInstantiator::ClearRun() spawnPointNetwork.Clear(); eventNetwork.Clear(); eventDetectorNetwork.ResetAll(); + dataStore.Clear(); } } // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/runInstantiator.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/runInstantiator.h index 70d0b47a75b9d3ecaf5eee6b67df7cb0125d8455..fc5ce093e4b177f6f1d4cb391e5b97020c7e87f2 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/runInstantiator.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/framework/runInstantiator.h @@ -16,15 +16,19 @@ #pragma once -#include <string> -#include <map> #include <QMutex> + +#include <map> +#include <string> + #include "frameworkModules.h" + #include "Interfaces/agentFactoryInterface.h" #include "Interfaces/configurationContainerInterface.h" -#include "Interfaces/parameterInterface.h" +#include "Interfaces/dataStoreInterface.h" #include "Interfaces/frameworkModuleContainerInterface.h" #include "Interfaces/observationNetworkInterface.h" +#include "Interfaces/parameterInterface.h" #include "Interfaces/stochasticsInterface.h" namespace SimulationSlave { @@ -45,6 +49,7 @@ public: stochastics(*frameworkModuleContainer.GetStochastics()), eventDetectorNetwork(*frameworkModuleContainer.GetEventDetectorNetwork()), manipulatorNetwork(*frameworkModuleContainer.GetManipulatorNetwork()), + dataStore(*frameworkModuleContainer.GetDataStore()), frameworkModules{frameworkModules} {} @@ -100,11 +105,10 @@ private: StochasticsInterface& stochastics; EventDetectorNetworkInterface& eventDetectorNetwork; ManipulatorNetworkInterface& manipulatorNetwork; + DataStoreInterface& dataStore; FrameworkModules& frameworkModules; - std::unique_ptr<ParameterInterface> worldParameter {nullptr}; + std::unique_ptr<ParameterInterface> worldParameter; }; } // namespace SimulationSlave - - diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/eventDetectorImporter.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/eventDetectorImporter.cpp index d2716458804ad608262cecc9e8c35049f1911ab7..85ebdadcbe98da70efeaac88378cd0a917022b03 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/eventDetectorImporter.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/eventDetectorImporter.cpp @@ -16,39 +16,39 @@ namespace ATTRIBUTE = openpass::importer::xml::eventDetectorImporter::attribute; namespace Importer { - openScenario::ConditionalEventDetectorInformation EventDetectorImporter::ImportEventDetector(QDomElement& eventElement, - const std::string& eventName, - const int numberOfExecutions, - const openScenario::ActorInformation& actorInformation, - const std::vector<ScenarioEntity>& entities, - openScenario::Parameters& parameters) - { - QDomElement startConditionsElement; - ThrowIfFalse(SimulationCommon::GetFirstChildElement(eventElement, TAG::startConditions, startConditionsElement), - eventElement, "Tag " + std::string(TAG::startConditions) + " missing."); +openScenario::ConditionalEventDetectorInformation EventDetectorImporter::ImportEventDetector(QDomElement &eventElement, + const std::string &eventName, + const int numberOfExecutions, + const openScenario::ActorInformation &actorInformation, + const std::vector<ScenarioEntity> &entities, + openScenario::Parameters& parameters) +{ + QDomElement startConditionsElement; + ThrowIfFalse(SimulationCommon::GetFirstChildElement(eventElement, TAG::startConditions, startConditionsElement), + eventElement, "Tag " + std::string(TAG::startConditions) + " missing."); - QDomElement conditionGroupElement; - ThrowIfFalse(SimulationCommon::GetFirstChildElement(startConditionsElement, TAG::conditionGroup, conditionGroupElement), - startConditionsElement, "Tag " + std::string(TAG::conditionGroup) + " missing."); + QDomElement conditionGroupElement; + ThrowIfFalse(SimulationCommon::GetFirstChildElement(startConditionsElement, TAG::conditionGroup, conditionGroupElement), + startConditionsElement, "Tag " + std::string(TAG::conditionGroup) + " missing."); - QDomElement conditionElement; - ThrowIfFalse(SimulationCommon::GetFirstChildElement(conditionGroupElement, TAG::condition, conditionElement), - conditionGroupElement, "Tag " + std::string(TAG::condition) + " missing."); + QDomElement conditionElement; + ThrowIfFalse(SimulationCommon::GetFirstChildElement(conditionGroupElement, TAG::condition, conditionElement), + conditionGroupElement, "Tag " + std::string(TAG::condition) + " missing."); - openScenario::ConditionCollection conditions{}; + openScenario::ConditionCollection conditions{}; - while (!conditionElement.isNull()) - { - conditions.emplace_back(ImportConditionElement(conditionElement, entities, parameters)); - conditionElement = conditionElement.nextSiblingElement(TAG::condition); - } - - return openScenario::ConditionalEventDetectorInformation{actorInformation, - numberOfExecutions, - eventName, - conditions}; + while (!conditionElement.isNull()) + { + conditions.emplace_back(ImportConditionElement(conditionElement, entities, parameters)); + conditionElement = conditionElement.nextSiblingElement(TAG::condition); } + return openScenario::ConditionalEventDetectorInformation{actorInformation, + numberOfExecutions, + eventName, + conditions}; +} + openScenario::Condition EventDetectorImporter::ImportConditionElement(QDomElement& conditionElement, const std::vector<ScenarioEntity>& entities, openScenario::Parameters& parameters) diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/eventDetectorImporter.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/eventDetectorImporter.h index 8bd7c9161e31aeaa4904db0bff9826dc31936270..5a393b625d8a79fa898352db7b656ac675897c15 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/eventDetectorImporter.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/eventDetectorImporter.h @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2017, 2019, 2020 in-tech GmbH * * This program and the accompanying materials are made @@ -38,30 +38,30 @@ public: * \brief ImportEventDetector parses information from an EventElement for * instantiation of a ConditionalEventDetector. * - * \param[in] eventElement the element from which to parse - * ConditionalEventDetector instantiation - * information - * \param[in] eventName the name of the event to which the - * ConditionalEventDetector will belong + * \param[in] eventElement the element from which to parse + * ConditionalEventDetector instantiation + * information + * \param[in] eventName Name of the event used for identification + * e.g. "MyStory/MyAct/MySequence/MyManeuver/MyEvent" * \param[in] numberOfExecutions the maximum number of times the * ConditionalEventDetector is to emit an * event - * \param[in] actorInformation information detailing what entities are the - * actors to be targeted by the - * ConditionalEventDetector's emitted events - * \param[in] entities the entities explicitly defined in the openScenario - * file's Entities element + * \param[in] actorInformation information detailing what entities are the + * actors to be targeted by the + * ConditionalEventDetector's emitted events + * \param[in] entities entities defined in openScenario Entities * * \return a struct containing all information relevant for the * instantiation of a ConditionalEventDetector * ------------------------------------------------------------------------ */ - static openScenario::ConditionalEventDetectorInformation ImportEventDetector(QDomElement& eventElement, + static openScenario::ConditionalEventDetectorInformation ImportEventDetector(QDomElement &eventElement, const std::string &eventName, const int numberOfExecutions, - const openScenario::ActorInformation& actorInformation, + const openScenario::ActorInformation &actorInformation, const std::vector<ScenarioEntity>& entities, openScenario::Parameters& parameters); + private: /*! * \brief Imports a condition element of a OpenSCENARIO storyboard DOM diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/frameworkModules.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/frameworkModules.h index b777f112868e1761bd1b3fa2cc957d71a70e2f7a..0bc0dc9cbd57bd7c384138279d06142262daf7b9 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/frameworkModules.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/frameworkModules.h @@ -46,6 +46,7 @@ struct FrameworkModules public: FrameworkModules(const int logLevel, const std::string& libraryDir, + const std::string& dataStoreLibrary, const std::string& eventDetectorLibrary, const std::string& manipulatorLibrary, const ObservationInstanceCollection& observationLibraries, @@ -54,6 +55,7 @@ public: const SpawnPointLibraryInfoCollection& spawnPointLibraries) : logLevel{logLevel}, libraryDir{libraryDir}, + dataStoreLibrary{openpass::core::Directories::Concat(libraryDir, dataStoreLibrary)}, eventDetectorLibrary{openpass::core::Directories::Concat(libraryDir, eventDetectorLibrary)}, manipulatorLibrary{openpass::core::Directories::Concat(libraryDir, manipulatorLibrary)}, observationLibraries{ConcatenateObservationLibraries(libraryDir, observationLibraries)}, @@ -64,6 +66,7 @@ public: const int logLevel; const std::string libraryDir; + const std::string dataStoreLibrary; const std::string eventDetectorLibrary; const std::string manipulatorLibrary; const ObservationInstanceCollection observationLibraries; diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/importerLoggingHelper.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/importerLoggingHelper.h index 6c0d9e11f30ea65fd1971725cd7fb540446c0225..f4b3f6d4e7ff8fed71b6486d0ca46e5e2cb6ef12 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/importerLoggingHelper.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/importerLoggingHelper.h @@ -98,6 +98,7 @@ namespace openpass::importer::xml::parameterImporter::tag constexpr char Int[] {"Int"}; constexpr char IntVector[] {"IntVector"}; constexpr char String[] {"String"}; + constexpr char StringVector[] {"StringVector"}; constexpr char NormalDistribution[] {"NormalDistribution"}; constexpr char LogNormalDistribution[] {"LogNormalDistribution"}; @@ -354,33 +355,24 @@ namespace openpass::importer::xml::sceneryImporter::attribute namespace openpass::importer::xml::slaveConfigImporter::tag { - constexpr char agentProfile[] {"AgentProfile"}; - constexpr char environmentConfig[] {"EnvironmentConfig"}; - constexpr char experimentConfig[] {"ExperimentConfig"}; + constexpr char environment[] {"Environment"}; + constexpr char experiment[] {"Experiment"}; constexpr char friction[] {"Friction"}; constexpr char frictions[] {"Frictions"}; constexpr char homogenities[] {"Homogenities"}; constexpr char homogenity[] {"Homogenity"}; constexpr char libraries[] {"Libraries"}; constexpr char library[] {"Library"}; - constexpr char loggingGroup[] {"LoggingGroup"}; - constexpr char loggingGroups[] {"LoggingGroups"}; - constexpr char platoonRate[] {"PlatoonRate"}; - constexpr char platoonRates[] {"PlatoonRates"}; + constexpr char observation[] {"Observation"}; + constexpr char observations[] {"Observations"}; + constexpr char parameters[] {"Parameters"}; constexpr char priority[] {"Priority"}; - constexpr char regularLane[] {"RegularLane"}; - constexpr char rightMostLane[] {"RightMostLane"}; - constexpr char scenarioConfig[] {"ScenarioConfig"}; - constexpr char spawnPoint[] {"SpawnPoint"}; + constexpr char scenario[] {"Scenario"}; + constexpr char spawner[] {"Spawner"}; + constexpr char spawners[] {"Spawners"}; constexpr char timeOfDay[] {"TimeOfDay"}; constexpr char timeOfDays[] {"TimeOfDays"}; - constexpr char trafficConfig[] {"TrafficConfig"}; - constexpr char trafficParameter[] {"TrafficParameter"}; - constexpr char trafficVolume[] {"TrafficVolume"}; - constexpr char trafficVolumes[] {"TrafficVolumes"}; constexpr char type[] {"Type"}; - constexpr char velocities[] {"Velocities"}; - constexpr char velocity[] {"Velocity"}; constexpr char visibilityDistance[] {"VisibilityDistance"}; constexpr char visibilityDistances[] {"VisibilityDistances"}; constexpr char weather[] {"Weather"}; diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/parameterImporter.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/parameterImporter.cpp index f8772ef673926adde9d24697d8a6766aa716e651..1734f0470db61eea364e0289dacc3bf037d1086e 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/parameterImporter.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/parameterImporter.cpp @@ -22,7 +22,7 @@ namespace openpass::parameter::internal { using namespace SimulationCommon; template <typename T> -ParameterSetLevel3 ImportParameter(QDomElement& domElement, const std::string& elementName) +ParameterSetLevel3 ImportParameter(const QDomElement& domElement, const std::string& elementName) { ParameterSetLevel3 param; @@ -48,7 +48,7 @@ ParameterSetLevel3 ImportParameter(QDomElement& domElement, const std::string& e } template <> -ParameterSetLevel3 ImportParameter<NormalDistribution>(QDomElement& domElement, const std::string& elementName) +ParameterSetLevel3 ImportParameter<NormalDistribution>(const QDomElement& domElement, const std::string& elementName) { ParameterSetLevel3 param; @@ -85,7 +85,7 @@ ParameterSetLevel3 ImportParameter<NormalDistribution>(QDomElement& domElement, } template <> -ParameterSetLevel3 ImportParameter<LogNormalDistribution>(QDomElement& domElement, const std::string& elementName) +ParameterSetLevel3 ImportParameter<LogNormalDistribution>(const QDomElement& domElement, const std::string& elementName) { ParameterSetLevel3 param; @@ -128,7 +128,7 @@ ParameterSetLevel3 ImportParameter<LogNormalDistribution>(QDomElement& domElemen } template <> -ParameterSetLevel3 ImportParameter<UniformDistribution>(QDomElement& domElement, const std::string& elementName) +ParameterSetLevel3 ImportParameter<UniformDistribution>(const QDomElement& domElement, const std::string& elementName) { ParameterSetLevel3 param; @@ -156,7 +156,7 @@ ParameterSetLevel3 ImportParameter<UniformDistribution>(QDomElement& domElement, } template <> -ParameterSetLevel3 ImportParameter<ExponentialDistribution>(QDomElement& domElement, const std::string& elementName) +ParameterSetLevel3 ImportParameter<ExponentialDistribution>(const QDomElement& domElement, const std::string& elementName) { ParameterSetLevel3 param; @@ -185,7 +185,7 @@ ParameterSetLevel3 ImportParameter<ExponentialDistribution>(QDomElement& domElem return param; } -std::vector<QDomElement> ImportReference(QDomElement& domElement, QDomElement& profilesElement) +std::vector<QDomElement> ImportReference(const QDomElement& domElement, const QDomElement& profilesElement) { std::vector<QDomElement> references; @@ -242,7 +242,7 @@ std::vector<QDomElement> ImportReference(QDomElement& domElement, QDomElement& p return references; } -static ParameterSetLevel3 ImportParameterLevel3WithoutReferences(QDomElement& element) +static ParameterSetLevel3 ImportParameterLevel3WithoutReferences(const QDomElement& element) { ParameterSetLevel3 param; @@ -252,6 +252,7 @@ static ParameterSetLevel3 ImportParameterLevel3WithoutReferences(QDomElement& el auto doubleParams = ImportParameter<double>(element, TAG::Double); auto doubleVectorParams = ImportParameter<std::vector<double>>(element, TAG::DoubleVector); auto stringParams = ImportParameter<std::string>(element, TAG::String); + auto stringVectorParams = ImportParameter<std::vector<std::string>>(element, TAG::StringVector); auto normalDistributionParams = ImportParameter<openpass::parameter::NormalDistribution>(element, TAG::NormalDistribution); auto lognormalDistributionParams = ImportParameter<openpass::parameter::LogNormalDistribution>(element, TAG::LogNormalDistribution); auto uniformDistributionParams = ImportParameter<openpass::parameter::UniformDistribution>(element, TAG::UniformDistribution); @@ -263,6 +264,7 @@ static ParameterSetLevel3 ImportParameterLevel3WithoutReferences(QDomElement& el param.insert(param.end(), doubleParams.begin(), doubleParams.end()); param.insert(param.end(), doubleVectorParams.begin(), doubleVectorParams.end()); param.insert(param.end(), stringParams.begin(), stringParams.end()); + param.insert(param.end(), stringVectorParams.begin(), stringVectorParams.end()); param.insert(param.end(), normalDistributionParams.begin(), normalDistributionParams.end()); param.insert(param.end(), lognormalDistributionParams.begin(), lognormalDistributionParams.end()); param.insert(param.end(), uniformDistributionParams.begin(), uniformDistributionParams.end()); @@ -271,7 +273,7 @@ static ParameterSetLevel3 ImportParameterLevel3WithoutReferences(QDomElement& el return param; } -static ParameterSetLevel3 ImportParameterLevel3(QDomElement& domElement, QDomElement& profilesElement) +static ParameterSetLevel3 ImportParameterLevel3(const QDomElement& domElement, const QDomElement& profilesElement) { ParameterSetLevel3 param; auto elementsToCombine = ImportReference(domElement, profilesElement); @@ -286,7 +288,7 @@ static ParameterSetLevel3 ImportParameterLevel3(QDomElement& domElement, QDomEle return param; } -static ParameterSetLevel2 ImportParameterListsLevel2(QDomElement& parameterElement, QDomElement& profilesElement) +static ParameterSetLevel2 ImportParameterListsLevel2(const QDomElement& parameterElement, const QDomElement& profilesElement) { QDomElement lists; @@ -321,7 +323,7 @@ static ParameterSetLevel2 ImportParameterListsLevel2(QDomElement& parameterEleme return param; } -static ParameterSetLevel2 ImportParameterSetLevel2(QDomElement& parameterElement, QDomElement& profilesElement) +static ParameterSetLevel2 ImportParameterSetLevel2(const QDomElement& parameterElement, const QDomElement& profilesElement) { ParameterSetLevel2 container; @@ -340,7 +342,7 @@ static ParameterSetLevel2 ImportParameterSetLevel2(QDomElement& parameterElement return container; } -static ParameterSetLevel1 ImportParameterListsLevel1(QDomElement& parameterElement, QDomElement& profilesElement) +static ParameterSetLevel1 ImportParameterListsLevel1(const QDomElement& parameterElement, const QDomElement& profilesElement) { QDomElement lists; @@ -380,7 +382,7 @@ static ParameterSetLevel1 ImportParameterListsLevel1(QDomElement& parameterEleme namespace openpass::parameter { -ParameterSetLevel1 Import(QDomElement& parameterElement, QDomElement& profilesElement) +ParameterSetLevel1 Import(const QDomElement& parameterElement, const QDomElement& profilesElement) { openpass::parameter::ParameterSetLevel1 tempContainer; diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/parameterImporter.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/parameterImporter.h index fef45c2072633201ba72373afa045dea9c560a49..48e27adab761cb8c69c0da8a6de12a77ac1149a7 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/parameterImporter.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/parameterImporter.h @@ -16,6 +16,6 @@ namespace openpass::parameter { -ParameterSetLevel1 Import(QDomElement& parameterElement, QDomElement& profilesElement); +ParameterSetLevel1 Import(const QDomElement& parameterElement, const QDomElement& profilesElement); } //namespace openpass::parameter diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/profiles.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/profiles.cpp index 1316e5a8cef7486824329044669278245a36f678..7f21f81d312f79b4cf99811706af8f4cd3f61819 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/profiles.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/profiles.cpp @@ -8,6 +8,8 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ +#include <stdexcept> + #include "profiles.h" std::unordered_map<std::string, AgentProfile>& Profiles::GetAgentProfiles() diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/scenarioImporter.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/scenarioImporter.cpp index 2e0d411ddd7dd85418b1c70516608722dc823398..974101465c73021fd38ed0180066eccbd557267d 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/scenarioImporter.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/scenarioImporter.cpp @@ -24,6 +24,7 @@ #include "xmlParser.h" #include "CoreFramework/CoreShare/log.h" #include "CoreFramework/OpenPassSlave/framework/directories.h" +#include "Common/openPassUtils.h" namespace TAG = openpass::importer::xml::scenarioImporter::tag; namespace ATTRIBUTE = openpass::importer::xml::scenarioImporter::attribute; @@ -155,8 +156,8 @@ void ScenarioImporter::ImportStoryboard(QDomElement& documentRoot, std::vector<S ImportEndConditionsFromStoryboard(storyboardElement, scenario, parameters); } -void ScenarioImporter::ImportStoryElement(QDomElement& storyElement, - const std::vector<ScenarioEntity>& entities, +void ScenarioImporter::ImportStoryElement(QDomElement &storyElement, + const std::vector<ScenarioEntity> &entities, ScenarioInterface* scenario, openScenario::Parameters& parameters) { @@ -164,11 +165,25 @@ void ScenarioImporter::ImportStoryElement(QDomElement& storyElement, QDomElement actElement; if (SimulationCommon::GetFirstChildElement(storyElement, TAG::act, actElement)) { + // Story name is mandatory unless story is empty tag + std::string storyName{}; + ThrowIfFalse(SimulationCommon::ParseAttribute(storyElement, ATTRIBUTE::name, storyName), + storyElement, "Attribute " + std::string(ATTRIBUTE::name) + " is missing."); + while (!actElement.isNull()) { + // Act name is mandatory + std::string actName; + ThrowIfFalse(SimulationCommon::ParseAttribute(actElement, ATTRIBUTE::name, actName), + actElement, "Attribute " + std::string(ATTRIBUTE::name) + " is missing."); + QDomElement seqElement; if (SimulationCommon::GetFirstChildElement(actElement, TAG::sequence, seqElement)) { + [[deprecated("Will be replaced in openSCENARIO 1-0-0 by ManeuverGroup")]] std::string sequenceName; + ThrowIfFalse(SimulationCommon::ParseAttribute(seqElement, ATTRIBUTE::name, sequenceName), + seqElement, "Attribute " + std::string(ATTRIBUTE::name) + " is missing."); + while (!seqElement.isNull()) { int numberOfExecutions; @@ -184,7 +199,9 @@ void ScenarioImporter::ImportStoryElement(QDomElement& storyElement, QDomElement maneuverElement; if (SimulationCommon::GetFirstChildElement(seqElement, TAG::maneuver, maneuverElement)) // just one maneuver per sequence { - ImportManeuverElement(maneuverElement, entities, scenario, actorInformation, numberOfExecutions, parameters); + ImportManeuverElement(maneuverElement, entities, scenario, actorInformation, + {storyName, actName, sequenceName}, + numberOfExecutions, parameters); } seqElement = seqElement.nextSiblingElement(TAG::sequence); @@ -195,7 +212,7 @@ void ScenarioImporter::ImportStoryElement(QDomElement& storyElement, } } -openScenario::ActorInformation ScenarioImporter::ImportActors(QDomElement& actorsElement, +openScenario::ActorInformation ScenarioImporter::ImportActors(QDomElement &actorsElement, const std::vector<ScenarioEntity>& entities, openScenario::Parameters& parameters) { @@ -225,25 +242,29 @@ openScenario::ActorInformation ScenarioImporter::ImportActors(QDomElement& actor QDomElement byConditionElement; SimulationCommon::GetFirstChildElement(actorsElement, TAG::byCondition, byConditionElement); - if(!byConditionElement.isNull()) + if (!byConditionElement.isNull()) { std::string actor = ParseAttribute<std::string>(byConditionElement, ATTRIBUTE::actor, parameters); - if(actor == "triggeringEntity") - { - actorInformation.triggeringAgentsAsActors.emplace(true); - } + + actorInformation.actorIsTriggeringEntity = (actor == "triggeringEntity"); } return actorInformation; } -void ScenarioImporter::ImportManeuverElement(QDomElement& maneuverElement, - const std::vector<ScenarioEntity>& entities, - ScenarioInterface* scenario, + +void ScenarioImporter::ImportManeuverElement(QDomElement &maneuverElement, + const std::vector<ScenarioEntity> &entities, + ScenarioInterface *scenario, const openScenario::ActorInformation &actorInformation, + const std::vector<std::string> &nameStack, const int numberOfExecutions, openScenario::Parameters& parameters) { + std::string maneuverName; + ThrowIfFalse(SimulationCommon::ParseAttribute(maneuverElement, ATTRIBUTE::name, maneuverName), + maneuverElement, "Attribute " + std::string(ATTRIBUTE::name) + " is missing."); + // handle parameterdeclaration element(s) for event(s) QDomElement parameterDeclarationElement; SimulationCommon::GetFirstChildElement(maneuverElement, TAG::parameterDeclaration, parameterDeclarationElement); @@ -256,19 +277,16 @@ void ScenarioImporter::ImportManeuverElement(QDomElement& maneuverElement, { std::string eventName = ParseAttribute<std::string>(eventElement, ATTRIBUTE::name, parameters); - openScenario::ConditionalEventDetectorInformation conditionalEventDetectorInformation = EventDetectorImporter::ImportEventDetector(eventElement, - eventName, - numberOfExecutions, - actorInformation, - entities, - parameters); + std::vector<std::string> eventNameStack{nameStack}; + eventNameStack.emplace_back(maneuverName); + eventNameStack.emplace_back(eventName); + + const auto stackedEventName = openpass::utils::vector::to_string(eventNameStack, "/"); - scenario->AddConditionalEventDetector(conditionalEventDetectorInformation); + auto metaInfo = EventDetectorImporter::ImportEventDetector(eventElement, stackedEventName, numberOfExecutions, actorInformation, entities, parameters); + scenario->AddConditionalEventDetector(metaInfo); - std::shared_ptr<ScenarioActionInterface> action = ManipulatorImporter::ImportManipulator(eventElement, - eventName, - scenario->GetTrajectoryCatalogPath(), - parameters); + auto action = ManipulatorImporter::ImportManipulator(eventElement, stackedEventName, scenario->GetTrajectoryCatalogPath(), parameters); scenario->AddAction(action); eventElement = eventElement.nextSiblingElement(TAG::event); @@ -735,10 +753,9 @@ bool ScenarioImporter::ContainsEntity(const std::vector<ScenarioEntity>& entitie { auto entitiesFound = std::find_if(entities.cbegin(), entities.cend(), - [entityName](const ScenarioEntity& elem) - { - return elem.name == entityName; - }); + [entityName](const ScenarioEntity &elem) { + return elem.name == entityName; + }); return entitiesFound != entities.cend(); } diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/scenarioImporter.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/scenarioImporter.h index f52a06e66e93363b240c1b7eb60354410b3e89d0..bd0ff7960ca0f4ac96bd6b9211ba1eed708b360b 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/scenarioImporter.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/scenarioImporter.h @@ -224,12 +224,23 @@ private: * \param[in] entities Objects from 'Entities' tag * \param[out] scenario The maneuver data is imported into this scenario * \param[out] actors Actors from the maneuver are imported into this container - * \param[in] parameters declared parameters + * \param[in] parameters declared parameters + */ + + /*! + * \brief ImportManeuverElement + * \param maneuverElement The DOM root of the maneuver element + * \param entities Objects from 'Entities' tag + * \param scenario The maneuver data is imported into this scenario + * \param actorInformation Information of actors from the maneuver + * \param nameStack List of names from tree structure e.g. {"myStory", "myAct", "myManeuver"} + * \param numberOfExecutions Number of executions */ static void ImportManeuverElement(QDomElement& maneuverElement, const std::vector<ScenarioEntity>& entities, ScenarioInterface *scenario, const openScenario::ActorInformation &actorInformation, + const std::vector<std::string> &nameStack, const int numberOfExecutions, openScenario::Parameters& parameters); diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/slaveConfigImporter.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/slaveConfigImporter.cpp index 7a9bea833b87d7ee1608fecab4cdf880bfc44db7..a4408baf05c91f59f322dec3371a7d2552f22337 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/slaveConfigImporter.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/slaveConfigImporter.cpp @@ -25,7 +25,7 @@ namespace ATTRIBUTE = openpass::importer::xml::slaveConfigImporter::attribute; using namespace Importer; using namespace SimulationCommon; -std::string SlaveConfigImporter::GetLibrary(const QDomElement& root, std::string tag, std::string defaultValue) +std::string SlaveConfigImporter::GetLibrary(const QDomElement& root, const std::string& tag, const std::string& defaultValue) { std::string parsedName; if (!Parse(root, tag, parsedName)) @@ -46,114 +46,80 @@ ExperimentConfig::Libraries SlaveConfigImporter::ImportLibraries(QDomElement roo } ExperimentConfig::Libraries libs; - for (auto [tagName, defaultValue] : defaultLibraryMapping) + for (const auto& [tagName, defaultValue] : defaultLibraryMapping) { libs.try_emplace(tagName, SlaveConfigImporter::GetLibrary(libsRoot, tagName, defaultValue)); } return libs; } -void SlaveConfigImporter::ImportLoggingGroups(QDomElement loggingGroupsElement, - std::vector<std::string>& loggingGroups) -{ - const auto& loggingGroupElements = loggingGroupsElement.elementsByTagName(TAG::loggingGroup); - - for (auto i = loggingGroupElements.length() - 1; i >= 0; --i) - { - const auto& loggingGroupElement = loggingGroupElements.at(i).toElement(); - - ThrowIfFalse(!loggingGroupElement.isNull(), "Error parsing LoggingGroup elements"); - - std::string groupName = loggingGroupElement.text().toStdString(); - - ThrowIfFalse(groupName.length() != 0, loggingGroupElement, "Invalid LoggingGroup name (empty string)"); - - loggingGroups.push_back(groupName); - } -} - -void SlaveConfigImporter::ImportExperimentConfig(QDomElement experimentConfigElement, +void SlaveConfigImporter::ImportExperiment(QDomElement experimentElement, ExperimentConfig& experimentConfig) { - ThrowIfFalse(ParseInt(experimentConfigElement, "ExperimentID", experimentConfig.experimentId), - experimentConfigElement, "ExperimentID not valid."); + ThrowIfFalse(ParseInt(experimentElement, "ExperimentID", experimentConfig.experimentId), + experimentElement, "ExperimentID not valid."); - ThrowIfFalse(ParseInt(experimentConfigElement, "NumberOfInvocations", experimentConfig.numberOfInvocations), - experimentConfigElement, "NumberOfInvocations not valid."); + ThrowIfFalse(ParseInt(experimentElement, "NumberOfInvocations", experimentConfig.numberOfInvocations), + experimentElement, "NumberOfInvocations not valid."); unsigned long randomSeed; - ThrowIfFalse(ParseULong(experimentConfigElement, "RandomSeed", randomSeed), - experimentConfigElement, "RandomSeed not valid."); + ThrowIfFalse(ParseULong(experimentElement, "RandomSeed", randomSeed), + experimentElement, "RandomSeed not valid."); experimentConfig.randomSeed = static_cast<std::uint32_t>(randomSeed); - bool logCyclicsToCsv; - if (!ParseBool(experimentConfigElement, "LoggingCyclicsToCsv", logCyclicsToCsv)) - { - LOG_INTERN(LogLevel::Info) << "Tag LogCyclicsToCsv undefined, falling back to default value false."; - logCyclicsToCsv = false; - } - experimentConfig.logCyclicsToCsv = logCyclicsToCsv; - - // Logging groups - QDomElement loggingGroupsElement; - ThrowIfFalse(GetFirstChildElement(experimentConfigElement, TAG::loggingGroups, loggingGroupsElement), - experimentConfigElement, "Tag " + std::string(TAG::loggingGroups) + " is missing."); - - ImportLoggingGroups(loggingGroupsElement, experimentConfig.loggingGroups); - - experimentConfig.libraries = ImportLibraries(experimentConfigElement); + experimentConfig.libraries = ImportLibraries(experimentElement); } -void SlaveConfigImporter::ImportScenarioConfig(QDomElement scenarioConfigElement, +void SlaveConfigImporter::ImportScenario(QDomElement scenarioElement, const std::string configurationDir, ScenarioConfig& scenarioConfig) { std::string scenarioFilename; - ThrowIfFalse(ParseString(scenarioConfigElement, "OpenScenarioFile", scenarioFilename), - scenarioConfigElement, "OpenScenarioFile not valid."); + ThrowIfFalse(ParseString(scenarioElement, "OpenScenarioFile", scenarioFilename), + scenarioElement, "OpenScenarioFile not valid."); scenarioConfig.scenarioPath = openpass::core::Directories::Concat(configurationDir, scenarioFilename); } -void SlaveConfigImporter::ImportEnvironmentConfig(QDomElement environmentConfigElement, +void SlaveConfigImporter::ImportEnvironment(QDomElement environmentElement, EnvironmentConfig& environmentConfig) { //Parse all time of days QDomElement timeOfDaysElement; - ThrowIfFalse(GetFirstChildElement(environmentConfigElement, TAG::timeOfDays, timeOfDaysElement), - environmentConfigElement, "Tag " + std::string(TAG::timeOfDays) + " is missing."); + ThrowIfFalse(GetFirstChildElement(environmentElement, TAG::timeOfDays, timeOfDaysElement), + environmentElement, "Tag " + std::string(TAG::timeOfDays) + " is missing."); ThrowIfFalse(ImportProbabilityMap(timeOfDaysElement, "Value", TAG::timeOfDay, environmentConfig.timeOfDays), timeOfDaysElement, "Could not import Probabilities."); //Parse all visibility distances QDomElement visibilityDistancesElement; - ThrowIfFalse(GetFirstChildElement(environmentConfigElement, TAG::visibilityDistances, visibilityDistancesElement), - environmentConfigElement, "Tag " + std::string(TAG::visibilityDistances) + " is missing."); + ThrowIfFalse(GetFirstChildElement(environmentElement, TAG::visibilityDistances, visibilityDistancesElement), + environmentElement, "Tag " + std::string(TAG::visibilityDistances) + " is missing."); ThrowIfFalse(ImportProbabilityMap(visibilityDistancesElement, "Value", TAG::visibilityDistance, environmentConfig.visibilityDistances), visibilityDistancesElement, "Could not import Probabilities."); //Parse all frictions QDomElement frictionsElement; - ThrowIfFalse(GetFirstChildElement(environmentConfigElement, TAG::frictions, frictionsElement), - environmentConfigElement, "Tag " + std::string(TAG::frictions) + " is missing."); + ThrowIfFalse(GetFirstChildElement(environmentElement, TAG::frictions, frictionsElement), + environmentElement, "Tag " + std::string(TAG::frictions) + " is missing."); ThrowIfFalse(ImportProbabilityMap(frictionsElement, "Value", TAG::friction, environmentConfig.frictions), frictionsElement, "Could not import Probabilities."); //Parse all weathers QDomElement weathersElement; - ThrowIfFalse(GetFirstChildElement(environmentConfigElement, TAG::weathers, weathersElement), - environmentConfigElement, "Tag " + std::string(TAG::weathers) + " is missing."); + ThrowIfFalse(GetFirstChildElement(environmentElement, TAG::weathers, weathersElement), + environmentElement, "Tag " + std::string(TAG::weathers) + " is missing."); ThrowIfFalse(ImportProbabilityMap(weathersElement, "Value", TAG::weather, environmentConfig.weathers), weathersElement, "Could not import Probabilities."); } -void SlaveConfigImporter::ImportSpawnPointsConfig(const QDomElement &spawnPointsConfigElement, +void SlaveConfigImporter::ImportSpawners(const QDomElement &spawnersElement, SpawnPointLibraryInfoCollection& spawnPointsInfo) { QDomElement spawnPointElement; - ThrowIfFalse(GetFirstChildElement(spawnPointsConfigElement, TAG::spawnPoint, spawnPointElement), - spawnPointsConfigElement, "Tag " + std::string(TAG::spawnPoint) + " is missing."); + ThrowIfFalse(GetFirstChildElement(spawnersElement, TAG::spawner, spawnPointElement), + spawnersElement, "Tag " + std::string(TAG::spawner) + " is missing."); while (!spawnPointElement.isNull()) { @@ -186,20 +152,32 @@ void SlaveConfigImporter::ImportSpawnPointsConfig(const QDomElement &spawnPoints spawnPointsInfo.emplace_back(spawnPointInfo); - spawnPointElement = spawnPointElement.nextSiblingElement("SpawnPoint"); + spawnPointElement = spawnPointElement.nextSiblingElement(TAG::spawner); } } -void SlaveConfigImporter::ImportObservationConfig(const QDomElement& librariesElement, std::vector<std::string>& loggingGroups, bool logCyclicsToCsv, ObservationInstanceCollection& observationConfig) +void SlaveConfigImporter::ImportObservations(const QDomElement& observationsElement, ObservationInstanceCollection& observations) { - auto observationLibrary = SlaveConfigImporter::GetLibrary(librariesElement, "ObservationLibrary", "Observation"); - openpass::parameter::ParameterSetLevel1 observationParameters + QDomElement observationElement; + ThrowIfFalse(GetFirstChildElement(observationsElement, TAG::observation, observationElement), + observationsElement, "Tag " + std::string(TAG::observation) + " is missing."); + + while (!observationElement.isNull()) { - { "LoggingCyclicsToCsv", logCyclicsToCsv}, - { "LoggingGroups", loggingGroups } - }; - ObservationInstance observationInstance{0, observationLibrary, observationParameters}; - observationConfig.push_back(observationInstance); + ObservationInstance observationInstance; + + ThrowIfFalse(ParseString(observationElement, TAG::library, observationInstance.libraryName), + observationElement, "Tag " + std::string(TAG::library) + " is missing."); + + QDomElement parametersElement; + ThrowIfFalse(GetFirstChildElement(observationElement, TAG::parameters, parametersElement), + observationsElement, "Tag " + std::string(TAG::parameters) + " is missing."); + observationInstance.parameters = openpass::parameter::Import(parametersElement, observationsElement); + + observations.emplace_back(observationInstance); + + observationElement = observationElement.nextSiblingElement(TAG::observation); + } } bool SlaveConfigImporter::Import(const std::string& configurationDir, @@ -227,44 +205,37 @@ bool SlaveConfigImporter::Import(const std::string& configurationDir, ParseAttributeString(documentRoot, ATTRIBUTE::schemaVersion, configVersion); ThrowIfFalse(configVersion.compare(supportedConfigVersion) == 0, "SlaveConfig version not suppored. Supported version is " + std::string(supportedConfigVersion)); - //Import profiles catalog std::string profilesCatalog; ThrowIfFalse(ParseString(documentRoot, "ProfilesCatalog", profilesCatalog), "Could not import Proifles Catalog."); slaveConfig.SetProfilesCatalog(openpass::core::Directories::Concat(configurationDir, profilesCatalog)); - //Import experiment config auto& experimentConfig = slaveConfig.GetExperimentConfig(); QDomElement experimentConfigElement; - ThrowIfFalse(GetFirstChildElement(documentRoot, TAG::experimentConfig, experimentConfigElement), - "Could not import ExperimentConfig."); + ThrowIfFalse(GetFirstChildElement(documentRoot, TAG::experiment, experimentConfigElement), + "Tag " + std::string(TAG::experiment) + " is missing."); + ImportExperiment(experimentConfigElement, experimentConfig); - ImportExperimentConfig(experimentConfigElement, experimentConfig); - - //Import scenario config QDomElement scenarioConfigElement; - ThrowIfFalse(GetFirstChildElement(documentRoot, TAG::scenarioConfig, scenarioConfigElement), - "Could not import ScenarioConfig."); - - ImportScenarioConfig(scenarioConfigElement, configurationDir, slaveConfig.GetScenarioConfig()); + ThrowIfFalse(GetFirstChildElement(documentRoot, TAG::scenario, scenarioConfigElement), + "Tag " + std::string(TAG::scenario) + " is missing."); + ImportScenario(scenarioConfigElement, configurationDir, slaveConfig.GetScenarioConfig()); - //Import environment config QDomElement environmentConfigElement; - ThrowIfFalse(GetFirstChildElement(documentRoot, TAG::environmentConfig, environmentConfigElement), - "Could not import EnvironmentConfig."); - - ImportEnvironmentConfig(environmentConfigElement, slaveConfig.GetEnvironmentConfig()); + ThrowIfFalse(GetFirstChildElement(documentRoot, TAG::environment, environmentConfigElement), + "Tag " + std::string(TAG::environment) + " is missing."); + ImportEnvironment(environmentConfigElement, slaveConfig.GetEnvironmentConfig()); - QDomElement librariesElement; - ThrowIfFalse(SimulationCommon::GetFirstChildElement(experimentConfigElement, TAG::libraries, librariesElement), experimentConfigElement, "Missing libraries"); - ImportObservationConfig(librariesElement, experimentConfig.loggingGroups, experimentConfig.logCyclicsToCsv, slaveConfig.GetObservationConfig()); + QDomElement observationConfigElement; + ThrowIfFalse(GetFirstChildElement(documentRoot, TAG::observations, observationConfigElement), + "Tag " + std::string(TAG::observations) + " is missing."); + ImportObservations(observationConfigElement, slaveConfig.GetObservationConfig()); - //Import spawnpoints config QDomElement spawnPointsConfigElement; - ThrowIfFalse(GetFirstChildElement(documentRoot, "SpawnPointsConfig", spawnPointsConfigElement), - "Could not import SpawnPointsConfig."); - ImportSpawnPointsConfig(spawnPointsConfigElement, slaveConfig.GetSpawnPointsConfig()); + ThrowIfFalse(GetFirstChildElement(documentRoot, TAG::spawners, spawnPointsConfigElement), + "Tag " + std::string(TAG::spawners) + " is missing."); + ImportSpawners(spawnPointsConfigElement, slaveConfig.GetSpawnPointsConfig()); return true; } diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/slaveConfigImporter.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/slaveConfigImporter.h index c99a8fa16970b32b0dc946604b77d3905dc1d406..ac2e2cf3e60ab1d854ebaa86fb6e9935e8468671 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/slaveConfigImporter.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/importer/slaveConfigImporter.h @@ -36,14 +36,6 @@ namespace Importer { class SlaveConfigImporter { public: - /*! - * \brief Imports the logging groups for the observer - * - * @param[in] loggingGroupsElement Element containing the logging groups information - * @param[out] loggingGroups Vector where the logging groups get saved - */ - static void ImportLoggingGroups(QDomElement loggingGroupsElement, std::vector<std::string>& loggingGroups); - /*! * \brief Imports the libraries used by the simulator * @@ -60,7 +52,7 @@ public: * @param[in] experimentConfigElement Element containing the information * @param[out] experimentConfig Struct into which the values get saved */ - static void ImportExperimentConfig(QDomElement experimentConfigElement, + static void ImportExperiment(QDomElement experimentElement, ExperimentConfig& experimentConfig); /*! @@ -69,7 +61,7 @@ public: * @param[in] scenarioConfigElement Element containing the information * @param[out] scenarioConfig Struct into which the values get saved */ - static void ImportScenarioConfig(QDomElement scenarioConfigElement, + static void ImportScenario(QDomElement scenarioElement, const std::string configurationDir, ScenarioConfig& scenarioConfig); @@ -79,7 +71,7 @@ public: * @param[in] environmentConfigElement Element containing the information * @param[out] environmentConfig Struct into which the values get saved */ - static void ImportEnvironmentConfig(QDomElement environmentConfigElement, + static void ImportEnvironment(QDomElement environmentElement, EnvironmentConfig& environmentConfig); /*! @@ -88,13 +80,11 @@ public: * \param spawnPointsInfo struct into which the values get saved * \return */ - static void ImportSpawnPointsConfig(const QDomElement& spawnPointsConfigElement, + static void ImportSpawners(const QDomElement& spawnersElement, SpawnPointLibraryInfoCollection& spawnPointsInfo); - static void ImportObservationConfig(const QDomElement& librariesElement, - std::vector<std::string>& loggingGroups, - bool logCyclicsToCsv, - ObservationInstanceCollection& observationConfig); + static void ImportObservations(const QDomElement& observationsElement, + ObservationInstanceCollection& observations); //Overall import function /*! @@ -111,13 +101,14 @@ public: Configuration::SlaveConfig& slaveConfig); private: - static std::string GetLibrary(const QDomElement& root, std::string key, std::string tag); - static constexpr auto supportedConfigVersion = "0.7.0"; + static std::string GetLibrary(const QDomElement& root, const std::string& key, const std::string& tag); + static constexpr auto supportedConfigVersion = "0.8.0"; //! \brief Identifier with correspondiong default values for mandatory libraries //! \note: The identifier is identical to the XML tag inline static const ExperimentConfig::Libraries defaultLibraryMapping = { + {"DataStoreLibrary", "BasicDataStore"}, {"EventDetectorLibrary", "EventDetector"}, {"ManipulatorLibrary", "Manipulator"}, {"WorldLibrary", "World"}, diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/agent.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/agent.cpp index cdd8b419b8602a900b5ef37764f077050bafca52..ecbcd2b9003efe15014f467f358fbceb913dbc46 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/agent.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/agent.cpp @@ -9,29 +9,32 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ +#include "agent.h" + #include <algorithm> +#include <iostream> #include <map> #include <vector> -#include <iostream> + #include <QDomDocument> #include <QFile> -#include "agent.h" +#include "CoreFramework/CoreShare/log.h" +#include "CoreFramework/CoreShare/parameters.h" +#include "Interfaces/observationNetworkInterface.h" +#include "agentDataPublisher.h" #include "agentType.h" #include "channel.h" -#include "componentType.h" #include "component.h" -#include "CoreFramework/CoreShare/log.h" +#include "componentType.h" #include "modelBinding.h" -#include "Interfaces/observationNetworkInterface.h" -#include "CoreFramework/CoreShare/parameters.h" #include "spawnPoint.h" -namespace SimulationSlave -{ +class DataStoreWriteInterface; + +namespace SimulationSlave { -Agent::Agent(int id, - WorldInterface *world): +Agent::Agent(int id, WorldInterface *world) : id(id), world(world) { @@ -42,11 +45,11 @@ Agent::~Agent() { LOG_INTERN(LogLevel::DebugCore) << "deleting agent " << id; - for(std::pair<const std::string, ComponentInterface*> &item : components) + for (std::pair<const std::string, ComponentInterface *> &item : components) { ComponentInterface *component = item.second; - if(!component->ReleaseFromLibrary()) + if (!component->ReleaseFromLibrary()) { LOG_INTERN(LogLevel::Error) << "component could not be released by agent " << id; } @@ -55,7 +58,7 @@ Agent::~Agent() } components.clear(); - for(std::pair<const int, Channel*> &item : channels) + for (std::pair<const int, Channel *> &item : channels) { Channel *channel = item.second; delete channel; @@ -63,26 +66,28 @@ Agent::~Agent() channels.clear(); } -bool Agent::Instantiate(AgentBlueprintInterface* agentBlueprint, +bool Agent::Instantiate(AgentBlueprintInterface *agentBlueprint, ModelBinding *modelBinding, StochasticsInterface *stochastics, ObservationNetworkInterface *observationNetwork, - EventNetworkInterface *eventNetwork) + EventNetworkInterface *eventNetwork, + DataStoreWriteInterface *dataStore) { + publisher = std::make_unique<openpass::publisher::AgentDataPublisher>(dataStore, id); + // setup - if(!agentInterface->InitAgentParameter(id, - agentBlueprint)) + if (!agentInterface->InitAgentParameter(id, agentBlueprint)) { return false; } // instantiate channels - for(int channelId : agentBlueprint->GetAgentType().GetChannels()) + for (int channelId : agentBlueprint->GetAgentType().GetChannels()) { LOG_INTERN(LogLevel::DebugCore) << "- instantiate channel " << channelId; Channel *channel = new (std::nothrow) Channel(channelId); - if(!channel) + if (!channel) { LOG_INTERN(LogLevel::Error) << "agent could not be instantiated"; return false; @@ -90,17 +95,16 @@ bool Agent::Instantiate(AgentBlueprintInterface* agentBlueprint, channel->SetAgent(this); - if(!AddChannel(channelId, channel)) + if (!AddChannel(channelId, channel)) { LOG_INTERN(LogLevel::Error) << "agent could not be instantiated"; delete channel; return false; } - } // instantiate components - for(const std::pair<const std::string, std::shared_ptr<ComponentType>> &itemComponentType : agentBlueprint->GetAgentType().GetComponents()) + for (const std::pair<const std::string, std::shared_ptr<ComponentType>> &itemComponentType : agentBlueprint->GetAgentType().GetComponents()) { std::string componentName = itemComponentType.first; std::shared_ptr<ComponentType> componentType = itemComponentType.second; @@ -108,19 +112,20 @@ bool Agent::Instantiate(AgentBlueprintInterface* agentBlueprint, LOG_INTERN(LogLevel::DebugCore) << "- instantiate component " << componentName; ComponentInterface *component = modelBinding->Instantiate(componentType, - componentName, - stochastics, - world, - observationNetwork, - this, - eventNetwork); - if(!component) + componentName, + stochastics, + world, + observationNetwork, + this, + eventNetwork, + publisher.get()); + if (!component) { LOG_INTERN(LogLevel::Error) << "agent could not be instantiated"; return false; } - if(!AddComponent(componentName, component)) + if (!AddComponent(componentName, component)) { LOG_INTERN(LogLevel::Error) << "agent could not be instantiated"; delete component; @@ -130,7 +135,7 @@ bool Agent::Instantiate(AgentBlueprintInterface* agentBlueprint, // from here component will be deleted implicitely by agent destructor since it is linked into its container // instantiate inputs - for(const std::pair<const int, int> &item : componentType->GetInputLinks()) + for (const std::pair<const int, int> &item : componentType->GetInputLinks()) { int linkId = item.first; int channelRef = item.second; @@ -138,24 +143,24 @@ bool Agent::Instantiate(AgentBlueprintInterface* agentBlueprint, LOG_INTERN(LogLevel::DebugCore) << " * instantiate input channel " << channelRef << " (linkId " << linkId << ")"; Channel *channel = GetChannel(channelRef); - if(!channel) + if (!channel) { continue; } - if(!component->AddInputLink(channel, linkId)) + if (!component->AddInputLink(channel, linkId)) { return false; } - if(!channel->AddTarget(component, linkId)) + if (!channel->AddTarget(component, linkId)) { return false; } } // instantiate outputs - for(const std::pair<const int, int> &item : componentType->GetOutputLinks()) + for (const std::pair<const int, int> &item : componentType->GetOutputLinks()) { int linkId = item.first; int channelRef = item.second; @@ -163,17 +168,17 @@ bool Agent::Instantiate(AgentBlueprintInterface* agentBlueprint, LOG_INTERN(LogLevel::DebugCore) << " * instantiate output channel " << channelRef << " (linkId " << linkId << ")"; Channel *channel = GetChannel(channelRef); - if(!channel) + if (!channel) { return false; } - if(!component->AddOutputLink(channel, linkId)) + if (!component->AddOutputLink(channel, linkId)) { return false; } - if(!channel->SetSource(component, linkId)) + if (!channel->SetSource(component, linkId)) { return false; } @@ -195,7 +200,7 @@ void Agent::SetAgentAdapter(AgentInterface *agentAdapt) bool Agent::AddComponent(std::string name, ComponentInterface *component) { - if(!components.insert(std::make_pair<std::string&, ComponentInterface*&>(name, component)).second) + if (!components.insert(std::make_pair<std::string &, ComponentInterface *&>(name, component)).second) { LOG_INTERN(LogLevel::Warning) << "components must be unique"; return false; @@ -206,7 +211,7 @@ bool Agent::AddComponent(std::string name, ComponentInterface *component) bool Agent::AddChannel(int id, Channel *channel) { - if(!channels.insert({id, channel}).second) + if (!channels.insert({id, channel}).second) { LOG_INTERN(LogLevel::Warning) << "channels must be unique"; return false; @@ -223,7 +228,7 @@ Channel *Agent::GetChannel(int id) const { channel = channels.at(id); } - catch(const std::out_of_range&) + catch (const std::out_of_range &) { channel = nullptr; } @@ -239,7 +244,7 @@ ComponentInterface *Agent::GetComponent(std::string name) const { component = components.at(name); } - catch(const std::out_of_range&) + catch (const std::out_of_range &) { component = nullptr; } @@ -247,9 +252,14 @@ ComponentInterface *Agent::GetComponent(std::string name) const return component; } -const std::map<std::string, ComponentInterface*> &Agent::GetComponents() const +const std::map<std::string, ComponentInterface *> &Agent::GetComponents() const { return components; } +void Agent::LinkSchedulerTime(int *const schedulerTime) +{ + currentTime = schedulerTime; +} + } // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/agent.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/agent.h index 8248a9d6d43038b65b04e25eda2e41bcc7e17c6b..aa9636d04b7beec2d756fbb2cc2809bbea5c40c7 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/agent.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/agent.h @@ -29,6 +29,8 @@ #include "Interfaces/agentInterface.h" #include "Interfaces/componentInterface.h" +class DataStoreWriteInterface; + namespace SimulationSlave { @@ -42,8 +44,7 @@ class SpawnItemParameter; class Agent { public: - Agent(int id, - WorldInterface *world); + Agent(int id, WorldInterface* world); Agent(const Agent&) = delete; Agent(Agent&&) = delete; Agent& operator=(const Agent&) = delete; @@ -55,6 +56,7 @@ public: Channel *GetChannel(int id) const; ComponentInterface *GetComponent(std::string name) const; const std::map<std::string, ComponentInterface*> &GetComponents() const; + int GetId() const { return id; @@ -64,17 +66,20 @@ public: ModelBinding *modelBinding, StochasticsInterface *stochastics, SimulationSlave::ObservationNetworkInterface *observationNetwork, - EventNetworkInterface *eventNetwork); + EventNetworkInterface *eventNetwork, + DataStoreWriteInterface* dataStore); bool IsValid() const { return agentInterface->IsValid(); } - AgentInterface *GetAgentAdapter() const; + AgentInterface* GetAgentAdapter() const; void SetAgentAdapter(AgentInterface *agentAdapt); + void LinkSchedulerTime(int* const schedulerTime); + private: // framework parameters std::vector<int> idsCollisionPartners; @@ -83,7 +88,10 @@ private: std::map<int, Channel*> channels; std::map<std::string, ComponentInterface*> components; - AgentInterface *agentInterface = nullptr; + AgentInterface* agentInterface = nullptr; + std::unique_ptr<PublisherInterface> publisher; + + int* currentTime = nullptr; }; } // namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/component.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/component.cpp index 5e4e7b2dcc9cb44139b4113306a70a2ae2225ef8..7296ccf35330942a583918bfbfd8e371429a34c7 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/component.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/component.cpp @@ -279,7 +279,7 @@ ChannelBuffer* Component::CreateOutputBuffer(int linkId) return nullptr; } - return (ChannelBuffer*)buffer; + return buffer; } bool Component::SetInputBuffer(int linkId, ChannelBuffer* buffer) diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/component.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/component.h index 4229cf628595a4337f858da7102e3d3f50ede76f..7e304aab65743c2962daaef872611dfd2d90c591 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/component.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelElements/component.h @@ -21,6 +21,7 @@ #include "Interfaces/componentInterface.h" #include "Interfaces/modelInterface.h" #include "Interfaces/observationInterface.h" +#include "Interfaces/publisherInterface.h" namespace SimulationSlave { @@ -48,7 +49,7 @@ public: //----------------------------------------------------------------------------- //! Destructor, deletes all saved output channel buffers. //----------------------------------------------------------------------------- - virtual ~Component(); + virtual ~Component() override; //----------------------------------------------------------------------------- @@ -56,8 +57,7 @@ public: //! //! @param[in] implementation Model interface implementation to set //----------------------------------------------------------------------------- - void SetImplementation(ModelInterface* implementation); - + void SetImplementation(ModelInterface* implementation) override; void SetParameter(std::unique_ptr<ParameterInterface> parameter) override { @@ -69,7 +69,7 @@ public: //! //! @return Stored agent //----------------------------------------------------------------------------- - Agent* GetAgent() const; + Agent* GetAgent() const override; //----------------------------------------------------------------------------- //! Adds the provided channel with the provided ID to the stored list of input @@ -79,7 +79,7 @@ public: //! @param[in] linkId ID of the channel to add //! @return Flag if adding the channel was successful //----------------------------------------------------------------------------- - bool AddInputLink(Channel* input, int linkId); + bool AddInputLink(Channel* input, int linkId) override; //----------------------------------------------------------------------------- //! Adds the provided channel with the provided ID to the stored list of output @@ -89,7 +89,7 @@ public: //! @param[in] linkId ID of the channel to add //! @return Flag if adding the channel was successful //----------------------------------------------------------------------------- - bool AddOutputLink(Channel* output, int linkId); + bool AddOutputLink(Channel* output, int linkId) override; //----------------------------------------------------------------------------- //! Sets the observation modules map of the component @@ -103,21 +103,21 @@ public: //! //! @return Map of IDs to stored input channels //----------------------------------------------------------------------------- - std::map<int, Channel*>& GetInputLinks(); + std::map<int, Channel*>& GetInputLinks() override; //----------------------------------------------------------------------------- //! Returns the map of IDs to stored output channels. //! //! @return Map of IDs to stored output channels //----------------------------------------------------------------------------- - std::map<int, Channel*>& GetOutputLinks(); + std::map<int, Channel*>& GetOutputLinks() override; //----------------------------------------------------------------------------- //! Returns the map of IDs to stored observation modules. //! //! @return Map of IDs to stored observation modules //----------------------------------------------------------------------------- - const std::map<int, ObservationInterface*>& GetObservations() const; + const std::map<int, ObservationInterface*>& GetObservations() const override; //----------------------------------------------------------------------------- //! Calls the Trigger method on the stored model library with the stored model @@ -126,7 +126,7 @@ public: //! @param[in] time Observation module (as interface)to add //! @return False if an error occurred, true otherwise //----------------------------------------------------------------------------- - bool TriggerCycle(int time); + bool TriggerCycle(int time) override; //----------------------------------------------------------------------------- //! Gets the data on the channel with the provided ID by updating the output @@ -138,7 +138,7 @@ public: //! @param[in] time Time stamp for the output //! @return False if an error occurred, true otherwise //----------------------------------------------------------------------------- - bool AcquireOutputData(int linkId, int time); + bool AcquireOutputData(int linkId, int time) override; //----------------------------------------------------------------------------- //! Releases the data on the channel with the provided ID. @@ -146,7 +146,7 @@ public: //! @param[in] linkId ID of the output channel //! @return False if an error occurred, true otherwise //----------------------------------------------------------------------------- - bool ReleaseOutputData(int linkId); + bool ReleaseOutputData(int linkId) override; //----------------------------------------------------------------------------- //! Updates the input data on the input channelwith the provided ID by updating @@ -157,7 +157,7 @@ public: //! @param[in] time Time stamp for the output //! @return False if an error occurred, true otherwise //----------------------------------------------------------------------------- - bool UpdateInputData(int linkId, int time); + bool UpdateInputData(int linkId, int time) override; //----------------------------------------------------------------------------- //! Creates a new channel buffer with the provided ID, store it in the stored @@ -166,7 +166,7 @@ public: //! @param[in] linkId ID of the channel output buffer to create //! @return Created output channel buffer //----------------------------------------------------------------------------- - ChannelBuffer* CreateOutputBuffer(int linkId); + ChannelBuffer* CreateOutputBuffer(int linkId) override; //----------------------------------------------------------------------------- //! Insert the provided channel buffer with the provided ID in the list of stored @@ -176,7 +176,7 @@ public: //! @param[in] buffer Channel input bufer to set //! @return False if an error occurred, true otherwise //----------------------------------------------------------------------------- - bool SetInputBuffer(int linkId, ChannelBuffer* buffer); + bool SetInputBuffer(int linkId, ChannelBuffer* buffer) override; //----------------------------------------------------------------------------- //! Returns if the stored model interface implementation is defined as init module. @@ -185,7 +185,7 @@ public: //! the flag if stored model interface //! implementation is defined as init module //----------------------------------------------------------------------------- - bool GetInit() const; + bool GetInit() const override; //----------------------------------------------------------------------------- //! Returns the priority of the stored model interface implementation. @@ -194,7 +194,7 @@ public: //! if error occured, otherwise the priority //! of the stored model interface implementation //----------------------------------------------------------------------------- - int GetPriority() const; + int GetPriority() const override; //----------------------------------------------------------------------------- //! Returns the offset time of the stored model interface implementation, i.e. @@ -204,7 +204,7 @@ public: //! the offset time of the stored model //! interface implementation //----------------------------------------------------------------------------- - int GetOffsetTime() const; + int GetOffsetTime() const override; //----------------------------------------------------------------------------- //! Returns the response time of the stored model interface implementation. @@ -213,7 +213,7 @@ public: //! the respone time of the stored model //! interface implementation //----------------------------------------------------------------------------- - int GetResponseTime() const; + int GetResponseTime() const override; //----------------------------------------------------------------------------- //! Returns the cycle time of the stored model interface implementation, i.e. @@ -223,7 +223,7 @@ public: //! the cycle time of the stored model //! interface implementation //----------------------------------------------------------------------------- - int GetCycleTime() const; + int GetCycleTime() const override; //----------------------------------------------------------------------------- //! Set the provided model library as library to store. @@ -232,28 +232,28 @@ public: //! @return False if library is already set, true //! otherwise //----------------------------------------------------------------------------- - bool SetModelLibrary(ModelLibrary* modelLibrary); + bool SetModelLibrary(ModelLibrary* modelLibrary) override; //----------------------------------------------------------------------------- //! Releases this component from the stored library. //! //! @return Result of releasing this component //----------------------------------------------------------------------------- - bool ReleaseFromLibrary(); + bool ReleaseFromLibrary() override; //----------------------------------------------------------------------------- //! Returns the stored model interface instance. //! //! @return Stored model interface instance //----------------------------------------------------------------------------- - ModelInterface* GetImplementation() const; + ModelInterface* GetImplementation() const override; //----------------------------------------------------------------------------- //! Returns the stored ID. //! //! @return Stored ID //----------------------------------------------------------------------------- - std::string GetName() const; + std::string GetName() const override; private: Agent* agent; @@ -264,6 +264,7 @@ private: ModelLibrary* modelLibrary; ModelInterface* implementation; std::unique_ptr<ParameterInterface> parameter; + std::unique_ptr<PublisherInterface> publisher; std::map<int, ChannelBuffer*> inputChannelBuffers; std::map<int, ChannelBuffer*> outputChannelBuffers; }; diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelBinding.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelBinding.cpp index 33d20a37f3520e73418267ead3de6e15b2fa6066..3b006eea9d55709265362f02ae5a8beb6cdc7088 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelBinding.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelBinding.cpp @@ -32,13 +32,14 @@ ModelBinding::~ModelBinding() Unload(); } -ComponentInterface *ModelBinding::Instantiate(std::shared_ptr<ComponentType>componentType, - std::string componentName, - StochasticsInterface *stochastics, - WorldInterface *world, - ObservationNetworkInterface *observationNetwork, - Agent *agent, - EventNetworkInterface *eventNetwork) +ComponentInterface *ModelBinding::Instantiate(std::shared_ptr<ComponentType> componentType, + std::string componentName, + StochasticsInterface *stochastics, + WorldInterface *world, + ObservationNetworkInterface *observationNetwork, + Agent *agent, + EventNetworkInterface *eventNetwork, + PublisherInterface *publisher) { const std::string name = componentType->GetModelLibrary(); @@ -82,7 +83,8 @@ ComponentInterface *ModelBinding::Instantiate(std::shared_ptr<ComponentType>comp world, observationNetwork, agent, - eventNetwork); + eventNetwork, + publisher); } void ModelBinding::Unload() diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelBinding.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelBinding.h index 9818518dc7ce0c026a45260c8c4385957102632c..eb40bae63eb63c2f6e3e0f7dab5d32201c4d29e2 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelBinding.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelBinding.h @@ -18,11 +18,15 @@ #include <map> #include <string> + #include "Interfaces/modelInterface.h" #include "Interfaces/componentInterface.h" + +#include "Common/runtimeInformation.h" #include "CoreFramework/CoreShare/callbacks.h" #include "CoreFramework/CoreShare/log.h" -#include "Common/runtimeInformation.h" + +class PublisherInterface; namespace SimulationSlave { @@ -53,21 +57,24 @@ public: //! parameters using this library. //! //! @param[in] componentType Type of the component to instantiate - //! @param[in] componentId ID of the component to instantiate + //! @param[in] componentName Name of the component to instantiate //! @param[in] stochastics Stochastics interface //! @param[in] world World representation //! @param[in] observationNetwork Network of the observation modules //! @param[in] agent Agent that the component type is a part of + //! @param[in] eventNetwork Instance of the internal event logic + //! @param[in] publisher Publisher instance //! //! @return The instantiated component //----------------------------------------------------------------------------- ComponentInterface *Instantiate(std::shared_ptr<ComponentType> componentType, - std::string componentName, - StochasticsInterface *stochastics, - WorldInterface *world, - ObservationNetworkInterface *observationNetwork, - Agent *agent, - EventNetworkInterface *eventNetwork); + std::string componentName, + StochasticsInterface *stochastics, + WorldInterface *world, + ObservationNetworkInterface *observationNetwork, + Agent *agent, + EventNetworkInterface *eventNetwork, + PublisherInterface *publisher); //----------------------------------------------------------------------------- //! Unloads the model library by deleting the stored libraries diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelLibrary.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelLibrary.cpp index aef91ef9eaacba919cf0f5d63123c385980786ea..8fd15fdcad9b7aa68d51a199585f18aba971e5da 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelLibrary.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelLibrary.cpp @@ -16,6 +16,7 @@ #include <QLibrary> #include "agent.h" +#include "agentDataPublisher.h" #include "component.h" #include "componentType.h" #include "CoreFramework/CoreShare/log.h" @@ -52,49 +53,42 @@ bool ModelLibrary::Init() return false; } - getVersionFunc = (ModelInterface_GetVersion)library->resolve(DllGetVersionId.c_str()); + getVersionFunc = reinterpret_cast<ModelInterface_GetVersion>(library->resolve(DllGetVersionId.c_str())); if (!getVersionFunc) { LOG_INTERN(LogLevel::Error) << "could not resolve " << DllGetVersionId.c_str() << " from DLL"; return false; } - createInstanceFunc = (ModelInterface_CreateInstanceType)library->resolve(DllCreateInstanceId.c_str()); + createInstanceFunc = reinterpret_cast<ModelInterface_CreateInstanceType>(library->resolve(DllCreateInstanceId.c_str())); if (!createInstanceFunc) { LOG_INTERN(LogLevel::Error) << "could not resolve " << DllCreateInstanceId.c_str() << " from DLL"; return false; } - createEventInstanceFunc = (UnrestrictedEventModelInterface_CreateInstanceType)library->resolve(DllCreateInstanceId.c_str()); - if(!createEventInstanceFunc) - { - LOG_INTERN(LogLevel::Error) << "could not resolve " << DllCreateInstanceId.c_str() << " from DLL"; - return false; - } - - destroyInstanceFunc = (ModelInterface_DestroyInstanceType)library->resolve(DllDestroyInstanceId.c_str()); + destroyInstanceFunc = reinterpret_cast<ModelInterface_DestroyInstanceType>(library->resolve(DllDestroyInstanceId.c_str())); if (!destroyInstanceFunc) { LOG_INTERN(LogLevel::Error) << "could not resolve " << DllDestroyInstanceId.c_str() << " from DLL"; return false; } - updateInputFunc = (ModelInterface_UpdateInputType)library->resolve(DllUpdateInputId.c_str()); + updateInputFunc = reinterpret_cast<ModelInterface_UpdateInputType>(library->resolve(DllUpdateInputId.c_str())); if (!updateInputFunc) { LOG_INTERN(LogLevel::Error) << "could not resolve " << DllUpdateInputId.c_str() << " from DLL"; return false; } - updateOutputFunc = (ModelInterface_UpdateOutputType)library->resolve(DllUpdateOutputId.c_str()); + updateOutputFunc = reinterpret_cast<ModelInterface_UpdateOutputType>(library->resolve(DllUpdateOutputId.c_str())); if (!updateOutputFunc) { LOG_INTERN(LogLevel::Error) << "could not resolve " << DllUpdateOutputId.c_str() << " from DLL"; return false; } - triggerFunc = (ModelInterface_TriggerType)library->resolve(DllTriggerId.c_str()); + triggerFunc = reinterpret_cast<ModelInterface_TriggerType>(library->resolve(DllTriggerId.c_str())); if (!triggerFunc) { LOG_INTERN(LogLevel::Error) << "could not resolve " << DllTriggerId.c_str() << " from DLL"; @@ -183,7 +177,8 @@ ComponentInterface* ModelLibrary::CreateComponent(std::shared_ptr<ComponentType> WorldInterface* world, ObservationNetworkInterface* observationNetwork, Agent* agent, - EventNetworkInterface* eventNetwork) + EventNetworkInterface* eventNetwork, + PublisherInterface* publisher) { if (!library) { @@ -216,36 +211,73 @@ ComponentInterface* ModelLibrary::CreateComponent(std::shared_ptr<ComponentType> { const auto &version = getVersionFunc(); - if (version == "0.1.0") + /*if (version == "0.3.0") + { + implementation = reinterpret_cast<UnrestrictedEventPublishModelInterface_CreateInstanceType>(createInstanceFunc)( + componentName, + componentType->GetInit(), + componentType->GetPriority(), + componentType->GetOffsetTime(), + componentType->GetResponseTime(), + componentType->GetCycleTime(), + stochastics, + world, + parameter.get(), + &component->GetObservations(), + agent->GetAgentAdapter(), + callbacks, + eventNetwork, + publisher); + } + if (version == "0.2.0") + { + implementation = reinterpret_cast<UnrestrictedPublishModelInterface_CreateInstanceType>(createInstanceFunc)( + componentName, + componentType->GetInit(), + componentType->GetPriority(), + componentType->GetOffsetTime(), + componentType->GetResponseTime(), + componentType->GetCycleTime(), + stochastics, + world, + parameter.get(), + &component->GetObservations(), + agent->GetAgentAdapter(), + callbacks, + publisher); + } + else*/ if (version == "0.1.0") { - implementation = createEventInstanceFunc(componentName, - componentType->GetInit(), - componentType->GetPriority(), - componentType->GetOffsetTime(), - componentType->GetResponseTime(), - componentType->GetCycleTime(), - stochastics, - world, - parameter.get(), - &component->GetObservations(), - agent->GetAgentAdapter(), - callbacks, - eventNetwork); + implementation = reinterpret_cast<UnrestrictedEventModelInterface_CreateInstanceType>(createInstanceFunc)( + componentName, + componentType->GetInit(), + componentType->GetPriority(), + componentType->GetOffsetTime(), + componentType->GetResponseTime(), + componentType->GetCycleTime(), + stochastics, + world, + parameter.get(), + publisher, + agent->GetAgentAdapter(), + callbacks, + eventNetwork); } else { - implementation = createInstanceFunc(componentName, - componentType->GetInit(), - componentType->GetPriority(), - componentType->GetOffsetTime(), - componentType->GetResponseTime(), - componentType->GetCycleTime(), - stochastics, - world, - parameter.get(), - &component->GetObservations(), - agent->GetAgentAdapter(), - callbacks); + implementation = createInstanceFunc( + componentName, + componentType->GetInit(), + componentType->GetPriority(), + componentType->GetOffsetTime(), + componentType->GetResponseTime(), + componentType->GetCycleTime(), + stochastics, + world, + parameter.get(), + publisher, + agent->GetAgentAdapter(), + callbacks); } } catch (std::runtime_error const& ex) diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelLibrary.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelLibrary.h index e44324962f30c0164b7d5069bf12957631b03305..126653c39282868dd1e2f91ca509f805d55e3403 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelLibrary.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/modelInterface/modelLibrary.h @@ -25,6 +25,8 @@ #include "Interfaces/componentInterface.h" #include "Interfaces/observationNetworkInterface.h" +class PublisherInterface; + namespace SimulationSlave { @@ -44,22 +46,22 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observationLinks, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks); typedef ModelInterface *(*UnrestrictedEventModelInterface_CreateInstanceType)(std::string componentName, - bool isInit, - int priority, - int offsetTime, - int responseTime, - int cycleTime, - StochasticsInterface *stochastics, - WorldInterface *world, - const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observationLinks, - AgentInterface *agent, - const CallbackInterface *callbacks, - const SimulationSlave::EventNetworkInterface *eventNetwork); + bool isInit, + int priority, + int offsetTime, + int responseTime, + int cycleTime, + StochasticsInterface *stochastics, + WorldInterface *world, + const ParameterInterface *parameters, + PublisherInterface * const publisher, + AgentInterface *agent, + const CallbackInterface *callbacks, + const SimulationSlave::EventNetworkInterface *eventNetwork); typedef void (*ModelInterface_DestroyInstanceType)(ModelInterface *implementation); typedef bool (*ModelInterface_UpdateInputType)(ModelInterface *implementation, int localLinkId, @@ -118,16 +120,18 @@ public: //! @param[in] observationNetwork Network of the observation modules //! @param[in] agent Agent instance //! @param[in] eventNetwork Instance of the internal event logic + //! @param[in] publisher Publisher instance //! @return //----------------------------------------------------------------------------- ComponentInterface *CreateComponent(std::shared_ptr<ComponentType> componentType, - std::string componentName, - const openpass::common::RuntimeInformation& runtimeInformation, - StochasticsInterface *stochastics, - WorldInterface *world, - ObservationNetworkInterface *observationNetwork, - Agent *agent, - EventNetworkInterface *eventNetwork); + std::string componentName, + const openpass::common::RuntimeInformation& runtimeInformation, + StochasticsInterface *stochastics, + WorldInterface *world, + ObservationNetworkInterface *observationNetwork, + Agent *agent, + EventNetworkInterface *eventNetwork, + PublisherInterface *publisher); //----------------------------------------------------------------------------- //! Calls the "update input" function pointer with the provided parameters and @@ -195,7 +199,6 @@ private: QLibrary *library = nullptr; ModelInterface_GetVersion getVersionFunc{nullptr}; ModelInterface_CreateInstanceType createInstanceFunc{nullptr}; - UnrestrictedEventModelInterface_CreateInstanceType createEventInstanceFunc{nullptr}; ModelInterface_DestroyInstanceType destroyInstanceFunc{nullptr}; ModelInterface_UpdateInputType updateInputFunc{nullptr}; ModelInterface_UpdateOutputType updateOutputFunc{nullptr}; diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationBinding.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationBinding.cpp index c574e39d6b93191c36ec396b9b06b80be06acc31..f9805048be39c93b1c0162517064c3415334464f 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationBinding.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationBinding.cpp @@ -30,12 +30,12 @@ ObservationModule* ObservationBinding::Instantiate(const std::string& libraryPat const openpass::parameter::ParameterSetLevel1 ¶meter, StochasticsInterface* stochastics, WorldInterface* world, - EventNetworkInterface* eventNetwork) + EventNetworkInterface* eventNetwork, + DataStoreReadInterface* const dataStore) { if (!library) { - library = new (std::nothrow) ObservationLibrary(libraryPath, - callbacks); + library = new (std::nothrow) ObservationLibrary(libraryPath, callbacks); if (!library) { return nullptr; @@ -52,7 +52,8 @@ ObservationModule* ObservationBinding::Instantiate(const std::string& libraryPat parameter, stochastics, world, - eventNetwork); + eventNetwork, + dataStore); } void ObservationBinding::Unload() diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationBinding.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationBinding.h index ca20e21a9b64fe033749e604195016cc47445ff6..0df7b0c6aef65a9df17e52dd09a59126b0b72d2e 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationBinding.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationBinding.h @@ -57,7 +57,8 @@ public: const openpass::parameter::ParameterSetLevel1& parameter, StochasticsInterface* stochastics, WorldInterface* world, - SimulationSlave::EventNetworkInterface* eventNetwork); + SimulationSlave::EventNetworkInterface* eventNetwork, + DataStoreReadInterface* dataStore); //----------------------------------------------------------------------------- //! Deletes the library mapping and all referenced observation library objects //----------------------------------------------------------------------------- diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationLibrary.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationLibrary.cpp index 83af3e7e17edf2dc45fcf8cedfcfded06c0d3186..22db70f0381cb9fd203b04d8745adf4a8b88faeb 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationLibrary.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationLibrary.cpp @@ -187,7 +187,8 @@ ObservationModule* ObservationLibrary::CreateObservationModule( const openpass::parameter::ParameterSetLevel1& parameters, StochasticsInterface* stochastics, WorldInterface* world, - EventNetworkInterface* eventNetwork) + EventNetworkInterface* eventNetwork, + DataStoreReadInterface* const dataStore) { if (!library) { @@ -211,7 +212,8 @@ ObservationModule* ObservationLibrary::CreateObservationModule( world, eventNetwork, module_parameters.get(), - callbacks); + callbacks, + dataStore); } catch (std::runtime_error const& ex) { diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationLibrary.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationLibrary.h index 07bf8c39edc04760d365133617328861279be308..edc44033e6ab3e0b0278bd2e5936c2f41417c47f 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationLibrary.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/observationInterface/observationLibrary.h @@ -38,7 +38,8 @@ public: WorldInterface* world, EventNetworkInterface* eventNetwork, const ParameterInterface* parameters, - const CallbackInterface* callbacks); + const CallbackInterface* callbacks, + DataStoreReadInterface* const dataStore); typedef void (*ObservationInterface_DestroyInstanceType)(ObservationInterface* implementation); typedef bool (*ObservationInterface_MasterPreHook)(ObservationInterface* implementation); typedef bool (*ObservationInterface_MasterPostHook)(ObservationInterface* implementation, @@ -96,7 +97,8 @@ public: const openpass::parameter::ParameterSetLevel1 ¶meters, StochasticsInterface* stochastics, WorldInterface* world, - EventNetworkInterface* eventNetwork); + EventNetworkInterface* eventNetwork, + DataStoreReadInterface* const dataStore); bool SlavePreHook(ObservationInterface* implementation) { @@ -149,6 +151,7 @@ private: std::list<ObservationModule*> observationModules; QLibrary* library = nullptr; CallbackInterface* callbacks; + ObservationInterface_GetVersion getVersionFunc{nullptr}; ObservationInterface_CreateInstanceType createInstanceFunc{nullptr}; ObservationInterface_DestroyInstanceType destroyInstanceFunc{nullptr}; diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/agentParser.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/agentParser.cpp index 291b031e7f615e5ec5fdf1b258517f8e8fc87ea1..c9d51bf093e59421a65e031a5ef0c7f7e32e8cdd 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/agentParser.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/agentParser.cpp @@ -8,24 +8,25 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -//----------------------------------------------------------------------------- -/** \file AgentParser.cpp */ -//----------------------------------------------------------------------------- - #include "agentParser.h" + #include "Interfaces/componentInterface.h" +#include "Interfaces/publisherInterface.h" #include "channel.h" +#include "tasks.h" +namespace openpass::scheduling { -namespace SimulationSlave { -namespace Scheduling { +using namespace SimulationSlave; -AgentParser::AgentParser(const int ¤tTime) : currentTime{currentTime} -{} +AgentParser::AgentParser(const int ¤tTime) : + currentTime{currentTime} +{ +} void AgentParser::Parse(const Agent &agent) { - for(const auto &componentMap : agent.GetComponents()) + for (const auto &componentMap : agent.GetComponents()) { std::list<TaskItem> taskItems; @@ -39,40 +40,35 @@ void AgentParser::Parse(const Agent &agent) std::function<bool()> triggerFunc = std::bind(&ComponentInterface::TriggerCycle, component, std::ref(currentTime)); taskItems.push_back( - { - TriggerTaskItem(agentId, priority, cycleTime, triggerDelay, triggerFunc) - }); -// std::cout << "Trigger Task: AgentId: " << agentId << " prio: " << priority << -// " cycleTime: " << cycleTime << " delay: " << triggerDelay << std::endl; + {TriggerTaskItem(agentId, priority, cycleTime, triggerDelay, triggerFunc)}); + // std::cout << "Trigger Task: AgentId: " << agentId << " prio: " << priority << + // " cycleTime: " << cycleTime << " delay: " << triggerDelay << std::endl; - for(auto& channel : component->GetOutputLinks()) + for (auto &channel : component->GetOutputLinks()) { int outputLinkId = channel.first; std::function<bool()> updateFunc = std::bind(&ComponentInterface::AcquireOutputData, component, outputLinkId, std::ref(currentTime)); taskItems.push_back( - { - UpdateTaskItem(agentId, priority, cycleTime, updateDelay, updateFunc) - }); -// std::cout << "UpdateOUT Task: AgentId: " << agentId << " prio: " << priority << -// " cycleTime: " << cycleTime << " delay: " << updateDelay << std::endl; + {UpdateTaskItem(agentId, priority, cycleTime, updateDelay, updateFunc)}); + // std::cout << "UpdateOUT Task: AgentId: " << agentId << " prio: " << priority << + // " cycleTime: " << cycleTime << " delay: " << updateDelay << std::endl; - for(auto& target : channel.second->GetTargets()) + for (auto &target : channel.second->GetTargets()) { int targetLinkId = std::get<static_cast<size_t>(Channel::TargetLinkType::LinkId)>(target); ComponentInterface *targetComponent = std::get<static_cast<size_t>(Channel::TargetLinkType::Component)>(target); std::function<bool()> updateInFunc = std::bind(&ComponentInterface::UpdateInputData, targetComponent, targetLinkId, std::ref(currentTime)); taskItems.push_back( - { - UpdateTaskItem(agentId, priority, cycleTime, updateDelay, updateInFunc) - }); -// std::cout << "UpdateIN Task: AgentId: " << agentId << " prio: " << priority << -// " cycleTime: " << cycleTime << " delay: " << updateDelay << std::endl; + {UpdateTaskItem(agentId, priority, cycleTime, updateDelay, updateInFunc)}); + // std::cout << "UpdateIN Task: AgentId: " << agentId << " prio: " << priority << + // " cycleTime: " << cycleTime << " delay: " << updateDelay << std::endl; } } - if(component->GetInit()) { + if (component->GetInit()) + { nonRecurringTasks.insert(nonRecurringTasks.end(), std::make_move_iterator(taskItems.begin()), std::make_move_iterator(taskItems.end())); @@ -96,5 +92,4 @@ std::list<TaskItem> AgentParser::GetRecurringTasks() return recurringTasks; } -} //namespace Scheduler -} //namespace SimulationSlave +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/agentParser.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/agentParser.h index 5906e1f633ae88208833d0b9468b2eb760e312d7..1faa82f5becccae78ba1419eb499162315147818 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/agentParser.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/agentParser.h @@ -19,14 +19,13 @@ #pragma once -#include <list> #include <functional> +#include <list> -#include "tasks.h" #include "agent.h" +#include "tasks.h" -namespace SimulationSlave { -namespace Scheduling { +namespace openpass::scheduling { //----------------------------------------------------------------------------- /** \brief convert agent to taskItems for Scheduling @@ -54,11 +53,10 @@ public: * * @param[in] Agent new agent */ - void Parse(const Agent &agent); + void Parse(const SimulationSlave::Agent &agent); std::list<TaskItem> GetNonRecurringTasks(); std::list<TaskItem> GetRecurringTasks(); }; -} //namespace Scheduler -} //namespace SimulationSlave +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/scheduler.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/scheduler.cpp index edaa9fd746d9d3cf83fa591d48d94f256ec4bf26..cd96329c424b602588ed612e9797ba50a6271444 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/scheduler.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/scheduler.cpp @@ -9,23 +9,23 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ +#include "scheduler.h" + +#include "CoreFramework/CoreShare/log.h" #include "agent.h" #include "agentParser.h" #include "eventNetwork.h" -#include "CoreFramework/CoreShare/log.h" #include "runResult.h" -#include "scheduler.h" -//----------------------------------------------------------------------------- -/** \file Scheduler.cpp */ -//----------------------------------------------------------------------------- -namespace SimulationSlave { +namespace openpass::scheduling { + +using namespace SimulationSlave; -Scheduler::Scheduler(WorldInterface& world, - SpawnPointNetworkInterface& spawnPointNetwork, - EventDetectorNetworkInterface& eventDetectorNetwork, - ManipulatorNetworkInterface& manipulatorNetwork, - ObservationNetworkInterface& observationNetwork) : +Scheduler::Scheduler(WorldInterface &world, + SpawnPointNetworkInterface &spawnPointNetwork, + EventDetectorNetworkInterface &eventDetectorNetwork, + ManipulatorNetworkInterface &manipulatorNetwork, + ObservationNetworkInterface &observationNetwork) : world(world), spawnPointNetwork(spawnPointNetwork), eventDetectorNetwork(eventDetectorNetwork), @@ -37,8 +37,8 @@ Scheduler::Scheduler(WorldInterface& world, bool Scheduler::Run( int startTime, int endTime, - RunResult& runResult, - EventNetworkInterface& eventNetwork) + RunResult &runResult, + EventNetworkInterface &eventNetwork) { if (startTime > endTime) { @@ -63,11 +63,11 @@ bool Scheduler::Run( auto finalizeTasks = taskBuilder.CreateFinalizeTasks(); auto taskList = SchedulerTasks( - bootstrapTasks, - commonTasks, - finalizeRecurringTasks, - finalizeTasks, - FRAMEWORK_UPDATE_RATE); + bootstrapTasks, + commonTasks, + finalizeRecurringTasks, + finalizeTasks, + FRAMEWORK_UPDATE_RATE); if (ExecuteTasks(taskList.GetBootstrapTasks()) == false) { @@ -113,10 +113,10 @@ bool Scheduler::Run( return Scheduler::SUCCESS; } -template<typename T> +template <typename T> bool Scheduler::ExecuteTasks(T tasks) { - for (const auto& task : tasks) + for (const auto &task : tasks) { if (task.func() == false) { @@ -126,17 +126,18 @@ bool Scheduler::ExecuteTasks(T tasks) return true; } -void Scheduler::UpdateAgents(SchedulerTasks& taskList, WorldInterface& world) +void Scheduler::UpdateAgents(SchedulerTasks &taskList, WorldInterface &world) { - for (const auto& agent : spawnPointNetwork.ConsumeNewAgents()) + for (const auto &agent : spawnPointNetwork.ConsumeNewAgents()) { + agent->LinkSchedulerTime(¤tTime); ScheduleAgentTasks(taskList, *agent); } std::list<int> removedAgents; - for (const auto& agentMap : world.GetAgents()) + for (const auto &agentMap : world.GetAgents()) { - AgentInterface* agent = agentMap.second; + AgentInterface *agent = agentMap.second; if (!agent->IsValid()) { removedAgents.push_back(agent->GetId()); @@ -146,7 +147,7 @@ void Scheduler::UpdateAgents(SchedulerTasks& taskList, WorldInterface& world) taskList.DeleteAgentTasks(removedAgents); } -void Scheduler::ScheduleAgentTasks(SchedulerTasks& taskList, const Agent& agent) +void Scheduler::ScheduleAgentTasks(SchedulerTasks &taskList, const Agent &agent) { AgentParser agentParser(currentTime); agentParser.Parse(agent); @@ -155,4 +156,4 @@ void Scheduler::ScheduleAgentTasks(SchedulerTasks& taskList, const Agent& agent) taskList.ScheduleNewNonRecurringTasks(agentParser.GetNonRecurringTasks()); } -} // namespace SimulationSlave +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/scheduler.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/scheduler.h index 54e6c0881b5e4f9492958862400924b69a78f2b6..dd9dc1c598cda283a7165fff7edeba901cdfc1de 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/scheduler.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/scheduler.h @@ -9,26 +9,24 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -//----------------------------------------------------------------------------- -//! @file Scheduler.h -//! @brief This file contains the generic schedule managing component -//----------------------------------------------------------------------------- - #pragma once #include <functional> #include <memory> + #include "Interfaces/worldInterface.h" -#include "taskBuilder.h" #include "schedulerTasks.h" +#include "taskBuilder.h" +#include "timeKeeper.h" -namespace SimulationSlave -{ - +namespace SimulationSlave { class RunResult; class EventNetworkInterface; class SchedulePolicy; class SpawnPointNetworkInterface; +} // namespace SimulationSlave + +namespace openpass::scheduling { //----------------------------------------------------------------------------- /** \brief execute all tasks for an simulation run @@ -42,15 +40,15 @@ class SpawnPointNetworkInterface; class Scheduler { public: - static constexpr bool FAILURE { false }; - static constexpr bool SUCCESS { true }; - static constexpr int FRAMEWORK_UPDATE_RATE { 100 }; + static constexpr bool FAILURE{false}; + static constexpr bool SUCCESS{true}; + static constexpr int FRAMEWORK_UPDATE_RATE{100}; Scheduler(WorldInterface &world, - SpawnPointNetworkInterface &spawnPointNetwork, - EventDetectorNetworkInterface &eventDetectorNetwork, - ManipulatorNetworkInterface &manipulatorNetwork, - ObservationNetworkInterface &observationNetwork); + SimulationSlave::SpawnPointNetworkInterface &spawnPointNetwork, + SimulationSlave::EventDetectorNetworkInterface &eventDetectorNetwork, + SimulationSlave::ManipulatorNetworkInterface &manipulatorNetwork, + SimulationSlave::ObservationNetworkInterface &observationNetwork); /*! * \brief Run @@ -65,7 +63,7 @@ public: */ bool Run(int startTime, int endTime, - RunResult &runResult, + SimulationSlave::RunResult &runResult, SimulationSlave::EventNetworkInterface &eventNetwork); /*! @@ -77,16 +75,16 @@ public: * @param[in] taskList current task list * @param[in] Agent new agent */ - void ScheduleAgentTasks(SchedulerTasks& taskList, const Agent& agent); + void ScheduleAgentTasks(SchedulerTasks &taskList, const SimulationSlave::Agent &agent); -private: +private: WorldInterface &world; - SpawnPointNetworkInterface &spawnPointNetwork; - EventDetectorNetworkInterface &eventDetectorNetwork; - ManipulatorNetworkInterface &manipulatorNetwork; - ObservationNetworkInterface &observationNetwork; + SimulationSlave::SpawnPointNetworkInterface &spawnPointNetwork; + SimulationSlave::EventDetectorNetworkInterface &eventDetectorNetwork; + SimulationSlave::ManipulatorNetworkInterface &manipulatorNetwork; + SimulationSlave::ObservationNetworkInterface &observationNetwork; - int currentTime {0}; + int ¤tTime{openpass::scheduling::TimeKeeper::time}; /*! * \brief UpdateAgents @@ -107,10 +105,8 @@ private: * @param[in] tasks execute function of given tasks * @return false, if a task reports error */ - template<typename T> + template <typename T> bool ExecuteTasks(T tasks); }; -} // namespace SimulationSlave - - +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/schedulerTasks.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/schedulerTasks.cpp index 996768860f588454b8c597b513473388af006c4b..6312742c942f48fd1442e587b41c40212096bbf9 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/schedulerTasks.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/schedulerTasks.cpp @@ -8,17 +8,17 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ +#include "schedulerTasks.h" + #include <algorithm> +#include <stdexcept> #include <utility> -#include "schedulerTasks.h" - //----------------------------------------------------------------------------- /** \file SchedulerTasks.cpp */ //----------------------------------------------------------------------------- -namespace SimulationSlave { -namespace Scheduling { +namespace openpass::scheduling { SchedulerTasks::SchedulerTasks(std::list<TaskItem> bootstrapTasks, std::list<TaskItem> commonTasks, @@ -29,7 +29,7 @@ SchedulerTasks::SchedulerTasks(std::list<TaskItem> bootstrapTasks, this->bootstrapTasks.tasks = std::multiset<TaskItem>(bootstrapTasks.begin(), bootstrapTasks.end()); this->commonTasks.tasks = std::multiset<TaskItem>(commonTasks.begin(), commonTasks.end()); this->finalizeRecurringTasks.tasks = std::multiset<TaskItem>(finalizeRecurringTasks.begin(), - finalizeRecurringTasks.end()); + finalizeRecurringTasks.end()); this->finalizeTasks.tasks = std::multiset<TaskItem>(finalizeTasks.begin(), finalizeTasks.end()); this->scheduledTimestampsInterval = scheduledTimestampsInterval; @@ -48,9 +48,9 @@ void SchedulerTasks::ScheduleNewNonRecurringTasks(std::list<TaskItem> newTasks) ScheduleNewTasks(nonRecurringTasks, newTasks); } -void SchedulerTasks::ScheduleNewTasks(Tasks& tasks, std::list<TaskItem> newTasks) +void SchedulerTasks::ScheduleNewTasks(Tasks &tasks, std::list<TaskItem> newTasks) { - for (const auto& newTask : newTasks) + for (const auto &newTask : newTasks) { tasks.AddTask(newTask); UpdateScheduledTimestamps(newTask.cycletime, newTask.delay); @@ -72,8 +72,8 @@ void SchedulerTasks::UpdateScheduledTimestamps(int cycleTime, int delay) int currentScheduleTime = cycleTime + delay; int numberOfSkippedTimestamps = std::max(0, - (lowerBoundOfScheduledTimestamps - currentScheduleTime + cycleTime - 1) / - cycleTime); //We add cycletime -1 because we want to round up + (lowerBoundOfScheduledTimestamps - currentScheduleTime + cycleTime - 1) / + cycleTime); //We add cycletime -1 because we want to round up currentScheduleTime += cycleTime * numberOfSkippedTimestamps; if (currentScheduleTime <= upperBoundOfScheduledTimestamps) @@ -87,9 +87,9 @@ void SchedulerTasks::UpdateScheduledTimestamps(int cycleTime, int delay) // scheduledTimesteps higher than horizon will be considered on next timestamp } -void SchedulerTasks::UpdateScheduledTimestamps(std::multiset<TaskItem>& tasks) +void SchedulerTasks::UpdateScheduledTimestamps(std::multiset<TaskItem> &tasks) { - for (const auto& task : tasks) + for (const auto &task : tasks) { UpdateScheduledTimestamps(task.cycletime, task.delay); } @@ -110,7 +110,7 @@ int SchedulerTasks::GetNextTimestamp(int timestamp) { ExpandUpperBoundary(timestamp); - for (const auto& scheduledTimestamp : scheduledTimestamps) + for (const auto &scheduledTimestamp : scheduledTimestamps) { if (scheduledTimestamp > timestamp) { @@ -132,9 +132,9 @@ void SchedulerTasks::ExpandUpperBoundary(int timestamp) // we are not time travelling.. backwards is illogical } -void SchedulerTasks::GetTasks(int timestamp, std::multiset<TaskItem>& tasks, std::list<TaskItem>& currentTasks) +void SchedulerTasks::GetTasks(int timestamp, std::multiset<TaskItem> &tasks, std::list<TaskItem> ¤tTasks) { - for (const auto& task : tasks) + for (const auto &task : tasks) { if (task.cycletime == 0) { @@ -189,7 +189,7 @@ std::list<TaskItem> SchedulerTasks::GetRecurringTasks(int timestamp) return currentTasks; } -void SchedulerTasks::PullNonRecurringTasks(int timestamp, std::list<TaskItem>& currentTasks) +void SchedulerTasks::PullNonRecurringTasks(int timestamp, std::list<TaskItem> ¤tTasks) { GetTasks(timestamp, nonRecurringTasks.tasks, currentTasks); ClearNonrecurringTasks(); @@ -216,9 +216,9 @@ void SchedulerTasks::DeleteAgentTasks(int agentId) DeleteAgentTasks(agentIds); } -void SchedulerTasks::DeleteAgentTasks(std::list<int>& agentIds) +void SchedulerTasks::DeleteAgentTasks(std::list<int> &agentIds) { - for (const auto& agentId : agentIds) + for (const auto &agentId : agentIds) { recurringTasks.DeleteTasks(agentId); nonRecurringTasks.DeleteTasks(agentId); //if agent immediately will be removed after spawning @@ -230,5 +230,4 @@ void SchedulerTasks::DeleteAgentTasks(std::list<int>& agentIds) } } -} // namespace Scheduling -} // namespace SimulationSlave +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/schedulerTasks.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/schedulerTasks.h index 2225010a1ac31dc362e164003f7a3536cbb0f315..52b6c69262431aeb51f84f6cde46455d9f8c7129 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/schedulerTasks.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/schedulerTasks.h @@ -15,13 +15,12 @@ #pragma once -#include <set> #include <list> +#include <set> #include "tasks.h" -namespace SimulationSlave { -namespace Scheduling { +namespace openpass::scheduling { //----------------------------------------------------------------------------- /** \brief managing timing of all given tasks @@ -172,7 +171,7 @@ private: * @param[in] tasks tasks to filter by current timestamp * @param[out] list of TaskItems filtered tasks */ - void GetTasks(int timestamp, std::multiset<TaskItem>& tasks, std::list<TaskItem> ¤tTasks); + void GetTasks(int timestamp, std::multiset<TaskItem> &tasks, std::list<TaskItem> ¤tTasks); /*! * \brief UpdateScheduledTimestamps @@ -224,6 +223,4 @@ private: int lowerBoundOfScheduledTimestamps; }; - -} // namespace Scheduling -} // namespace SimulationSlave +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/taskBuilder.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/taskBuilder.cpp index 02a047f3ecd526cf2543a5db264879d01fbf0ceb..e4173ccbd70b4f730acf67c3cd63796432b0d848 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/taskBuilder.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/taskBuilder.cpp @@ -12,24 +12,25 @@ /** \file TaskBuilder.cpp */ //----------------------------------------------------------------------------- +#include "taskBuilder.h" +#include <algorithm> #include <functional> -#include "taskBuilder.h" + #include "eventDetector.h" #include "manipulator.h" -#include <algorithm> using namespace SimulationSlave; -using namespace SimulationSlave::Scheduling; +namespace openpass::scheduling { -TaskBuilder::TaskBuilder(const int& currentTime, - RunResult& runResult, +TaskBuilder::TaskBuilder(const int ¤tTime, + RunResult &runResult, const int frameworkUpdateRate, - WorldInterface* const world, - SpawnPointNetworkInterface* const spawnPointNetwork, - ObservationNetworkInterface* const observationNetwork, - EventDetectorNetworkInterface* const eventDetectorNetwork, - ManipulatorNetworkInterface* const manipulatorNetwork) : + WorldInterface *const world, + SpawnPointNetworkInterface *const spawnPointNetwork, + ObservationNetworkInterface *const observationNetwork, + EventDetectorNetworkInterface *const eventDetectorNetwork, + ManipulatorNetworkInterface *const manipulatorNetwork) : currentTime{currentTime}, runResult{runResult}, frameworkUpdateRate{frameworkUpdateRate}, @@ -48,8 +49,8 @@ std::list<TaskItem> TaskBuilder::CreateBootstrapTasks() std::list<TaskItem> items; items.emplace_back(ObservationTaskItem(frameworkUpdateRate, - std::bind(&ObservationNetworkInterface::UpdateTimeStep, - observationNetwork, std::ref(currentTime), std::ref(runResult)))); + std::bind(&ObservationNetworkInterface::UpdateTimeStep, + observationNetwork, std::ref(currentTime), std::ref(runResult)))); items.emplace_back(SpawningTaskItem(frameworkUpdateRate, std::bind(&SpawnPointNetworkInterface::TriggerPreRunSpawnPoints, @@ -60,7 +61,7 @@ std::list<TaskItem> TaskBuilder::CreateBootstrapTasks() std::list<TaskItem> TaskBuilder::CreateCommonTasks() { - std::list<TaskItem> items {}; + std::list<TaskItem> items{}; items.emplace_back(SpawningTaskItem(frameworkUpdateRate, std::bind(&SpawnPointNetworkInterface::TriggerRuntimeSpawnPoints, spawnPointNetwork, @@ -70,61 +71,58 @@ std::list<TaskItem> TaskBuilder::CreateCommonTasks() std::copy(std::begin(manipulatorTasks), std::end(manipulatorTasks), std::back_inserter(items)); items.emplace_back(ObservationTaskItem(frameworkUpdateRate, std::bind( - &ObservationNetworkInterface::UpdateTimeStep, - observationNetwork, - std::ref(currentTime), std::ref(runResult)))); + &ObservationNetworkInterface::UpdateTimeStep, + observationNetwork, + std::ref(currentTime), std::ref(runResult)))); return items; } std::list<TaskItem> TaskBuilder::CreateFinalizeRecurringTasks() { - return std::list<TaskItem> - { - SyncWorldTaskItem(ScheduleAtEachCycle, std::bind(&WorldInterface::SyncGlobalData, world)) - }; + return std::list<TaskItem>{ + SyncWorldTaskItem(ScheduleAtEachCycle, std::bind(&WorldInterface::SyncGlobalData, world))}; } std::list<TaskItem> TaskBuilder::CreateFinalizeTasks() { - std::list<TaskItem> items {}; + std::list<TaskItem> items{}; std::copy(std::begin(eventDetectorTasks), std::end(eventDetectorTasks), std::back_inserter(items)); std::copy(std::begin(manipulatorTasks), std::end(manipulatorTasks), std::back_inserter(items)); items.emplace_back(ObservationTaskItem(frameworkUpdateRate, std::bind( - &ObservationNetworkInterface::UpdateTimeStep, - observationNetwork, - std::ref(currentTime), - std::ref(runResult)))); + &ObservationNetworkInterface::UpdateTimeStep, + observationNetwork, + std::ref(currentTime), + std::ref(runResult)))); return items; } void TaskBuilder::BuildEventDetectorTasks() { - const auto& eventDetectors = eventDetectorNetwork->GetEventDetectors(); + const auto &eventDetectors = eventDetectorNetwork->GetEventDetectors(); std::transform(std::begin(eventDetectors), std::end(eventDetectors), std::back_inserter(eventDetectorTasks), - [&](auto eventDetector) - { - return EventDetectorTaskItem(frameworkUpdateRate, std::bind( - &EventDetectorInterface::Trigger, - eventDetector->GetImplementation(), - std::ref(currentTime))); - }); + [&](auto eventDetector) { + return EventDetectorTaskItem(frameworkUpdateRate, std::bind( + &EventDetectorInterface::Trigger, + eventDetector->GetImplementation(), + std::ref(currentTime))); + }); } void TaskBuilder::BuildManipulatorTasks() { - const auto& manipulators = manipulatorNetwork->GetManipulators(); + const auto &manipulators = manipulatorNetwork->GetManipulators(); std::transform(std::begin(manipulators), std::end(manipulators), std::back_inserter(manipulatorTasks), - [&](auto manipulator) - { - return EventDetectorTaskItem(frameworkUpdateRate, std::bind( - &ManipulatorInterface::Trigger, - manipulator->GetImplementation(), - std::ref(currentTime))); - }); + [&](auto manipulator) { + return EventDetectorTaskItem(frameworkUpdateRate, std::bind( + &ManipulatorInterface::Trigger, + manipulator->GetImplementation(), + std::ref(currentTime))); + }); } +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/taskBuilder.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/taskBuilder.h index cac019ff6de432a214c347fc17c0568c9137f0da..8c9a56ced4288013c8d674e42705137e579eca22 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/taskBuilder.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/taskBuilder.h @@ -17,20 +17,18 @@ //----------------------------------------------------------------------------- #include <functional> -#include <vector> #include <list> +#include <vector> -#include "tasks.h" #include "Interfaces/spawnPointNetworkInterface.h" #include "Interfaces/worldInterface.h" -#include "runResult.h" -#include "observationNetwork.h" #include "eventDetectorNetwork.h" #include "manipulatorNetwork.h" +#include "observationNetwork.h" +#include "runResult.h" +#include "tasks.h" -using namespace SimulationSlave; -using namespace Scheduling; - +namespace openpass::scheduling { //----------------------------------------------------------------------------- /** \brief interface of taskBuilder * @@ -41,10 +39,10 @@ using namespace Scheduling; class TaskBuilderInterface { public: - virtual std::list<TaskItem> CreateBootstrapTasks()= 0; + virtual std::list<TaskItem> CreateBootstrapTasks() = 0; virtual std::list<TaskItem> CreateCommonTasks() = 0; virtual std::list<TaskItem> CreateFinalizeRecurringTasks() = 0; - virtual std::list<TaskItem> CreateFinalizeTasks() = 0; + virtual std::list<TaskItem> CreateFinalizeTasks() = 0; }; //----------------------------------------------------------------------------- @@ -58,16 +56,15 @@ class TaskBuilder : public TaskBuilderInterface { private: const int ¤tTime; - RunResult &runResult; + SimulationSlave::RunResult &runResult; const int frameworkUpdateRate; const int ScheduleAtEachCycle = 0; - - WorldInterface* const world; - SpawnPointNetworkInterface* const spawnPointNetwork; - ObservationNetworkInterface* const observationNetwork; - EventDetectorNetworkInterface* const eventDetectorNetwork; - ManipulatorNetworkInterface* const manipulatorNetwork; + WorldInterface *const world; + SimulationSlave::SpawnPointNetworkInterface *const spawnPointNetwork; + SimulationSlave::ObservationNetworkInterface *const observationNetwork; + SimulationSlave::EventDetectorNetworkInterface *const eventDetectorNetwork; + SimulationSlave::ManipulatorNetworkInterface *const manipulatorNetwork; std::list<TaskItem> eventDetectorTasks; std::list<TaskItem> manipulatorTasks; @@ -91,13 +88,13 @@ private: public: TaskBuilder(const int ¤tTime, - RunResult &runResult, - const int frameworkUpdateRate, - WorldInterface* const world, - SpawnPointNetworkInterface* const spawnPointNetwork, - ObservationNetworkInterface * const observationNetwork, - EventDetectorNetworkInterface* const eventDetectorNetwork, - ManipulatorNetworkInterface* const manipulatorNetwork); + SimulationSlave::RunResult &runResult, + const int frameworkUpdateRate, + WorldInterface *const world, + SimulationSlave::SpawnPointNetworkInterface *const spawnPointNetwork, + SimulationSlave::ObservationNetworkInterface *const observationNetwork, + SimulationSlave::EventDetectorNetworkInterface *const eventDetectorNetwork, + SimulationSlave::ManipulatorNetworkInterface *const manipulatorNetwork); virtual ~TaskBuilder() = default; /*! @@ -139,5 +136,6 @@ public: * @return tasks final tasks of finalize phase */ std::list<TaskItem> CreateFinalizeTasks() override; - }; + +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/tasks.cpp b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/tasks.cpp index b1eacfb0edc48670183aa78834fae22b3d8be1eb..2c6669e8917b1fbd63db9ec95adce474953b2085 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/tasks.cpp +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/tasks.cpp @@ -14,10 +14,9 @@ /** \file Tasks.cpp */ //----------------------------------------------------------------------------- -namespace SimulationSlave { -namespace Scheduling { +namespace openpass::scheduling { -void Tasks::AddTask(const TaskItem& newTask) +void Tasks::AddTask(const TaskItem &newTask) { tasks.insert(newTask); } @@ -38,13 +37,13 @@ void Tasks::DeleteTasks(int agentId) } } -bool TaskItem::operator<(const TaskItem& rhs) const +bool TaskItem::operator<(const TaskItem &rhs) const { return (priority > rhs.priority || ((priority == rhs.priority) && (taskType < rhs.taskType))); } -bool TaskItem::operator==(const TaskItem& rhs) const +bool TaskItem::operator==(const TaskItem &rhs) const { return (priority == rhs.priority && cycletime == rhs.cycletime && @@ -53,5 +52,4 @@ bool TaskItem::operator==(const TaskItem& rhs) const taskType == rhs.taskType); } -} // namespace Scheduling -} // namespace SimulationSlave +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/tasks.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/tasks.h index f04284b741c80a2237e0bf0f6e5f7a53d64ef867..a27ba44ff368bc4f09164eb3f55276c93b15c404 100644 --- a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/tasks.h +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/tasks.h @@ -19,11 +19,10 @@ //----------------------------------------------------------------------------- #include <exception> -#include <set> #include <functional> +#include <set> -namespace SimulationSlave { -namespace Scheduling { +namespace openpass::scheduling { enum TaskType { @@ -61,12 +60,14 @@ public: delay(delay), taskType(taskType), func(func) - {} + { + } virtual ~TaskItem() = default; static constexpr int VALID_FOR_ALL_AGENTS = -1; static constexpr int NO_DELAY = 0; + static constexpr int PRIORITY_PRESPAWNING = 6; static constexpr int PRIORITY_SPAWNING = 5; static constexpr int PRIORITY_EVENTDETECTOR = 4; static constexpr int PRIORITY_MANIPULATOR = 3; @@ -74,8 +75,8 @@ public: static constexpr int PRIORITY_UPDATEGLOBALDRIVINGVIEW = 1; static constexpr int PRIORITY_OBSERVATION = 0; - bool operator<(const TaskItem& rhs) const; - bool operator==(const TaskItem& rhs) const; + bool operator<(const TaskItem &rhs) const; + bool operator==(const TaskItem &rhs) const; }; /*! @@ -101,7 +102,9 @@ class TriggerTaskItem : public TaskItem { public: TriggerTaskItem(int agentId, int priority, int cycleTime, int delay, std::function<bool()> func) : - TaskItem(agentId, priority, cycleTime, delay, TaskType::Trigger, func) {} + TaskItem(agentId, priority, cycleTime, delay, TaskType::Trigger, func) + { + } }; //----------------------------------------------------------------------------- @@ -127,7 +130,9 @@ public: SpawningTaskItem(int cycleTime, std::function<bool()> func) : TaskItem(VALID_FOR_ALL_AGENTS, PRIORITY_SPAWNING, cycleTime, NO_DELAY, TaskType::Spawning, - func) { } + func) + { + } }; //----------------------------------------------------------------------------- @@ -140,7 +145,9 @@ public: EventDetectorTaskItem(int cycleTime, std::function<void()> func) : TaskItem(VALID_FOR_ALL_AGENTS, PRIORITY_EVENTDETECTOR, cycleTime, NO_DELAY, TaskType::EventDetector, - std::bind(&voidFunctionWrapper, func)) { } + std::bind(&voidFunctionWrapper, func)) + { + } }; //----------------------------------------------------------------------------- @@ -153,7 +160,9 @@ public: ManipulatorTaskItem(int cycleTime, std::function<void()> func) : TaskItem(VALID_FOR_ALL_AGENTS, PRIORITY_MANIPULATOR, cycleTime, NO_DELAY, TaskType::Manipulator, - std::bind(&voidFunctionWrapper, func)) { } + std::bind(&voidFunctionWrapper, func)) + { + } }; //----------------------------------------------------------------------------- @@ -180,7 +189,9 @@ public: SyncWorldTaskItem(int cycleTime, std::function<void()> func) : TaskItem(VALID_FOR_ALL_AGENTS, PRIORITY_SYNCGLOBALDATA, cycleTime, NO_DELAY, TaskType::SyncGlobalData, - std::bind(&voidFunctionWrapper, func)) { } + std::bind(&voidFunctionWrapper, func)) + { + } }; //----------------------------------------------------------------------------- @@ -206,7 +217,6 @@ public: class Tasks { - public: /*! * \brief AddTask @@ -216,7 +226,7 @@ public: * * @param[in] TaskItem subclass of taskItem */ - void AddTask(const TaskItem& newTask); + void AddTask(const TaskItem &newTask); /*! * \brief DeleteTasks @@ -231,6 +241,4 @@ public: std::multiset<TaskItem> tasks; }; - -} // namespace Scheduling -} // namespace SimulationSlave +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/timeKeeper.h b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/timeKeeper.h new file mode 100644 index 0000000000000000000000000000000000000000..7e37796b5053719abfdf01797457269833548530 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreFramework/OpenPassSlave/scheduler/timeKeeper.h @@ -0,0 +1,39 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#pragma once + +namespace openpass::scheduling { + +class Scheduler; + +/// \brief Allows core components to access the current schedule time without need for a direct reference +/// \note The scheduler holds a manipulate reference to the current time provided by this instance +/// +/// \code{.cpp} +/// auto currentTime = openpass::scheduling::TimeKeeper::Now(); +/// \endcode +class TimeKeeper +{ + friend class Scheduler; + +protected: + static inline int time{-1}; //!< Global time for the simulator + +public: + /// \brief Get the current simulation time + /// \return Current simulation time + static int Now() noexcept + { + return time; + } +}; + +} // namespace openpass::scheduling diff --git a/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/BasicDataStore.pro b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/BasicDataStore.pro new file mode 100644 index 0000000000000000000000000000000000000000..7b987fd146b014f922d22e4268ee5faa0b995bf0 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/BasicDataStore.pro @@ -0,0 +1,31 @@ +# /********************************************************************* +# * Copyright (c) 2020 in-tech GmbH +# * +# * This program and the accompanying materials are made +# * available under the terms of the Eclipse Public License 2.0 +# * which is available at https://www.eclipse.org/legal/epl-2.0/ +# * +# * SPDX-License-Identifier: EPL-2.0 +# **********************************************************************/ + +#----------------------------------------------------------------------------- +# \file BasicDataStore.pro +# \brief This file contains the information for the QtCreator-project of the +# module BasicDataStore +#-----------------------------------------------------------------------------/ + +CONFIG += OPENPASS_LIBRARY +DEFINES += BASIC_DATASTORE_LIBRARY + +include(../../../global.pri) + +INCLUDEPATH += \ + ../../CoreFrameWork/CoreShare + +SOURCES += \ + basicDataStore.cpp \ + basicDataStoreImplementation.cpp + +HEADERS += \ + basicDataStore.h \ + basicDataStoreImplementation.h diff --git a/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStore.cpp b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStore.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0e8b4ec6a3ba37859b4c1e61b2fbd8133583ba5 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStore.cpp @@ -0,0 +1,72 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +//----------------------------------------------------------------------------- +/** \file basicDataStore.cpp */ +//----------------------------------------------------------------------------- + +#include "basicDataStore.h" +#include "basicDataStoreImplementation.h" + +const std::string Version = "1.0.0"; //!< The version of the current module - has to be incremented manually + +//----------------------------------------------------------------------------- +//! dll-function to obtain the version of the current module +//! +//! @return Version of the current module +//----------------------------------------------------------------------------- +extern "C" BASIC_DATASTORE_SHARED_EXPORT const std::string& OpenPASS_GetVersion() +{ + return Version; +} + +//----------------------------------------------------------------------------- +//! dll-function to create an instance of the module +//! +//! @param[in] parameters Pointer to the parameters of the module +//! @param[in] callbacks Pointer to the callbacks +//! +//! @return A pointer to the created module instance +//----------------------------------------------------------------------------- +extern "C" BASIC_DATASTORE_SHARED_EXPORT DataStoreInterface* OpenPASS_CreateInstance(const openpass::common::RuntimeInformation* runtimeInformation, const CallbackInterface* callbacks) +{ + try + { + return (DataStoreInterface*)(new (std::nothrow) BasicDataStoreImplementation(runtimeInformation, callbacks)); + } + catch (const std::runtime_error& ex) + { + if (callbacks != nullptr) + { + callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, ex.what()); + } + + return nullptr; + } + catch (...) + { + if (callbacks != nullptr) + { + callbacks->Log(CbkLogLevel::Error, __FILE__, __LINE__, "unexpected exception"); + } + + return nullptr; + } +} + +//----------------------------------------------------------------------------- +//! dll-function to destroy/delete an instance of the module +//! +//! @param[in] implementation The instance that should be freed +//----------------------------------------------------------------------------- +extern "C" BASIC_DATASTORE_SHARED_EXPORT void OpenPASS_DestroyInstance(DataStoreInterface* implementation) +{ + delete implementation; +} diff --git a/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStore.h b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStore.h new file mode 100644 index 0000000000000000000000000000000000000000..e38632774490f1e4dffacc7d41c1ecca95a4b518 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStore.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +//----------------------------------------------------------------------------- +/** @file basicDataStore.h +* @brief This file provides the exported methods. +* +* This file provides the exported methods which are available outside of the library. +*/ +//----------------------------------------------------------------------------- + +#pragma once + +#include "basicDataStoreGlobal.h" +#include "Interfaces/dataStoreInterface.h" diff --git a/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStoreGlobal.h b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStoreGlobal.h new file mode 100644 index 0000000000000000000000000000000000000000..2c76c815ab213968d7d908506c5ffb5bef6c4c12 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStoreGlobal.h @@ -0,0 +1,26 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +/** + * \file basicDataStoreGlobal.h + * \brief This file contains DLL export declarations + */ + +#pragma once + +#include <QtCore/qglobal.h> + +#if defined(BASIC_DATASTORE_LIBRARY) +# define BASIC_DATASTORE_SHARED_EXPORT Q_DECL_EXPORT //! Export of the dll-functions +#else +# define BASIC_DATASTORE_SHARED_EXPORT Q_DECL_IMPORT //! Import of the dll-functions +#endif + + diff --git a/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStoreImplementation.cpp b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStoreImplementation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f15c79254e27a3b4d108f94c2870d5ace5d573f --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStoreImplementation.cpp @@ -0,0 +1,391 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +//----------------------------------------------------------------------------- +/** \file basicDataStoreImplementation.cpp */ +//----------------------------------------------------------------------------- + +#include "basicDataStoreImplementation.h" + +#include <memory> +#include <utility> + +#include "Common/commonTools.h" +#include "Common/openPassUtils.h" +#include "Interfaces/parameterInterface.h" +#include "Interfaces/stochasticsInterface.h" +#include "Interfaces/worldInterface.h" + +using namespace openpass::type; + +/*! + * \brief Tests, if two vectors of tokens have matching elements + * + * The test result will be true, if each token A in the matcher, the token B at the same position (index) in the reference are string equal. + * A matcher token containing \c openpass::datastore::WILDCARD ('*') will match every string in the reference. + * The test result will always be false, if the matcher contains more elements than the reference. + * + * \param[in] matcher Tokens to test against reference + * \param[out] reference A full stack of tokens to match against (i. e. a 'path' of DataStore keys in the DataStore hierarchy) + * + * \return True if the token vectores are considered to be matching, false otherwise. + */ +static bool TokensMatch(const Tokens& matcher, const Tokens& reference) +{ + if (matcher.size() > reference.size()) + { + return false; + } + + for (size_t pos = 0; pos < matcher.size(); ++pos) + { + if (matcher[pos] != WILDCARD && matcher[pos] != reference[pos]) + { + return false; + } + } + + return true; +} + +CyclicResult::CyclicResult(const CyclicStore& store, const CyclicRowRefs& elements) : + store{store}, + elements{elements} +{ +} + +size_t CyclicResult::size() const +{ + return elements.size(); +} + +const CyclicRow& CyclicResult::at(const size_t index) const +{ + return elements.at(index); +} + +CyclicRowRefs::const_iterator CyclicResult::begin() const +{ + return elements.cbegin(); +} + +CyclicRowRefs::const_iterator CyclicResult::end() const +{ + return elements.cend(); +} + +AcyclicResult::AcyclicResult(const AcyclicStore& store, const AcyclicRowRefs& elements) : + store{store}, + elements{elements} +{ +} + +size_t AcyclicResult::size() const +{ + return elements.size(); +} + +const AcyclicRow& AcyclicResult::at(const size_t index) const +{ + return elements.at(index); +} + +AcyclicRowRefs::const_iterator AcyclicResult::begin() const +{ + return elements.cbegin(); +} + +AcyclicRowRefs::const_iterator AcyclicResult::end() const +{ + return elements.cend(); +} + +BasicDataStoreImplementation::BasicDataStoreImplementation(const openpass::common::RuntimeInformation *runtimeInformation, const CallbackInterface *callbacks) : + DataStoreInterface(runtimeInformation, callbacks) +{ +} + +template <> +std::unique_ptr<CyclicResultInterface> BasicDataStoreImplementation::GetIndexed<EntityId>([[maybe_unused]] const std::optional<Timestamp> time, const std::optional<EntityId> entityId, const Tokens &tokens) const +{ + CyclicRowRefs rowRefs; + + auto range = entityIdIndex.equal_range(entityId.value()); + + for (auto it = range.first; it != range.second; ++it) + { + const auto& storeValue = cyclicStore.at(it->second); + + if (TokensMatch(tokens, Tokens{storeValue.key})) + { + rowRefs.emplace_back(storeValue); + } + } + + return std::make_unique<CyclicResult>(cyclicStore, rowRefs); +} + +template <> +std::unique_ptr<CyclicResultInterface> BasicDataStoreImplementation::GetIndexed<Timestamp>(const std::optional<Timestamp> time, [[maybe_unused]] const std::optional<EntityId> entityId, const Tokens &tokens) const +{ + CyclicRowRefs rowRefs; + + auto range = timestampIndex.equal_range(time.value()); + + for (auto it = range.first; it != range.second; ++it) + { + const auto& storeValue = cyclicStore.at(it->second); + + if (TokensMatch(tokens, CommonHelper::TokenizeString(storeValue.key, SEPARATOR[0]))) + { + rowRefs.emplace_back(storeValue); + } + } + + return std::make_unique<CyclicResult>(cyclicStore, rowRefs); +} + +template <> +std::unique_ptr<CyclicResultInterface> BasicDataStoreImplementation::GetIndexed<Timestamp, EntityId>(const std::optional<Timestamp> time, const std::optional<EntityId> entityId, const Tokens &tokens) const +{ + std::vector<size_t> filteredIndexes; + CyclicRowRefs rowRefs; + + auto range = timeAndEntityIdIndex.equal_range(std::make_tuple(time.value(), entityId.value())); + + for (auto it = range.first; it != range.second; ++it) + { + const auto& storeValue = cyclicStore.at(it->second); + + if (TokensMatch(tokens, CommonHelper::TokenizeString(storeValue.key, SEPARATOR[0]))) + { + rowRefs.emplace_back(storeValue); + } + } + + return std::make_unique<CyclicResult>(cyclicStore, rowRefs); +} + +std::unique_ptr<CyclicResultInterface> BasicDataStoreImplementation::GetCyclic(const Key& key) const +{ + const Tokens tokens = CommonHelper::TokenizeString(key, SEPARATOR[0]); + CyclicRowRefs rowRefs; + + for (const auto& storeValue : cyclicStore) + { + if (TokensMatch(tokens, CommonHelper::TokenizeString(storeValue.key, SEPARATOR[0]))) + { + rowRefs.emplace_back(storeValue); + } + } + + return std::make_unique<CyclicResult>(cyclicStore, rowRefs); +} + +std::unique_ptr<CyclicResultInterface> BasicDataStoreImplementation::GetCyclic(const std::optional<Timestamp> time, const std::optional<EntityId> entityId, const Key &key) const +{ + const Tokens tokens = CommonHelper::TokenizeString(key, SEPARATOR[0]); + + if (!time.has_value() && entityId.has_value()) + { + return GetIndexed<EntityId>(time, entityId, tokens); + } + else if (time.has_value() && !entityId.has_value()) + { + return GetIndexed<Timestamp>(time, entityId, tokens); + } + else if (time.has_value() && entityId.has_value()) + { + return GetIndexed<Timestamp, EntityId>(time, entityId, tokens); + } + else + { + return GetCyclic(key); + } +} + +void BasicDataStoreImplementation::PutCyclic(const Timestamp time, const EntityId agentId, const Key &key, const Value &value) +{ + cyclicStore.emplace_back(time, agentId, key, value); + + size_t newValueIndex = cyclicStore.size() - 1; + timestampIndex.emplace(time, newValueIndex); + entityIdIndex.emplace(agentId, newValueIndex); + timeAndEntityIdIndex.emplace(std::tuple(time, agentId), newValueIndex); +} + +void BasicDataStoreImplementation::PutAcyclic(const Timestamp time, const EntityId entityId, const Key &key, const openpass::datastore::Acyclic&acyclic) +{ + acyclicStore.emplace_back(time, entityId, key, acyclic); +} + +void BasicDataStoreImplementation::PutStatic(const Key &key, const Value &value, bool persist) +{ + if (staticStore.find(key) == staticStore.end()) + { + staticStore[key] = {value, persist}; + } +} + +void BasicDataStoreImplementation::Clear() +{ + cyclicStore.clear(); + entityIdIndex.clear(); + timestampIndex.clear(); + timeAndEntityIdIndex.clear(); + + acyclicStore.clear(); + + auto it = staticStore.begin(); + + while (it != staticStore.end()) + { + if (std::get<Persistence>(it->second) == false) + { + it = staticStore.erase(it); + } + else + { + ++it; + } + } +} + +std::unique_ptr<AcyclicResultInterface> BasicDataStoreImplementation::GetAcyclic(const Key& key) const +{ + const Tokens tokens = CommonHelper::TokenizeString(key, SEPARATOR[0]); + + AcyclicRowRefs rowRefs; + + for (const auto& storeValue : acyclicStore) + { + if (TokensMatch(tokens, CommonHelper::TokenizeString(storeValue.key, SEPARATOR[0]))) + { + rowRefs.emplace_back(storeValue); + } + } + + return std::make_unique<AcyclicResult>(acyclicStore, rowRefs); +} + +std::unique_ptr<AcyclicResultInterface> BasicDataStoreImplementation::GetAcyclic([[maybe_unused]] const std::optional<Timestamp> time, [[maybe_unused]] const std::optional<EntityId> entityId, const Key &key) const +{ + if (key == WILDCARD) + { + AcyclicRowRefs rowRefs; + + for (const auto& storeValue : acyclicStore) + { + rowRefs.emplace_back(storeValue); + } + + return std::make_unique<AcyclicResult>(acyclicStore, rowRefs); + } + else + { + return GetAcyclic(key); + } +} + +Values BasicDataStoreImplementation::GetStatic(const Key &key) const +{ + try + { + // currently, the result is always a vector containing only one element + return {std::get<Value>(staticStore.at(key))}; + } + catch (const std::out_of_range&) + { + return {}; + } +} + +Keys BasicDataStoreImplementation::GetKeys(const Key &key) const +{ + const Tokens tokens = CommonHelper::TokenizeString(key, SEPARATOR[0]); + + if (tokens.at(0) == "Cyclics") + { + if (tokens.size() == 1) + { + Keys keys; + Timestamp lastTimestamp{-1}; + + auto it = timestampIndex.cbegin(); + + while (it != timestampIndex.cend()) + { + lastTimestamp = std::get<0>(it->first); + keys.push_back(std::to_string(lastTimestamp)); + it = timestampIndex.upper_bound(lastTimestamp); + } + + return keys; + } + else if (tokens.size() >= 3) + { + std::set<Key> result; + Tokens searchKeyTokens{tokens.cbegin() + 3, tokens.cend()}; + + const auto entries = GetIndexed<Timestamp, EntityId>(std::stod(tokens.at(1)), std::stod(tokens.at(2)), searchKeyTokens); + + for (const auto& entry : *entries) + { + const auto& row = entry.get(); + const Tokens storedKeyTokens = CommonHelper::TokenizeString(row.key, SEPARATOR[0]); + + size_t tokenCount = searchKeyTokens.size(); + + if (searchKeyTokens == Tokens{storedKeyTokens.cbegin(), std::next(storedKeyTokens.cbegin(), static_cast<ssize_t>(tokenCount))}) // match given tokens against currently processed store entry + { + // retrieve the token following the last matched one + result.insert(storedKeyTokens.at(searchKeyTokens.size())); + } + } + + return {result.cbegin(), result.cend()}; + } + } + else if (tokens.at(0) == "Statics") + { + return GetStaticKeys(tokens); + } + + LOG(CbkLogLevel::Warning, "Using unsupported key format for GetKeys() on datastore: '" + key + "'"); + return {}; +} + +Keys BasicDataStoreImplementation::GetStaticKeys(const Tokens &tokens) const +{ + const Tokens searchKeyTokens{tokens.cbegin() + 1, tokens.cend()}; + std::set<Key> result; // keys in result shall be unique + + for (const auto& [storedKey, storedValue] : staticStore) + { + const auto storedKeyTokens = CommonHelper::TokenizeString(storedKey, SEPARATOR[0]); + size_t tokenCount = searchKeyTokens.size(); + + if (tokenCount == 0) // all keys at top level are requested + { + result.insert(storedKeyTokens.front()); + } + else if (tokenCount >= storedKeyTokens.size()) + { + // key can't match (search key has more elements than currently processed store entry) + } + else if (searchKeyTokens == Tokens{storedKeyTokens.cbegin(), std::next(storedKeyTokens.cbegin(), static_cast<ssize_t>(tokenCount))}) // match given tokens agains currently processed store entry + { + // retrieve the token following the last matched one + result.insert(storedKeyTokens.at(searchKeyTokens.size())); + } + } + + return {result.cbegin(), result.cend()}; +} diff --git a/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStoreImplementation.h b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStoreImplementation.h new file mode 100644 index 0000000000000000000000000000000000000000..2c0b58eb15358d1e62b8e0454c659f8df859066e --- /dev/null +++ b/OpenPass_Source_Code/openPASS/CoreModules/BasicDataStore/basicDataStoreImplementation.h @@ -0,0 +1,123 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +/*! +* \file basicDataStoreImplementation.h +* +* \brief Stores data sent by publishers and provides acces to this data for observers +*/ + +#pragma once + +#include <map> +#include <string> +#include <unordered_map> +#include <vector> + +#include "Common/commonTools.h" +#include "Common/runtimeInformation.h" +#include "Interfaces/dataStoreInterface.h" + +using namespace openpass::datastore; + +using Persistence = bool; +using StaticStore = std::unordered_map<Key, std::tuple<Value, Persistence>>; +using CyclicStore = std::vector<CyclicRow>; +using AcyclicStore = std::vector<AcyclicRow>; + +template <typename... Ts> +using StoreIndex = std::multimap<std::tuple<Ts...>, size_t>; + +using Tokens = std::vector<std::string>; + +class CyclicResult : public CyclicResultInterface +{ +public: + CyclicResult(const CyclicStore& store, const CyclicRowRefs& elements); + virtual ~CyclicResult() override = default; + + size_t size() const override; + const CyclicRow& at(const size_t index) const override; + CyclicRowRefs::const_iterator begin() const override; + CyclicRowRefs::const_iterator end() const override; + +private: + const CyclicStore& store; //!< Reference to the cyclic datastore associated with the result set + const CyclicRowRefs elements; //!< The result set (referencing elements in a datastore) +}; + +class AcyclicResult : public AcyclicResultInterface +{ +public: + AcyclicResult(const AcyclicStore& store, const AcyclicRowRefs& elements); + virtual ~AcyclicResult() override = default; + + size_t size() const override; + const AcyclicRow& at(const size_t index) const override; + AcyclicRowRefs::const_iterator begin() const override; + AcyclicRowRefs::const_iterator end() const override; + +private: + const AcyclicStore& store; //!< Reference to the acyclic datastore associated with the result set + const AcyclicRowRefs elements; //!< The result set (referencing elements in a datastore) +}; + +/*! + * \brief This class implements a basic version of a data store + * + * Data is stored in a simple mapping usign the timestamp and agent id as keys, + * values are stored as key/value pairs. + */ +class BasicDataStoreImplementation : public DataStoreInterface +{ +public: + const std::string COMPONENTNAME = "BasicDataStore"; + + BasicDataStoreImplementation(const openpass::common::RuntimeInformation *runtimeInformation, const CallbackInterface *callbacks); + BasicDataStoreImplementation(const BasicDataStoreImplementation &) = delete; + BasicDataStoreImplementation(BasicDataStoreImplementation &&) = delete; + BasicDataStoreImplementation &operator=(const BasicDataStoreImplementation &) = delete; + BasicDataStoreImplementation &operator=(BasicDataStoreImplementation &&) = delete; + virtual ~BasicDataStoreImplementation() override = default; + + void PutCyclic(const openpass::type::Timestamp time, const openpass::type::EntityId entityId, const Key &key, const Value &value) override; + + void PutAcyclic(const openpass::type::Timestamp time, const openpass::type::EntityId entityId, const Key &key, const openpass::datastore::Acyclic &acyclic) override; + + void PutStatic(const Key &key, const Value &value, bool persist = false) override; + + void Clear() override; + + std::unique_ptr<CyclicResultInterface> GetCyclic(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key &key) const override; + + std::unique_ptr<AcyclicResultInterface> GetAcyclic(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key &key) const override; + + Values GetStatic(const Key &key) const override; + + Keys GetKeys(const Key &key) const override; + +protected: + StaticStore staticStore; //!< Container for DataStore static values + CyclicStore cyclicStore; //!< Container for DataStore cyclic values + AcyclicStore acyclicStore; //!< Container for DataStore acyclic values + + StoreIndex<openpass::type::Timestamp> timestampIndex; //!< Index for timestamp based cyclics access + StoreIndex<openpass::type::EntityId> entityIdIndex; //!< Index for entity id based cyclics access + StoreIndex<openpass::type::Timestamp, openpass::type::EntityId> timeAndEntityIdIndex; //!< Index for (time, entity) based cyclics access + +private: + template <typename... Ts> + std::unique_ptr<CyclicResultInterface> GetIndexed(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Tokens &tokens) const; + + std::unique_ptr<CyclicResultInterface> GetCyclic(const Key& key) const; + std::unique_ptr<AcyclicResultInterface> GetAcyclic(const Key& key) const; + CyclicRows GetStatic(const Tokens &tokens) const; + Keys GetStaticKeys(const Tokens &tokens) const; +}; diff --git a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/CollisionDetector.cpp b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/CollisionDetector.cpp index 4693a93df110fa7b8a3ffb43120410e3c0f6eb63..047f1dba55f30d7075dccd576fb715c359437822 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/CollisionDetector.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/CollisionDetector.cpp @@ -22,7 +22,7 @@ CollisionDetector::CollisionDetector(WorldInterface *world, SimulationSlave::EventNetworkInterface *eventNetwork, const CallbackInterface *callbacks, - StochasticsInterface *stochastics): + StochasticsInterface *stochastics) : EventDetectorCommonBase( world, eventNetwork, @@ -62,14 +62,14 @@ void CollisionDetector::CalculateWorldObjectGeometry(const WorldObjectInterface resultCorners[LowerLeft].y = -agentWidthHalf; // transform corners - for(int i = 0; i < NumberCorners; ++i) + for (size_t i = 0; i < NumberCorners; ++i) { resultCorners[i].Rotate(agentAngle); resultCorners[i].Translate(position.x, position.y); } resultNormals[Right] = resultCorners[LowerRight] - resultCorners[LowerLeft]; // pointing right if angle == 0 - resultNormals[Up] = resultCorners[UpperLeft] - resultCorners[LowerLeft]; // pointing up if angle == 0 + resultNormals[Up] = resultCorners[UpperLeft] - resultCorners[LowerLeft]; // pointing up if angle == 0 } void CollisionDetector::GetWorldObjectGeometry(const WorldObjectInterface *worldObject, @@ -87,14 +87,14 @@ void CollisionDetector::GetMinMax4(std::array<double, 4> &input, maxValue = input[0]; minValue = input[0]; - for(size_t index = 1; index < 4; ++index) + for (size_t index = 1; index < 4; ++index) { - if(input[index] > maxValue) + if (input[index] > maxValue) { maxValue = input[index]; } - if(input[index] < minValue) + if (input[index] < minValue) { minValue = input[index]; } @@ -109,14 +109,14 @@ void CollisionDetector::GetMinMax2(std::array<double, 2> &input, minValue = std::min(input[0], input[1]); } -bool CollisionDetector::CalculateDistOnBorder(const WorldObjectInterface* worldObject, +bool CollisionDetector::CalculateDistOnBorder(const WorldObjectInterface *worldObject, int corner, double cornerDistance, double &result) { double distance = 0; - if(UpperLeft < corner) + if (UpperLeft < corner) { distance += worldObject->GetLength(); } @@ -127,7 +127,7 @@ bool CollisionDetector::CalculateDistOnBorder(const WorldObjectInterface* worldO return true; } - if(UpperRight < corner) + if (UpperRight < corner) { distance += worldObject->GetWidth(); } @@ -138,7 +138,7 @@ bool CollisionDetector::CalculateDistOnBorder(const WorldObjectInterface* worldO return true; } - if(LowerRight < corner) + if (LowerRight < corner) { distance += worldObject->GetLength(); } @@ -158,7 +158,7 @@ bool CollisionDetector::CalculateDistOnBorder(const WorldObjectInterface* worldO // intersectionPoints tuple elements: intersection occurred on edge, scaled distance from previous corner, edge direction, distance from initial position to intersection bool CollisionDetector::CalculateIntersectionPoints(const WorldObjectInterface *agent, - const WorldObjectInterface* other, + const WorldObjectInterface *other, bool &intersected, Common::Vector2d &intersectionPoint, double &otherDistanceFromCorner, @@ -166,7 +166,7 @@ bool CollisionDetector::CalculateIntersectionPoints(const WorldObjectInterface * double &agentDistanceFromInitial, Common::Vector2d &agentReferencePoint, Common::Vector2d &otherReferencePoint, - int &agentPenetratingCorner) + size_t &agentPenetratingCorner) { // reduce problem of two moving agents into problem of one moving agent: // add translation of other agent relative to translation of first agent @@ -186,18 +186,19 @@ bool CollisionDetector::CalculateIntersectionPoints(const WorldObjectInterface * Common::Vector2d agentVelocity = agentVelocityLongitudinal + agentVelocityLateral; Common::Vector2d agentRelativeVelocity = agentVelocity; - if(0 == otherVelocity.x && 0 == otherVelocity.y && 0 == agentRelativeVelocity.x && 0 == agentRelativeVelocity.y) + if (0 == otherVelocity.x && 0 == otherVelocity.y && 0 == agentRelativeVelocity.x && 0 == agentRelativeVelocity.y) { - LOG(CbkLogLevel::Warning, + "calculation of point of contact not possible since velocities of both agents are 0" - " (this could happen for example if agents are spawned with overlaps)"); + LOG(CbkLogLevel::Warning, +"calculation of point of contact not possible since velocities of both agents are 0" + " (this could happen for example if agents are spawned with overlaps)"); return false; } agentRelativeVelocity.Sub(otherVelocity); - if(agentRelativeVelocity.Length() == 0){ - LOG(CbkLogLevel::Warning, + "calculation of point of contact not possible since velocities of both agents are the same" - " (this could happen for example if agents are spawned with overlaps)"); + if (agentRelativeVelocity.Length() == 0) + { + LOG(CbkLogLevel::Warning, +"calculation of point of contact not possible since velocities of both agents are the same" + " (this could happen for example if agents are spawned with overlaps)"); return false; } @@ -253,21 +254,23 @@ bool CollisionDetector::CalculateIntersectionPoints(const WorldObjectInterface * intersected = false; agentDistanceFromInitial = std::numeric_limits<double>::max(); - for(int corner = 0; corner < NumberCorners; ++corner) // for each corner in agentInitialCorners[] + for (size_t corner = 0; corner < NumberCorners; ++corner) // for each corner in agentInitialCorners[] { // intersection point with upper edge otherEdgeDirection = otherInitialCorners[UpperRight] - otherInitialCorners[UpperLeft]; det = otherEdgeDirection.x * agentDirection.y - otherEdgeDirection.y * agentDirection.x; - if(0 != det) + if (0 != det) { double s = ((otherInitialCorners[UpperLeft].y - agentInitialCorners[corner].y) * otherEdgeDirection.x - - (otherInitialCorners[UpperLeft].x - agentInitialCorners[corner].x) * otherEdgeDirection.y) / det; + (otherInitialCorners[UpperLeft].x - agentInitialCorners[corner].x) * otherEdgeDirection.y) / + det; double t = ((otherInitialCorners[UpperLeft].y - agentInitialCorners[corner].y) * agentDirection.x - - (otherInitialCorners[UpperLeft].x - agentInitialCorners[corner].x) * agentDirection.y) / det; - if(0.0 <= s && 1.0 >= s && 0.0 <= t && 1.0 >= t) // within bounds of edge + (otherInitialCorners[UpperLeft].x - agentInitialCorners[corner].x) * agentDirection.y) / + det; + if (0.0 <= s && 1.0 >= s && 0.0 <= t && 1.0 >= t) // within bounds of edge { double tmpDistance = (agentDirection * s).Length(); - if(agentDistanceFromInitial > tmpDistance) + if (agentDistanceFromInitial > tmpDistance) { intersected = true; agentDistanceFromInitial = tmpDistance; @@ -292,16 +295,18 @@ bool CollisionDetector::CalculateIntersectionPoints(const WorldObjectInterface * // intersection point with right edge otherEdgeDirection = otherInitialCorners[LowerRight] - otherInitialCorners[UpperRight]; det = otherEdgeDirection.x * agentDirection.y - otherEdgeDirection.y * agentDirection.x; - if(0 != det) + if (0 != det) { double s = ((otherInitialCorners[UpperRight].y - agentInitialCorners[corner].y) * otherEdgeDirection.x - - (otherInitialCorners[UpperRight].x - agentInitialCorners[corner].x) * otherEdgeDirection.y) / det; + (otherInitialCorners[UpperRight].x - agentInitialCorners[corner].x) * otherEdgeDirection.y) / + det; double t = ((otherInitialCorners[UpperRight].y - agentInitialCorners[corner].y) * agentDirection.x - - (otherInitialCorners[UpperRight].x - agentInitialCorners[corner].x) * agentDirection.y) / det; - if(0.0 <= s && 1.0 >= s && 0.0 <= t && 1.0 >= t) // within bounds of edge + (otherInitialCorners[UpperRight].x - agentInitialCorners[corner].x) * agentDirection.y) / + det; + if (0.0 <= s && 1.0 >= s && 0.0 <= t && 1.0 >= t) // within bounds of edge { double tmpDistance = (agentDirection * s).Length(); - if(agentDistanceFromInitial > tmpDistance) + if (agentDistanceFromInitial > tmpDistance) { intersected = true; agentDistanceFromInitial = tmpDistance; @@ -326,16 +331,18 @@ bool CollisionDetector::CalculateIntersectionPoints(const WorldObjectInterface * // intersection point with lower edge otherEdgeDirection = otherInitialCorners[LowerLeft] - otherInitialCorners[LowerRight]; det = otherEdgeDirection.x * agentDirection.y - otherEdgeDirection.y * agentDirection.x; - if(0 != det) + if (0 != det) { double s = ((otherInitialCorners[LowerRight].y - agentInitialCorners[corner].y) * otherEdgeDirection.x - - (otherInitialCorners[LowerRight].x - agentInitialCorners[corner].x) * otherEdgeDirection.y) / det; + (otherInitialCorners[LowerRight].x - agentInitialCorners[corner].x) * otherEdgeDirection.y) / + det; double t = ((otherInitialCorners[LowerRight].y - agentInitialCorners[corner].y) * agentDirection.x - - (otherInitialCorners[LowerRight].x - agentInitialCorners[corner].x) * agentDirection.y) / det; - if(0.0 <= s && 1.0 >= s && 0.0 <= t && 1.0 >= t) // within bounds of edge + (otherInitialCorners[LowerRight].x - agentInitialCorners[corner].x) * agentDirection.y) / + det; + if (0.0 <= s && 1.0 >= s && 0.0 <= t && 1.0 >= t) // within bounds of edge { double tmpDistance = (agentDirection * s).Length(); - if(agentDistanceFromInitial > tmpDistance) + if (agentDistanceFromInitial > tmpDistance) { intersected = true; agentDistanceFromInitial = tmpDistance; @@ -360,16 +367,18 @@ bool CollisionDetector::CalculateIntersectionPoints(const WorldObjectInterface * // intersection point with left edge otherEdgeDirection = otherInitialCorners[UpperLeft] - otherInitialCorners[LowerLeft]; det = otherEdgeDirection.x * agentDirection.y - otherEdgeDirection.y * agentDirection.x; - if(0 != det) + if (0 != det) { double s = ((otherInitialCorners[LowerLeft].y - agentInitialCorners[corner].y) * otherEdgeDirection.x - - (otherInitialCorners[LowerLeft].x - agentInitialCorners[corner].x) * otherEdgeDirection.y) / det; + (otherInitialCorners[LowerLeft].x - agentInitialCorners[corner].x) * otherEdgeDirection.y) / + det; double t = ((otherInitialCorners[LowerLeft].y - agentInitialCorners[corner].y) * agentDirection.x - - (otherInitialCorners[LowerLeft].x - agentInitialCorners[corner].x) * agentDirection.y) / det; - if(0.0 <= s && 1.0 >= s && 0.0 <= t && 1.0 >= t) // within bounds of edge + (otherInitialCorners[LowerLeft].x - agentInitialCorners[corner].x) * agentDirection.y) / + det; + if (0.0 <= s && 1.0 >= s && 0.0 <= t && 1.0 >= t) // within bounds of edge { double tmpDistance = (agentDirection * s).Length(); - if(agentDistanceFromInitial > tmpDistance) + if (agentDistanceFromInitial > tmpDistance) { intersected = true; agentDistanceFromInitial = tmpDistance; @@ -396,31 +405,31 @@ bool CollisionDetector::CalculateIntersectionPoints(const WorldObjectInterface * } bool CollisionDetector::CalculatePointOfContact(AgentInterface *agent, - const WorldObjectInterface* other, + const WorldObjectInterface *other, double &resultAgentDistOnBorder, double &resultOtherDistOnBorder, Common::Vector2d &resultAgentReferencePoint, Common::Vector2d &resultOtherReferencePoint) { - bool agentIntersected; // is agent intersected at all - Common::Vector2d agentIntersectionPoint; // coordinates of intersection point - double agentDistanceFromCorner; // distance from previous corner of intersected edge - int agentFromCorner; // starting corner for measuring distance on edge - double otherDistanceFromInitial; // distance of other moving agent from it's non-colliding start position - int otherPenetratingCorner; // corner of other agent which penetrated first - Common::Vector2d movingOtherReferencePoint; // ReferencePoint of agent at point of collision + bool agentIntersected; // is agent intersected at all + Common::Vector2d agentIntersectionPoint; // coordinates of intersection point + double agentDistanceFromCorner; // distance from previous corner of intersected edge + int agentFromCorner; // starting corner for measuring distance on edge + double otherDistanceFromInitial; // distance of other moving agent from it's non-colliding start position + size_t otherPenetratingCorner; // corner of other agent which penetrated first + Common::Vector2d movingOtherReferencePoint; // ReferencePoint of agent at point of collision Common::Vector2d penetratedAgentReferencePoint; // ReferencePoint of other at point of collision - if(!CalculateIntersectionPoints(other, - agent, - agentIntersected, - agentIntersectionPoint, - agentDistanceFromCorner, - agentFromCorner, - otherDistanceFromInitial, - movingOtherReferencePoint, - penetratedAgentReferencePoint, - otherPenetratingCorner)) + if (!CalculateIntersectionPoints(other, + agent, + agentIntersected, + agentIntersectionPoint, + agentDistanceFromCorner, + agentFromCorner, + otherDistanceFromInitial, + movingOtherReferencePoint, + penetratedAgentReferencePoint, + otherPenetratingCorner)) { return false; } @@ -430,36 +439,37 @@ bool CollisionDetector::CalculatePointOfContact(AgentInterface *agent, double otherDistanceFromCorner; int otherFromCorner; double agentDistanceFromInitial; - int agentPenetratingCorner; + size_t agentPenetratingCorner; Common::Vector2d movingAgentReferencePoint; Common::Vector2d penetratedOtherReferencePoint; - if(!CalculateIntersectionPoints(agent, - other, - otherIntersected, - otherIntersectionPoint, - otherDistanceFromCorner, - otherFromCorner, - agentDistanceFromInitial, - movingAgentReferencePoint, - penetratedOtherReferencePoint, - agentPenetratingCorner)) + if (!CalculateIntersectionPoints(agent, + other, + otherIntersected, + otherIntersectionPoint, + otherDistanceFromCorner, + otherFromCorner, + agentDistanceFromInitial, + movingAgentReferencePoint, + penetratedOtherReferencePoint, + agentPenetratingCorner)) { return false; } - if(agentIntersected==0 && otherIntersected==0){ + if (agentIntersected == 0 && otherIntersected == 0) + { assert(agentIntersected || otherIntersected); } - if(agentIntersected && !otherIntersected) + if (agentIntersected && !otherIntersected) { - if(!CalculateDistOnBorder(agent, agentFromCorner, agentDistanceFromCorner, resultAgentDistOnBorder)) + if (!CalculateDistOnBorder(agent, agentFromCorner, agentDistanceFromCorner, resultAgentDistOnBorder)) { return false; } - if(!CalculateDistOnBorder(other, otherPenetratingCorner, 0, resultOtherDistOnBorder)) + if (!CalculateDistOnBorder(other, otherPenetratingCorner, 0, resultOtherDistOnBorder)) { return false; } @@ -467,14 +477,14 @@ bool CollisionDetector::CalculatePointOfContact(AgentInterface *agent, resultAgentReferencePoint = penetratedAgentReferencePoint; resultOtherReferencePoint = movingOtherReferencePoint; } - else if(!agentIntersected && otherIntersected) + else if (!agentIntersected && otherIntersected) { - if(!CalculateDistOnBorder(agent, agentPenetratingCorner, 0, resultAgentDistOnBorder)) + if (!CalculateDistOnBorder(agent, agentPenetratingCorner, 0, resultAgentDistOnBorder)) { return false; } - if(!CalculateDistOnBorder(other, otherFromCorner, otherDistanceFromCorner, resultOtherDistOnBorder)) + if (!CalculateDistOnBorder(other, otherFromCorner, otherDistanceFromCorner, resultOtherDistOnBorder)) { return false; } @@ -485,15 +495,15 @@ bool CollisionDetector::CalculatePointOfContact(AgentInterface *agent, else { // decide which agent entered first into body of other agent - if(agentDistanceFromInitial < otherDistanceFromInitial) + if (agentDistanceFromInitial < otherDistanceFromInitial) { // agent corner penetrated first into body of other - if(!CalculateDistOnBorder(agent, agentPenetratingCorner, 0, resultAgentDistOnBorder)) + if (!CalculateDistOnBorder(agent, agentPenetratingCorner, 0, resultAgentDistOnBorder)) { return false; } - if(!CalculateDistOnBorder(other, otherFromCorner, otherDistanceFromCorner, resultOtherDistOnBorder)) + if (!CalculateDistOnBorder(other, otherFromCorner, otherDistanceFromCorner, resultOtherDistOnBorder)) { return false; } @@ -504,12 +514,12 @@ bool CollisionDetector::CalculatePointOfContact(AgentInterface *agent, else { // other corner penetrated first into body of agent - if(!CalculateDistOnBorder(agent, agentFromCorner, agentDistanceFromCorner, resultAgentDistOnBorder)) + if (!CalculateDistOnBorder(agent, agentFromCorner, agentDistanceFromCorner, resultAgentDistOnBorder)) { return false; } - if(!CalculateDistOnBorder(other, otherPenetratingCorner, 0, resultOtherDistOnBorder)) + if (!CalculateDistOnBorder(other, otherPenetratingCorner, 0, resultOtherDistOnBorder)) { return false; } @@ -525,7 +535,7 @@ bool CollisionDetector::CalculatePointOfContact(AgentInterface *agent, void CollisionDetector::Trigger(int time) { // accumulate collisions - for(auto it = agents->cbegin(); it != agents->cend(); ++it) + for (auto it = agents->cbegin(); it != agents->cend(); ++it) { AgentInterface *agent = it->second; assert(agent != nullptr); @@ -535,10 +545,10 @@ void CollisionDetector::Trigger(int time) std::array<Common::Vector2d, NumberNormals> agentNormals; GetWorldObjectGeometry(agent, agentCorners, agentNormals); - for(auto otherIt = std::next(it); otherIt != agents->cend(); ++otherIt) + for (auto otherIt = std::next(it); otherIt != agents->cend(); ++otherIt) { AgentInterface *other = otherIt->second; - if(!DetectCollision(other, agent, agentCorners, agentNormals)) + if (!DetectCollision(other, agent, agentCorners, agentNormals)) { continue; } @@ -550,15 +560,15 @@ void CollisionDetector::Trigger(int time) } // second loop to avoid comparing traffic objects with traffic objects - for(auto trafficObjectIt = trafficObjects->begin(); trafficObjectIt != trafficObjects->end(); ++trafficObjectIt) + for (auto trafficObjectIt = trafficObjects->begin(); trafficObjectIt != trafficObjects->end(); ++trafficObjectIt) { - const TrafficObjectInterface* otherObject = *trafficObjectIt; - if(!otherObject) + const TrafficObjectInterface *otherObject = *trafficObjectIt; + if (!otherObject) { LOG(CbkLogLevel::Warning, "collision detection aborted"); throw std::runtime_error("Invalid other worldObject. Collision detection cancled."); } - if(!DetectCollision(otherObject, agent, agentCorners, agentNormals)) + if (!DetectCollision(otherObject, agent, agentCorners, agentNormals)) { continue; } @@ -571,19 +581,21 @@ void CollisionDetector::Trigger(int time) } template <typename T> -bool IsInVector(const std::vector<T>& v, T element) +bool IsInVector(const std::vector<T> &v, T element) { return std::find(v.begin(), v.end(), element) != v.end(); } bool CollisionDetector::DetectCollision(const WorldObjectInterface *other, - AgentInterface *agent, - std::array<Common::Vector2d, - NumberCorners> agentCorners, - std::array<Common::Vector2d, - NumberNormals> agentNormals) + AgentInterface *agent, + std::array<Common::Vector2d, + NumberCorners> + agentCorners, + std::array<Common::Vector2d, + NumberNormals> + agentNormals) { - if( IsInVector(agent->GetCollisionPartners(), std::make_pair(other->GetType(), other->GetId())) ) + if (IsInVector(agent->GetCollisionPartners(), std::make_pair(other->GetType(), other->GetId()))) { return false; } @@ -595,8 +607,8 @@ bool CollisionDetector::DetectCollision(const WorldObjectInterface *other, // quick check double quickDistance = agent->GetLength() + agent->GetWidth() + other->GetLength() + other->GetWidth(); - if(fabs(agentCorners[UpperLeft].x - otherCorners[UpperLeft].x) > quickDistance || - fabs(agentCorners[UpperLeft].y - otherCorners[UpperLeft].y) > quickDistance) + if (fabs(agentCorners[UpperLeft].x - otherCorners[UpperLeft].x) > quickDistance || + fabs(agentCorners[UpperLeft].y - otherCorners[UpperLeft].y) > quickDistance) { return false; } @@ -611,11 +623,11 @@ bool CollisionDetector::DetectIntersectionOfTwoWorldObjects(const WorldObjectInt std::array<Common::Vector2d, NumberNormals> otherNormals, std::array<Common::Vector2d, NumberCorners> otherCorners) { - double agentNormal1_agentCornerProjectedMinValue; - double agentNormal1_agentCornerProjectedMaxValue; + double agentNormal1_agentCornerProjectedMinValue{}; + double agentNormal1_agentCornerProjectedMaxValue{}; - double agentNormal0_agentCornerProjectedMinValue; - double agentNormal0_agentCornerProjectedMaxValue; + double agentNormal0_agentCornerProjectedMinValue{}; + double agentNormal0_agentCornerProjectedMaxValue{}; // only two points need to be projected on own normals since they are aligned std::array<double, NumberProjectedOwnAxis> agentNormal0_agentCornerProjected; @@ -625,7 +637,7 @@ bool CollisionDetector::DetectIntersectionOfTwoWorldObjects(const WorldObjectInt bool calculatedNormal1 = false; // project agent corners on agent normal0 (take origin as reference, unnormalized since only comparision result is significant) - if(!calculatedNormal0) + if (!calculatedNormal0) { agentNormal0_agentCornerProjected[ProjectedFirst] = agentCorners[LowerLeft].Dot(agentNormals[Right]); agentNormal0_agentCornerProjected[ProjectedSecond] = agentCorners[LowerRight].Dot(agentNormals[Right]); // right normal @@ -637,7 +649,7 @@ bool CollisionDetector::DetectIntersectionOfTwoWorldObjects(const WorldObjectInt // project other corners on agent normal0 (take origin as reference, unnormalized since only comparision result is significant) std::array<double, NumberProjectedOpponentAxis> agentNormal0_otherCornerProjected; - for(int i = 0; i < NumberProjectedOpponentAxis; ++i) + for (size_t i = 0; i < NumberProjectedOpponentAxis; ++i) { agentNormal0_otherCornerProjected[i] = otherCorners[i].Dot(agentNormals[Right]); } @@ -649,15 +661,15 @@ bool CollisionDetector::DetectIntersectionOfTwoWorldObjects(const WorldObjectInt agentNormal0_otherCornerProjectedMinValue); // check for collision on agent normal 0 - if(agentNormal0_agentCornerProjectedMaxValue < agentNormal0_otherCornerProjectedMinValue || - agentNormal0_otherCornerProjectedMaxValue < agentNormal0_agentCornerProjectedMinValue) + if (agentNormal0_agentCornerProjectedMaxValue < agentNormal0_otherCornerProjectedMinValue || + agentNormal0_otherCornerProjectedMaxValue < agentNormal0_agentCornerProjectedMinValue) { // agents separated on agent normal 0 axis return false; } // project agent corners on agent normal1 (take origin as reference, unnormalized since only comparision result is significant) - if(!calculatedNormal1) + if (!calculatedNormal1) { agentNormal1_agentCornerProjected[ProjectedFirst] = agentCorners[LowerLeft].Dot(agentNormals[Up]); agentNormal1_agentCornerProjected[ProjectedSecond] = agentCorners[UpperLeft].Dot(agentNormals[Up]); // up normal @@ -669,7 +681,7 @@ bool CollisionDetector::DetectIntersectionOfTwoWorldObjects(const WorldObjectInt // project other corners on agent normal1 (take origin as reference, unnormalized since only comparision result is significant) std::array<double, NumberProjectedOpponentAxis> agentNormal1_otherCornerProjected; - for(int i = 0; i < NumberProjectedOpponentAxis; ++i) + for (size_t i = 0; i < NumberProjectedOpponentAxis; ++i) { agentNormal1_otherCornerProjected[i] = otherCorners[i].Dot(agentNormals[Up]); } @@ -681,107 +693,92 @@ bool CollisionDetector::DetectIntersectionOfTwoWorldObjects(const WorldObjectInt agentNormal1_otherCornerProjectedMinValue); // check for collision on agent normal 1 - if(agentNormal1_agentCornerProjectedMaxValue < agentNormal1_otherCornerProjectedMinValue || - agentNormal1_otherCornerProjectedMaxValue < agentNormal1_agentCornerProjectedMinValue) + if (agentNormal1_agentCornerProjectedMaxValue < agentNormal1_otherCornerProjectedMinValue || + agentNormal1_otherCornerProjectedMaxValue < agentNormal1_agentCornerProjectedMinValue) { // agents separated on agent normal 1 axis return false; } // skip check for other normals if agents are approximately aligned to same axes - if(fabs(fmod(fabs(agent->GetYaw()), 90.0) - fmod(fabs(other->GetYaw()), 90.0)) > ROTATION_EPS) + if (fabs(fmod(fabs(agent->GetYaw()), 90.0) - fmod(fabs(other->GetYaw()), 90.0)) <= ROTATION_EPS) { - // project agent corners on other normal0 (take origin as reference, unnormalized since only comparision result is significant) - std::array<double, NumberProjectedOpponentAxis> otherNormal0_agentCornerProjected; - for(int i = 0; i < NumberProjectedOpponentAxis; ++i) - { - otherNormal0_agentCornerProjected[i] = agentCorners[i].Dot(otherNormals[Right]); - } - - double otherNormal0_agentCornerProjectedMaxValue; - double otherNormal0_agentCornerProjectedMinValue; - GetMinMax4(otherNormal0_agentCornerProjected, - otherNormal0_agentCornerProjectedMaxValue, - otherNormal0_agentCornerProjectedMinValue); - - // project other corners on other normal0 (take origin as reference, unnormalized since only comparision result is significant) - std::array<double, NumberProjectedOwnAxis> otherNormal0_otherCornerProjected; // only two points need to be projected on own normals since they are aligned - otherNormal0_otherCornerProjected[ProjectedFirst] = otherCorners[LowerLeft].Dot(otherNormals[Right]); // right normal - otherNormal0_otherCornerProjected[ProjectedSecond] = otherCorners[LowerRight].Dot(otherNormals[Right]); - - double otherNormal0_otherCornerProjectedMaxValue; - double otherNormal0_otherCornerProjectedMinValue; - GetMinMax2(otherNormal0_otherCornerProjected, - otherNormal0_otherCornerProjectedMaxValue, - otherNormal0_otherCornerProjectedMinValue); - - // check for collision on other normal 0 - if(otherNormal0_agentCornerProjectedMaxValue < otherNormal0_otherCornerProjectedMinValue || - otherNormal0_otherCornerProjectedMaxValue < otherNormal0_agentCornerProjectedMinValue) - { - // agents separated on other normal 0 axis - return false; - } + return true; + } - // project agent corners on other normal1 (take origin as reference, unnormalized since only comparision result is significant) - std::array<double, NumberProjectedOpponentAxis> otherNormal1_agentCornerProjected; - for(int i = 0; i < NumberProjectedOpponentAxis; ++i) - { - otherNormal1_agentCornerProjected[i] = agentCorners[i].Dot(otherNormals[Up]); - } + // project agent corners on other normal0 (take origin as reference, unnormalized since only comparision result is significant) + std::array<double, NumberProjectedOpponentAxis> otherNormal0_agentCornerProjected; + for (size_t i = 0; i < NumberProjectedOpponentAxis; ++i) + { + otherNormal0_agentCornerProjected[i] = agentCorners[i].Dot(otherNormals[Right]); + } - double otherNormal1_agentCornerProjectedMaxValue; - double otherNormal1_agentCornerProjectedMinValue; - GetMinMax4(otherNormal1_agentCornerProjected, - otherNormal1_agentCornerProjectedMaxValue, - otherNormal1_agentCornerProjectedMinValue); - - // project other corners on other normal1 (take origin as reference, unnormalized since only comparision result is significant) - std::array<double, NumberProjectedOwnAxis> otherNormal1_otherCornerProjected; // only two points need to be projected on own normals since they are aligned - otherNormal1_otherCornerProjected[ProjectedFirst] = otherCorners[LowerLeft].Dot(otherNormals[Up]); // up normal - otherNormal1_otherCornerProjected[ProjectedSecond] = otherCorners[UpperLeft].Dot(otherNormals[Up]); - - double otherNormal1_otherCornerProjectedMaxValue; - double otherNormal1_otherCornerProjectedMinValue; - GetMinMax2(otherNormal1_otherCornerProjected, - otherNormal1_otherCornerProjectedMaxValue, - otherNormal1_otherCornerProjectedMinValue); - - // check for collision on other normal 1 - if(otherNormal1_agentCornerProjectedMaxValue < otherNormal1_otherCornerProjectedMinValue || - otherNormal1_otherCornerProjectedMaxValue < otherNormal1_agentCornerProjectedMinValue) - { - // agents separated on other normal 1 axis - return false; - } + double otherNormal0_agentCornerProjectedMaxValue; + double otherNormal0_agentCornerProjectedMinValue; + GetMinMax4(otherNormal0_agentCornerProjected, + otherNormal0_agentCornerProjectedMaxValue, + otherNormal0_agentCornerProjectedMinValue); + + // project other corners on other normal0 (take origin as reference, unnormalized since only comparision result is significant) + std::array<double, NumberProjectedOwnAxis> otherNormal0_otherCornerProjected; // only two points need to be projected on own normals since they are aligned + otherNormal0_otherCornerProjected[ProjectedFirst] = otherCorners[LowerLeft].Dot(otherNormals[Right]); // right normal + otherNormal0_otherCornerProjected[ProjectedSecond] = otherCorners[LowerRight].Dot(otherNormals[Right]); + + double otherNormal0_otherCornerProjectedMaxValue; + double otherNormal0_otherCornerProjectedMinValue; + GetMinMax2(otherNormal0_otherCornerProjected, + otherNormal0_otherCornerProjectedMaxValue, + otherNormal0_otherCornerProjectedMinValue); + + // check for collision on other normal 0 + if (otherNormal0_agentCornerProjectedMaxValue < otherNormal0_otherCornerProjectedMinValue || + otherNormal0_otherCornerProjectedMaxValue < otherNormal0_agentCornerProjectedMinValue) + { + // agents separated on other normal 0 axis + return false; + } - return true; + // project agent corners on other normal1 (take origin as reference, unnormalized since only comparision result is significant) + std::array<double, NumberProjectedOpponentAxis> otherNormal1_agentCornerProjected; + for (size_t i = 0; i < NumberProjectedOpponentAxis; ++i) + { + otherNormal1_agentCornerProjected[i] = agentCorners[i].Dot(otherNormals[Up]); } - else + + double otherNormal1_agentCornerProjectedMaxValue; + double otherNormal1_agentCornerProjectedMinValue; + GetMinMax4(otherNormal1_agentCornerProjected, + otherNormal1_agentCornerProjectedMaxValue, + otherNormal1_agentCornerProjectedMinValue); + + // project other corners on other normal1 (take origin as reference, unnormalized since only comparision result is significant) + std::array<double, NumberProjectedOwnAxis> otherNormal1_otherCornerProjected; // only two points need to be projected on own normals since they are aligned + otherNormal1_otherCornerProjected[ProjectedFirst] = otherCorners[LowerLeft].Dot(otherNormals[Up]); // up normal + otherNormal1_otherCornerProjected[ProjectedSecond] = otherCorners[UpperLeft].Dot(otherNormals[Up]); + + double otherNormal1_otherCornerProjectedMaxValue; + double otherNormal1_otherCornerProjectedMinValue; + GetMinMax2(otherNormal1_otherCornerProjected, + otherNormal1_otherCornerProjectedMaxValue, + otherNormal1_otherCornerProjectedMinValue); + + // check for collision on other normal 1 + if (otherNormal1_agentCornerProjectedMaxValue < otherNormal1_otherCornerProjectedMinValue || + otherNormal1_otherCornerProjectedMaxValue < otherNormal1_agentCornerProjectedMinValue) { - return true; + // agents separated on other normal 1 axis + return false; } + + return true; } void CollisionDetector::DetectedCollisionWithObject(int time, AgentInterface *agent, const WorldObjectInterface *other) { - auto event = std::make_shared<CollisionEvent>(time, - COMPONENTNAME, - false, - agent->GetId(), - other->GetId()); - - eventNetwork->InsertEvent(event); + eventNetwork->InsertEvent(std::make_shared<CollisionEvent>(time, COMPONENTNAME, false, agent->GetId(), other->GetId())); } void CollisionDetector::DetectedCollisionWithAgent(int time, AgentInterface *agent, AgentInterface *other) { - auto event = std::make_shared<CollisionEvent>(time, - COMPONENTNAME, - true, - agent->GetId(), - other->GetId()); - - eventNetwork->InsertEvent(event); + eventNetwork->InsertEvent(std::make_shared<CollisionEvent>(time, COMPONENTNAME, true, agent->GetId(), other->GetId())); } - diff --git a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/CollisionDetector.h b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/CollisionDetector.h index ab999fa62e44e2b662e65c4ced1621ccc997d79c..f13fb5bb4d0aadcd87f10046e1db6ac69b0d54e7 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/CollisionDetector.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/CollisionDetector.h @@ -202,7 +202,7 @@ public: double &agentDistanceFromInitial, Common::Vector2d &agentReferencePoint, Common::Vector2d &otherReferencePoint, - int &agentPenetratingCorner); + size_t &agentPenetratingCorner); //----------------------------------------------------------------------------- /*! Calculates parameters of point of contact diff --git a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/ConditionalEventDetector.cpp b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/ConditionalEventDetector.cpp index 923434b13fa7a3655858f6dd7c619a6f3a142961..7b2e95f51a3a28d044331ccdc5fb971685083c85 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/ConditionalEventDetector.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/ConditionalEventDetector.cpp @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2019 in-tech GmbH +* Copyright (c) 2019, 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -11,16 +11,17 @@ #include "ConditionalEventDetector.h" ConditionalEventDetector::ConditionalEventDetector(WorldInterface *world, - const openScenario::ConditionalEventDetectorInformation& eventDetectorInformation, + const openScenario::ConditionalEventDetectorInformation &eventDetectorInformation, SimulationSlave::EventNetworkInterface *eventNetwork, const CallbackInterface *callbacks, StochasticsInterface *stochastics) : - EventDetectorCommonBase(world, - eventNetwork, - callbacks, - stochastics), - eventDetectorInformation(eventDetectorInformation) -{} + EventDetectorCommonBase(world, + eventNetwork, + callbacks, + stochastics), + eventDetectorInformation(eventDetectorInformation) +{ +} void ConditionalEventDetector::Reset() { @@ -31,12 +32,7 @@ void ConditionalEventDetector::Trigger(int time) { if (IsBelowMaximumNumberOfExecutions()) { - // this collection contains all of the agents who are defined as "TriggeringEntities" and who meet their conditions - std::vector<const AgentInterface *> triggeringAgents {}; - bool allConditionsMet = EvaluateConditionsAtTime(time, - triggeringAgents); - - if (allConditionsMet) + if (const auto [allConditionsMet, triggeringAgents] = EvaluateConditions(time); allConditionsMet == true) { TriggerEventInsertion(time, triggeringAgents); } @@ -45,27 +41,20 @@ void ConditionalEventDetector::Trigger(int time) void ConditionalEventDetector::TriggerEventInsertion(int time, const std::vector<const AgentInterface *> triggeringAgents) { - const auto actors = GetActors(triggeringAgents); - std::vector<int> triggeringAgentIds{}; - for(const auto triggeringAgent : triggeringAgents) + for (const auto triggeringAgent : triggeringAgents) { triggeringAgentIds.push_back(triggeringAgent->GetId()); } + const auto actors = GetActors(triggeringAgents); std::vector<int> actingAgentIds{}; - for(const auto actingAgent : actors) + for (const auto actingAgent : actors) { actingAgentIds.push_back(actingAgent->GetId()); } - auto event = std::make_shared<ConditionalEvent>(time, - eventDetectorInformation.eventName, - COMPONENTNAME, - triggeringAgentIds, - actingAgentIds); - - eventNetwork->InsertEvent(event); + eventNetwork->InsertEvent(std::make_shared<ConditionalEvent>(time, eventDetectorInformation.eventName, COMPONENTNAME, triggeringAgentIds, actingAgentIds)); executionCounter++; } @@ -78,17 +67,17 @@ bool ConditionalEventDetector::IsBelowMaximumNumberOfExecutions() std::vector<const AgentInterface *> ConditionalEventDetector::GetActors(const std::vector<const AgentInterface *> triggeringAgents) { std::vector<const AgentInterface *> actors{}; - if (eventDetectorInformation.actorInformation.triggeringAgentsAsActors.value_or(false)) + if (eventDetectorInformation.actorInformation.actorIsTriggeringEntity) { actors = triggeringAgents; } - if(eventDetectorInformation.actorInformation.actors.has_value()) + if (eventDetectorInformation.actorInformation.actors) { - for (const auto &agentName : eventDetectorInformation.actorInformation.actors.value()) + for (const auto &agentName : *eventDetectorInformation.actorInformation.actors) { AgentInterface *agent = world->GetAgentByName(agentName); - if(agent != nullptr && std::find(actors.begin(), actors.end(), agent) == actors.end()) + if (agent && std::find(actors.begin(), actors.end(), agent) == actors.end()) { actors.push_back(agent); } @@ -98,9 +87,10 @@ std::vector<const AgentInterface *> ConditionalEventDetector::GetActors(const st return actors; } -bool ConditionalEventDetector::EvaluateConditionsAtTime(const int time, - std::vector<const AgentInterface*>& triggeringAgents) +std::pair<bool, std::vector<const AgentInterface *>> ConditionalEventDetector::EvaluateConditions(const int time) { + std::vector<const AgentInterface *> triggeringAgents; + // this flag is used to ensure the first set of triggeringAgents found is correctly // added to the triggeringAgents array (an intersection with an empty set is always empty) bool isFirstByEntityConditionEvaluated = false; @@ -110,24 +100,23 @@ bool ConditionalEventDetector::EvaluateConditionsAtTime(const int time, // Evaluate if each condition is met. For some conditions, an array of Agents // is returned containing those entities described in the openScenario file // as "TriggeringEntities" that meet the prescribed condition. - for (const auto& condition : eventDetectorInformation.conditions) + for (const auto &condition : eventDetectorInformation.conditions) { auto conditionEvaluation = evaluateCondition(condition); // if a vector of AgentInterfaces is returned, it contains those TriggeringEntities who meet the condition - std::vector<const AgentInterface*>* triggeringEntitiesWhoMeetCondition = std::get_if<std::vector<const AgentInterface*>>(&conditionEvaluation); + std::vector<const AgentInterface *> *triggeringEntitiesWhoMeetCondition = std::get_if<std::vector<const AgentInterface *>>(&conditionEvaluation); // get_if resolves to nullptr if the type specified is not found if (triggeringEntitiesWhoMeetCondition) { // if there are TriggeringEntities who meet the condition, add or intersect the set of // entities for this condition into the triggeringAgents collection - if (triggeringEntitiesWhoMeetCondition->size() > 0) + if (!triggeringEntitiesWhoMeetCondition->empty()) { std::sort(triggeringEntitiesWhoMeetCondition->begin(), triggeringEntitiesWhoMeetCondition->end(), - [](const AgentInterface* agentA, const AgentInterface* agentB) -> bool - { - return agentA->GetId() < agentB->GetId(); + [](const AgentInterface *agentA, const AgentInterface *agentB) -> bool { + return agentA->GetId() < agentB->GetId(); }); if (!isFirstByEntityConditionEvaluated) { @@ -136,7 +125,7 @@ bool ConditionalEventDetector::EvaluateConditionsAtTime(const int time, } else { - std::vector<const AgentInterface*> intersection{}; + std::vector<const AgentInterface *> intersection{}; std::set_intersection(triggeringAgents.begin(), triggeringAgents.end(), triggeringEntitiesWhoMeetCondition->begin(), triggeringEntitiesWhoMeetCondition->end(), std::back_inserter(intersection)); @@ -144,7 +133,7 @@ bool ConditionalEventDetector::EvaluateConditionsAtTime(const int time, if (intersection.empty()) { // this condition was not met; no further condition checking needs to be done - return false; + return {false, {}}; } triggeringAgents = intersection; } @@ -153,18 +142,18 @@ bool ConditionalEventDetector::EvaluateConditionsAtTime(const int time, else { // this condition was not met; no further condition checking needs to be done - return false; + return {false, {}}; } } else { - bool* conditionIsMet = std::get_if<bool>(&conditionEvaluation); + bool *conditionIsMet = std::get_if<bool>(&conditionEvaluation); if (!(conditionIsMet == nullptr)) { if (!(*conditionIsMet)) { // this condition was not met; no further condition checking needs to be done - return false; + return {false, {}}; } } else @@ -176,5 +165,5 @@ bool ConditionalEventDetector::EvaluateConditionsAtTime(const int time, } } - return true; + return {true, triggeringAgents}; } diff --git a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/ConditionalEventDetector.h b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/ConditionalEventDetector.h index 6ccc65b2dce6ae9c1fe4409d97c5cdc32ff496c2..eff361f4154edeb5ea08342964615292df854f62 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/ConditionalEventDetector.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/ConditionalEventDetector.h @@ -13,30 +13,35 @@ #include "EventDetectorCommonBase.h" // template for overload pattern used in CheckCondition() -template<class... Ts> struct overload : Ts... { using Ts::operator()...; }; -template<class... Ts> overload(Ts...) -> overload<Ts...>; +template <class... Ts> +struct overload : Ts... +{ + using Ts::operator()...; +}; +template <class... Ts> +overload(Ts...)->overload<Ts...>; struct ConditionMetaInformation { - WorldInterface * const world {}; - int currentTime {}; + WorldInterface *const world{}; + int currentTime{}; }; -using ConditionVisitorVariant = std::variant<std::vector<const AgentInterface*>, bool>; +using ConditionVisitorVariant = std::variant<std::vector<const AgentInterface *>, bool>; class ConditionalEventDetector : public EventDetectorCommonBase { public: ConditionalEventDetector(WorldInterface *world, - const openScenario::ConditionalEventDetectorInformation& eventDetectorInformation, + const openScenario::ConditionalEventDetectorInformation &eventDetectorInformation, SimulationSlave::EventNetworkInterface *eventNetwork, const CallbackInterface *callbacks, StochasticsInterface *stochastics); ConditionalEventDetector() = delete; - ConditionalEventDetector(const ConditionalEventDetector&) = delete; - ConditionalEventDetector(ConditionalEventDetector&&) = delete; - ConditionalEventDetector& operator=(const ConditionalEventDetector&) = delete; - ConditionalEventDetector& operator=(ConditionalEventDetector&&) = delete; + ConditionalEventDetector(const ConditionalEventDetector &) = delete; + ConditionalEventDetector(ConditionalEventDetector &&) = delete; + ConditionalEventDetector &operator=(const ConditionalEventDetector &) = delete; + ConditionalEventDetector &operator=(ConditionalEventDetector &&) = delete; virtual void Trigger(int time) override; @@ -56,7 +61,7 @@ private: * EventNetwork. * ------------------------------------------------------------------------ */ - void TriggerEventInsertion(int time, const std::vector<const AgentInterface*> triggeringAgents); + void TriggerEventInsertion(int time, const std::vector<const AgentInterface *> triggeringAgents); /*! * ------------------------------------------------------------------------ @@ -84,24 +89,21 @@ private: * by the Events emitted by the EventDetector * ------------------------------------------------------------------------ */ - std::vector<const AgentInterface*> GetActors(const std::vector<const AgentInterface*> triggeringAgents = {}); + std::vector<const AgentInterface *> GetActors(const std::vector<const AgentInterface *> triggeringAgents = {}); /*! * ------------------------------------------------------------------------ * \brief EvaluateConditionsAtTime evaluates all conditions for the - * specified time. TriggeringAgents who meet all conditions are - * placed into the triggeringAgents collection. + * specified time and returns triggering agents who meet all conditions. * * \param[in] time the time at which the conditions are being evaluated * - * \param[out] triggeringAgents the collection into which the - * TriggeringAgents who meet all conditions are placed - * - * \return true if all conditions are met; false otherwise + * \return <0> true if all conditions are met; false otherwise + * <1> triggeringAgents who meet all conditions * ------------------------------------------------------------------------ */ - bool EvaluateConditionsAtTime(const int time, - std::vector<const AgentInterface*>& triggeringAgents); + + std::pair<bool, std::vector<const AgentInterface *>> EvaluateConditions(const int time); /*! * ------------------------------------------------------------------------ @@ -115,18 +117,18 @@ private: * \return lambda function for evaluating a Condition variant * ------------------------------------------------------------------------ */ - auto CheckCondition(const ConditionMetaInformation& cmi) + auto CheckCondition(const ConditionMetaInformation &cmi) { return [cmi](auto&& condition) { return std::visit(overload{ - [&](const openScenario::ReachPositionRoadCondition& reachPositionCondition) { return ConditionVisitorVariant{reachPositionCondition.IsMet(cmi.world)}; }, - [&](const openScenario::RelativeLaneCondition& relativeLaneCondition) { return ConditionVisitorVariant{relativeLaneCondition.IsMet(cmi.world)}; }, - [&](const openScenario::RelativeSpeedCondition& relativeSpeedCondition) { return ConditionVisitorVariant{relativeSpeedCondition.IsMet(cmi.world)}; }, - [&](const openScenario::TimeToCollisionCondition& timeToCollisionCondition) { return ConditionVisitorVariant{timeToCollisionCondition.IsMet(cmi.world)}; }, + [&](const openScenario::ReachPositionRoadCondition &reachPositionCondition) { return ConditionVisitorVariant{reachPositionCondition.IsMet(cmi.world)}; }, + [&](const openScenario::RelativeLaneCondition &relativeLaneCondition) { return ConditionVisitorVariant{relativeLaneCondition.IsMet(cmi.world)}; }, + [&](const openScenario::RelativeSpeedCondition &relativeSpeedCondition) { return ConditionVisitorVariant{relativeSpeedCondition.IsMet(cmi.world)}; }, + [&](const openScenario::TimeToCollisionCondition &timeToCollisionCondition) { return ConditionVisitorVariant{timeToCollisionCondition.IsMet(cmi.world)}; }, [&](const openScenario::TimeHeadwayCondition& timeHeadwayCondition) { return ConditionVisitorVariant{timeHeadwayCondition.IsMet(cmi.world)}; }, - [&](const openScenario::SimulationTimeCondition& simulationTimeCondition) { return ConditionVisitorVariant{simulationTimeCondition.IsMet(cmi.currentTime)}; } - }, condition); + [&](const openScenario::SimulationTimeCondition &simulationTimeCondition) { return ConditionVisitorVariant{simulationTimeCondition.IsMet(cmi.currentTime)}; }}, + condition); }; } }; diff --git a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/EventDetectorCommonBase.h b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/EventDetectorCommonBase.h index 89d8662862ea5538d46c3f58e776a0c3c332c8d3..b7da71a3c28f43b4545d9252f575f4f969d4302c 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/EventDetectorCommonBase.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/EventDetector/EventDetectorCommonBase.h @@ -35,6 +35,7 @@ #include "Interfaces/parameterInterface.h" #include "Interfaces/worldInterface.h" #include "Interfaces/eventDetectorInterface.h" +#include "Interfaces/stochasticsInterface.h" #include "Common/conditionalEvent.h" #include "Common/collisionEvent.h" diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/CollisionManipulator.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/CollisionManipulator.cpp index 084d18536370beb4817137a0360b365daf58f60e..652222cfb45f258d55dc384bc7311b12d8c1d13e 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/CollisionManipulator.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/CollisionManipulator.cpp @@ -16,9 +16,9 @@ #include <QtGlobal> -CollisionManipulator::CollisionManipulator(WorldInterface* world, - SimulationSlave::EventNetworkInterface* eventNetwork, - const CallbackInterface* callbacks): +CollisionManipulator::CollisionManipulator(WorldInterface *world, + SimulationSlave::EventNetworkInterface *eventNetwork, + const CallbackInterface *callbacks) : ManipulatorCommonBase(world, eventNetwork, callbacks) @@ -33,20 +33,20 @@ void CollisionManipulator::Trigger(int time) for (std::shared_ptr<EventInterface> eventInterface : GetEvents()) { std::shared_ptr<CollisionEvent> event = std::dynamic_pointer_cast<CollisionEvent>(eventInterface); - AgentInterface* collisionAgent = world->GetAgent(event->collisionAgentId); + AgentInterface *collisionAgent = world->GetAgent(event->collisionAgentId); eventNetwork->AddCollision(event->collisionAgentId); if (event->collisionWithAgent) { - AgentInterface* collisionOpponent = world->GetAgent(event->collisionOpponentId); + AgentInterface *collisionOpponent = world->GetAgent(event->collisionOpponentId); try { UpdateCollision(collisionAgent, collisionOpponent); } - catch (const std::bad_alloc&) + catch (const std::bad_alloc &) { - std::cout << "BAD ALLOC"; + std::cout << "BAD ALLOC"; // TODO: log if something like this happens } eventNetwork->AddCollision(event->collisionOpponentId); } @@ -57,7 +57,7 @@ void CollisionManipulator::Trigger(int time) { if (partner.first == ObjectTypeOSI::Vehicle) { - AgentInterface* partnerAgent = world->GetAgent(partner.second); + AgentInterface *partnerAgent = world->GetAgent(partner.second); partnerAgent->UpdateCollision(pair); } } @@ -67,37 +67,32 @@ void CollisionManipulator::Trigger(int time) } } -void CollisionManipulator::UpdateCollision(AgentInterface* agent, AgentInterface* opponent) +void CollisionManipulator::UpdateCollision(AgentInterface *agent, AgentInterface *opponent) { - //Stop conditions for the recursion - if (agent == nullptr || opponent == nullptr) - { - return ; - } - - if (agent->GetId() == opponent->GetId()) + if (!agent || !opponent || agent->GetId() == opponent->GetId()) { return; } - for (const auto& partner : agent->GetCollisionPartners()) + // check if object is already in stored collision partners + for (const auto &[objectType, id] : agent->GetCollisionPartners()) { - if (partner.second == opponent->GetId() && partner.first == ObjectTypeOSI::Vehicle) + if (id == opponent->GetId() && objectType == ObjectTypeOSI::Vehicle) { return; } } //Update the collision partners - agent->UpdateCollision(std::make_pair(opponent->GetType(), opponent->GetId())); - opponent->UpdateCollision(std::make_pair(agent->GetType(), agent->GetId())); + agent->UpdateCollision({opponent->GetType(), opponent->GetId()}); + opponent->UpdateCollision({agent->GetType(), agent->GetId()}); //Recursion for agent - for (const auto& partner : agent->GetCollisionPartners()) + for (const auto &partner : agent->GetCollisionPartners()) { if (partner.first == ObjectTypeOSI::Object) { - opponent->UpdateCollision(std::make_pair(ObjectTypeOSI::Object, partner.second)); + opponent->UpdateCollision({ObjectTypeOSI::Object, partner.second}); } else { @@ -106,11 +101,11 @@ void CollisionManipulator::UpdateCollision(AgentInterface* agent, AgentInterface } //Recursion for opponent - for (const auto& partner : opponent->GetCollisionPartners()) + for (const auto &partner : opponent->GetCollisionPartners()) { if (partner.first == ObjectTypeOSI::Object) { - agent->UpdateCollision(std::make_pair(ObjectTypeOSI::Object, partner.second)); + agent->UpdateCollision({ObjectTypeOSI::Object, partner.second}); } else { @@ -119,8 +114,7 @@ void CollisionManipulator::UpdateCollision(AgentInterface* agent, AgentInterface } } - EventContainer CollisionManipulator::GetEvents() { - return eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::Collision); + return eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::OpenPASS); } diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/ComponentStateChangeManipulator.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/ComponentStateChangeManipulator.cpp index 97b3f2dc86e754983c94ab2b95bcb058dd57ce37..98cf3029a389f2364f9cc9853680802a60441bf1 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/ComponentStateChangeManipulator.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/ComponentStateChangeManipulator.cpp @@ -17,8 +17,6 @@ #include "Common/componentStateChangeEvent.h" #include "Common/commonTools.h" -#include <QtGlobal> -#include <array> ComponentStateChangeManipulator::ComponentStateChangeManipulator(WorldInterface *world, std::shared_ptr<openScenario::UserDefinedCommandAction> action, @@ -52,13 +50,11 @@ ComponentStateChangeManipulator::ComponentStateChangeManipulator(WorldInterface cycleTime = 100; } -void ComponentStateChangeManipulator::Trigger(int time) +void ComponentStateChangeManipulator::Trigger([[maybe_unused]] int time) { - Q_UNUSED(time) - - for (std::shared_ptr<EventInterface> eventInterface : GetEvents()) + for (const auto& eventInterface : GetEvents()) { - std::shared_ptr<ConditionalEvent> triggeringEvent = std::dynamic_pointer_cast<ConditionalEvent>(eventInterface); + const auto& triggeringEvent = std::dynamic_pointer_cast<ConditionalEvent>(eventInterface); std::shared_ptr<ComponentChangeEvent> event = std::make_shared<ComponentChangeEvent>(time, @@ -79,7 +75,7 @@ EventContainer ComponentStateChangeManipulator::GetEvents() { EventContainer manipulatorSpecificEvents{}; - const auto &conditionalEvents = eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::Conditional); + const auto &conditionalEvents = eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::OpenSCENARIO); for(const auto &event: conditionalEvents) { diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/LaneChangeManipulator.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/LaneChangeManipulator.cpp index 0ddfebbe54c3d9ff7cef4ed80059d7ad16e562e7..674078876c832e92c8b528c2aefa262e2f9eea5e 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/LaneChangeManipulator.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/LaneChangeManipulator.cpp @@ -53,7 +53,7 @@ EventContainer LaneChangeManipulator::GetEvents() { EventContainer manipulatorSpecificEvents{}; - const auto &conditionalEvents = eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::Conditional); + const auto &conditionalEvents = eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::OpenSCENARIO); for(const auto &event: conditionalEvents) { diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/RemoveAgentsManipulator.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/RemoveAgentsManipulator.cpp index 9ccbab01927d0380503fd71274355fdea365e99d..6e825b3bea4d7caaa4780903d991b4c89c69d9ed 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/RemoveAgentsManipulator.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/RemoveAgentsManipulator.cpp @@ -14,8 +14,6 @@ #include "RemoveAgentsManipulator.h" -#include <QtGlobal> - RemoveAgentsManipulator::RemoveAgentsManipulator(WorldInterface *world, std::shared_ptr<openScenario::GlobalEntityAction> action, SimulationSlave::EventNetworkInterface *eventNetwork, @@ -54,9 +52,7 @@ EventContainer RemoveAgentsManipulator::GetEvents() { EventContainer manipulatorSpecificEvents{}; - const auto &conditionalEvents = eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::Conditional); - - for(const auto &event: conditionalEvents) + for (const auto &event : eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::OpenSCENARIO)) { const auto conditionalEvent = std::static_pointer_cast<ConditionalEvent>(event); diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/TrajectoryManipulator.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/TrajectoryManipulator.cpp index 75e5e553b5a91077bafd263ddf3897626f79de2b..a421317d852a356e59d840ad6b336fef2b9eec06 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/TrajectoryManipulator.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Manipulator/TrajectoryManipulator.cpp @@ -53,7 +53,7 @@ EventContainer TrajectoryManipulator::GetEvents() { EventContainer manipulatorSpecificEvents{}; - const auto &conditionalEvents = eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::Conditional); + const auto &conditionalEvents = eventNetwork->GetActiveEventCategory(EventDefinitions::EventCategory::OpenSCENARIO); for(const auto &event: conditionalEvents) { diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/Observation_Log.pro b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/Observation_Log.pro index 91cb59c4dcb8b1132cc67987ae81c023fdcabee8..c3c975e3ac3ffdc31f048f5795550d0f906d6096 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/Observation_Log.pro +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/Observation_Log.pro @@ -1,5 +1,5 @@ # /********************************************************************* -# * Copyright (c) 2017, 2018, 2019 in-tech GmbH +# * Copyright (c) 2017, 2018, 2019, 2020 in-tech GmbH # * 2016, 2017 ITK Engineering GmbH # * This program and the accompanying materials are made # * available under the terms of the Eclipse Public License 2.0 @@ -18,21 +18,25 @@ DEFINES += OBSERVATION_LOG_LIBRARY CONFIG += OPENPASS_LIBRARY include(../../../global.pri) -SUBDIRS += . \ - -INCLUDEPATH += $$SUBDIRS \ - ../../CoreFrameWork/CoreShare \ - ../.. +INCLUDEPATH += \ + . \ + ../.. \ + ../Observation_Log \ + ../../CoreFrameWork/CoreShare SOURCES += \ - $$getFiles(SUBDIRS, cpp) \ - $$getFiles(SUBDIRS, cc) \ - $$getFiles(SUBDIRS, c) \ - ../../CoreFramework/CoreShare/log.cpp \ - ../../CoreFramework/CoreShare/parameters.cpp + observationFileHandler.cpp \ + observation_log.cpp \ + observation_logImplementation.cpp \ + observationCyclics.cpp \ + runStatistic.cpp \ + runStatisticCalculation.cpp HEADERS += \ - $$getFiles(SUBDIRS, hpp) \ - $$getFiles(SUBDIRS, h) \ - ../../CoreFramework/CoreShare/log.h \ - ../../CoreFramework/CoreShare/parameters.h + observationFileHandler.h \ + observationLogConstants.h \ + observation_log.h \ + observation_logImplementation.h \ + observationCyclics.h \ + runStatistic.h \ + runStatisticCalculation.h diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationCyclics.h b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationCyclics.h index 516efb571fb12ce1fccbe71300e6e52201c15f5e..bf74716874b356ca401fe9d9b316f0ef18bb45f5 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationCyclics.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationCyclics.h @@ -22,8 +22,6 @@ class ObservationCyclics { public: - const std::string COMPONENTNAME = "ObservationCyclics"; - ObservationCyclics() { } @@ -64,9 +62,9 @@ public: /*! * \brief Returns all timesteps for which samples exist */ - std::vector<int> *GetTimeSteps() + std::vector<int>& GetTimeSteps() { - return &timeSteps; + return timeSteps; } /*! diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationFileHandler.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationFileHandler.cpp index 2a6e21688e255e22946e5faa801ba37db83d0c5a..fb7bcd57148181132841878f00cf6c1ea41c4005 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationFileHandler.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationFileHandler.cpp @@ -14,29 +14,28 @@ //----------------------------------------------------------------------------- #include <sstream> + #include <QDir> +#include <QFile> #include <QString> +#include <QTemporaryFile> -#include "Interfaces/worldInterface.h" +#include "Common/openPassTypes.h" +#include "Common/openPassUtils.h" #include "Common/sensorDefinitions.h" +#include "Interfaces/dataStoreInterface.h" +#include "Interfaces/worldInterface.h" #include "observationFileHandler.h" +ObservationFileHandler::ObservationFileHandler(const DataStoreReadInterface& dataStore) : + dataStore{dataStore} +{ +} + void ObservationFileHandler::WriteStartOfFile(const std::string& frameworkVersion) { runNumber = 0; - // retrieve storage location - - tmpFilename = "simulationOutput.tmp"; - finalFilename = "simulationOutput.xml"; - - tmpPath = folder + QDir::separator() + tmpFilename; - finalPath = folder + QDir::separator() + finalFilename; - - std::stringstream ss; - ss << COMPONENTNAME << " retrieved storage location: " << finalPath.toStdString(); - // LOG(CbkLogLevel::Debug, ss.str()); - // setup environment QDir dir(folder); if (!dir.exists() && !dir.mkpath(folder)) @@ -47,11 +46,6 @@ void ObservationFileHandler::WriteStartOfFile(const std::string& frameworkVersio throw std::runtime_error(ss.str()); } - if (QFile::exists(tmpPath)) - { - QFile::remove(tmpPath); - } - if (QFile::exists(finalPath)) { QFile::remove(finalPath); @@ -59,16 +53,18 @@ void ObservationFileHandler::WriteStartOfFile(const std::string& frameworkVersio RemoveCsvCyclics(folder); - xmlFile = std::make_shared<QFile>(tmpPath); - if (!xmlFile->open(QIODevice::WriteOnly)) + xmlFile = std::make_unique<QTemporaryFile>(folder + "/simulationOutput_XXXXXX.tmp"); + xmlFile->setAutoRemove(false); + xmlFile->fileName(); // required for setAutoRemove to be applied, see https://doc.qt.io/qt-5/qtemporaryfile.html#setAutoRemove + + if (!xmlFile->open()) { std::stringstream ss; - ss << COMPONENTNAME << " could not create file: " << tmpPath.toStdString(); - // LOG(CbkLogLevel::Error, ss.str()); + ss << COMPONENTNAME << ": could not create file: " << xmlFile->fileName().toStdString(); throw std::runtime_error(ss.str()); } - xmlFileStream = std::make_shared<QXmlStreamWriter>(xmlFile.get()); + xmlFileStream = std::make_unique<QXmlStreamWriter>(xmlFile.get()); xmlFileStream->setAutoFormatting(true); xmlFileStream->writeStartDocument(); xmlFileStream->writeStartElement(outputTags.SIMULATIONOUTPUT); @@ -80,11 +76,8 @@ void ObservationFileHandler::WriteStartOfFile(const std::string& frameworkVersio xmlFileStream->writeStartElement(outputTags.RUNRESULTS); } -void ObservationFileHandler::WriteRun(const RunResultInterface& runResult, RunStatistic runStatistic, - ObservationCyclics& cyclics, WorldInterface* world, SimulationSlave::EventNetworkInterface* eventNetwork) +void ObservationFileHandler::WriteRun([[maybe_unused]] const RunResultInterface& runResult, RunStatistic runStatistic, ObservationCyclics& cyclics) { - Q_UNUSED(runResult); - std::stringstream ss; ss << COMPONENTNAME << " append log to file: " << tmpPath.toStdString(); // LOG(CbkLogLevel::Debug, ss.str()); @@ -96,19 +89,33 @@ void ObservationFileHandler::WriteRun(const RunResultInterface& runResult, RunSt // write RunStatisticsTag xmlFileStream->writeStartElement(outputTags.RUNSTATISTICS); - runStatistic.WriteStatistics(xmlFileStream); + const auto agentIds = dataStore.GetKeys("Statics/Agents"); + + for (const auto& agentId : agentIds) + { + const auto tdtResult = dataStore.GetCyclic(std::nullopt, std::stoi(agentId), "TotalDistanceTraveled"); + const auto last_tdt_row = (*((*tdtResult).end() - 1)).get(); + + if (last_tdt_row.entityId == 0) + { + runStatistic.EgoDistanceTraveled = std::get<double>(last_tdt_row.value); + } + + runStatistic.TotalDistanceTraveled += std::get<double>(last_tdt_row.value); + } + + runStatistic.WriteStatistics(xmlFileStream.get()); // close RunStatisticsTag xmlFileStream->writeEndElement(); - AddEvents(xmlFileStream, eventNetwork); - - AddAgents(xmlFileStream, world); + AddEvents(); + AddAgents(); // write CyclicsTag xmlFileStream->writeStartElement(outputTags.CYCLICS); - if(writeCyclicsToCsv) + if (writeCyclicsToCsv) { QString runPrefix = ""; if (runNumber < 10) @@ -121,15 +128,14 @@ void ObservationFileHandler::WriteRun(const RunResultInterface& runResult, RunSt } QString csvFilename = "Cyclics_Run_" + runPrefix + QString::number(runNumber) + ".csv"; - AddReference(xmlFileStream, csvFilename); + AddReference(csvFilename); WriteCsvCyclics(csvFilename, cyclics); } else { - AddHeader(xmlFileStream, cyclics); - - AddSamples(xmlFileStream, cyclics); + AddHeader(cyclics); + AddSamples(cyclics); } // close CyclicsTag @@ -154,144 +160,96 @@ void ObservationFileHandler::WriteEndOfFile() xmlFile->close(); // finalize results - // using copy/remove instead of rename, since latter is failing on some systems - if (xmlFile->copy(finalPath)) - { - xmlFile->remove(); - } + xmlFile->rename(finalPath); } -void ObservationFileHandler::AddEventParameters(std::shared_ptr<QXmlStreamWriter> fStream, - EventParameters eventParameters) +void ObservationFileHandler::AddEvents() { - for (auto parameter : eventParameters) - { - fStream->writeStartElement(outputTags.EVENTPARAMETER); - fStream->writeAttribute(outputAttributes.KEY, QString::fromStdString(parameter.key)); - fStream->writeAttribute(outputAttributes.VALUE, QString::fromStdString(parameter.value)); + xmlFileStream->writeStartElement(outputTags.EVENTS); - //Closes EventParameter tag - fStream->writeEndElement(); - } -} + const auto events = dataStore.GetAcyclic(std::nullopt, std::nullopt, "*"); -void ObservationFileHandler::AddEvent(std::shared_ptr<QXmlStreamWriter> fStream, std::shared_ptr<EventInterface> event) -{ - fStream->writeStartElement(outputTags.EVENT); - fStream->writeAttribute(outputAttributes.ID, QString::number(event->GetId())); - fStream->writeAttribute(outputAttributes.TIME, QString::number(event->GetEventTime())); - fStream->writeAttribute(outputAttributes.SOURCE, QString::fromStdString(event->GetSource())); - fStream->writeAttribute(outputAttributes.NAME, QString::fromStdString(event->GetName())); - - const int& triggeringEventId = event->GetTriggeringEventId(); - if (triggeringEventId >= 0) + for (const AcyclicRow& event : *events) { - fStream->writeAttribute(outputAttributes.TRIGGERINGEVENTID, QString::number(triggeringEventId)); - } - - AddEventParameters(fStream, event->GetParametersAsString()); - - fStream->writeEndElement(); -} + xmlFileStream->writeStartElement(outputTags.EVENT); + xmlFileStream->writeAttribute(outputAttributes.TIME, QString::number(event.timestamp)); + xmlFileStream->writeAttribute(outputAttributes.SOURCE, QString::fromStdString(event.key)); + xmlFileStream->writeAttribute(outputAttributes.NAME, QString::fromStdString(event.data.name)); -void ObservationFileHandler::AddEvents(std::shared_ptr<QXmlStreamWriter> fStream, - SimulationSlave::EventNetworkInterface* eventNetwork) -{ - // write events - fStream->writeStartElement(outputTags.EVENTS); + WriteEntities(outputTags.TRIGGERINGENTITIES, event.data.triggeringEntities.entities, true); + WriteEntities(outputTags.AFFECTEDENTITIES, event.data.affectedEntities.entities, true); + WriteParameter(event.data.parameter, true); - for (const auto& eventList : * (eventNetwork->GetArchivedEvents())) - { - for (const auto& event : eventList.second) - { - AddEvent(fStream, event); - } - } - - for (const auto& eventList : * (eventNetwork->GetActiveEvents())) - { - for (const auto& event : eventList.second) - { - AddEvent(fStream, event); - } + xmlFileStream->writeEndElement(); // event } - // close EventsTag - fStream->writeEndElement(); + xmlFileStream->writeEndElement(); // events } -void ObservationFileHandler::AddAgents(std::shared_ptr<QXmlStreamWriter> fStream, WorldInterface* world) +void ObservationFileHandler::AddAgents() { - //write Agents - fStream->writeStartElement(outputTags.AGENTS); + xmlFileStream->writeStartElement(outputTags.AGENTS); - for (const auto& it : world->GetAgents()) - { - const AgentInterface* agent = it.second; - AddAgent(fStream, agent); - } + const auto agentIds = dataStore.GetKeys("Statics/Agents"); - for (const auto& it : world->GetRemovedAgents()) + for (const auto& agentId : agentIds) { - const AgentInterface* agent = it; - AddAgent(fStream, agent); + AddAgent(agentId); } - fStream->writeEndElement(); + xmlFileStream->writeEndElement(); } -void ObservationFileHandler::AddAgent(std::shared_ptr<QXmlStreamWriter> fStream, const AgentInterface* agent) +void ObservationFileHandler::AddAgent(const std::string& agentId) { - fStream->writeStartElement(outputTags.AGENT); + const std::string keyPrefix = "Agents/" + agentId + "/"; - const auto& agentCategory = static_cast<int>(agent->GetAgentCategory()); + xmlFileStream->writeStartElement(outputTags.AGENT); - fStream->writeAttribute(outputAttributes.ID, QString::number(agent->GetId())); - fStream->writeAttribute(outputAttributes.AGENTTYPEGROUPNAME, - QString::fromStdString(AgentCategoryStrings[agentCategory])); - fStream->writeAttribute(outputAttributes.AGENTTYPENAME, QString::fromStdString(agent->GetAgentTypeName())); - fStream->writeAttribute(outputAttributes.VEHICLEMODELTYPE, QString::fromStdString(agent->GetVehicleModelType())); - fStream->writeAttribute(outputAttributes.DRIVERPROFILENAME, QString::fromStdString(agent->GetDriverProfileName())); + xmlFileStream->writeAttribute(outputAttributes.ID, QString::fromStdString(agentId)); + xmlFileStream->writeAttribute(outputAttributes.AGENTTYPEGROUPNAME, QString::fromStdString(std::get<std::string>(dataStore.GetStatic(keyPrefix + "AgentTypeGroupName").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.AGENTTYPENAME, QString::fromStdString(std::get<std::string>(dataStore.GetStatic(keyPrefix + "AgentTypeName").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.VEHICLEMODELTYPE, QString::fromStdString(std::get<std::string>(dataStore.GetStatic(keyPrefix + "VehicleModelType").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.DRIVERPROFILENAME, QString::fromStdString(std::get<std::string>(dataStore.GetStatic(keyPrefix + "DriverProfileName").at(0)))); - AddVehicleAttributes(fStream, agent->GetVehicleModelParameters()); - AddSensors(fStream, agent); + AddVehicleAttributes(agentId); + AddSensors(agentId); - fStream->writeEndElement(); + xmlFileStream->writeEndElement(); } -void ObservationFileHandler::AddVehicleAttributes(std::shared_ptr<QXmlStreamWriter> fStream, const VehicleModelParameters &vehicleModelParameters) +void ObservationFileHandler::AddVehicleAttributes(const std::string& agentId) { - fStream->writeStartElement(outputTags.VEHICLEATTRIBUTES); + const std::string keyPrefix = "Agents/" + agentId + "/Vehicle/"; - fStream->writeAttribute(outputAttributes.WIDTH, - QString::number(vehicleModelParameters.width)); - fStream->writeAttribute(outputAttributes.LENGTH, - QString::number(vehicleModelParameters.length)); - fStream->writeAttribute(outputAttributes.HEIGHT, - QString::number(vehicleModelParameters.height)); + xmlFileStream->writeStartElement(outputTags.VEHICLEATTRIBUTES); - const double longitudinalPivotOffset = (vehicleModelParameters.length / 2.0) - vehicleModelParameters.distanceReferencePointToLeadingEdge; - fStream->writeAttribute(outputAttributes.LONGITUDINALPIVOTOFFSET, - QString::number(longitudinalPivotOffset)); + xmlFileStream->writeAttribute(outputAttributes.WIDTH, QString::number(std::get<double>(dataStore.GetStatic(keyPrefix + "Width").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.LENGTH, QString::number(std::get<double>(dataStore.GetStatic(keyPrefix + "Length").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.HEIGHT, QString::number(std::get<double>(dataStore.GetStatic(keyPrefix + "Height").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.LONGITUDINALPIVOTOFFSET, QString::number(std::get<double>(dataStore.GetStatic(keyPrefix + "LongitudinalPivotOffset").at(0)))); - fStream->writeEndElement(); + xmlFileStream->writeEndElement(); } -void ObservationFileHandler::AddSensors(std::shared_ptr<QXmlStreamWriter> fStream, const AgentInterface* agent) +void ObservationFileHandler::AddSensors(const std::string& agentId) { - const openpass::sensors::Parameters sensorParameters = agent->GetSensorParameters(); + const std::string keyPrefix = "Statics/Agents/" + agentId + "/Vehicle/Sensors"; + const auto& sensorIds = dataStore.GetKeys(keyPrefix); - if (ContainsSensor(sensorParameters)) + if (sensorIds.empty()) { - fStream->writeStartElement(outputTags.SENSORS); + return; + } - for (const auto& itSensors : sensorParameters) - { - AddSensor(fStream, itSensors); - } + xmlFileStream->writeStartElement(outputTags.SENSORS); - fStream->writeEndElement(); + for (const auto& sensorId : sensorIds) + { + AddSensor(agentId, sensorId); } + + xmlFileStream->writeEndElement(); } bool ObservationFileHandler::ContainsSensor(const openpass::sensors::Parameters& sensorParameters) const @@ -299,86 +257,73 @@ bool ObservationFileHandler::ContainsSensor(const openpass::sensors::Parameters& return !sensorParameters.empty(); } -void ObservationFileHandler::AddSensor(std::shared_ptr<QXmlStreamWriter> fStream, - const openpass::sensors::Parameter& sensorParameter) +void ObservationFileHandler::AddSensor(const std::string& agentId, const::std::string& sensorId) { - fStream->writeStartElement(outputTags.SENSOR); - - fStream->writeAttribute(outputAttributes.ID, QString::number(sensorParameter.id)); + const std::string sensorKeyPrefix = "Agents/" + agentId + "/Vehicle/Sensors/" + sensorId + "/"; + const std::string mountingKeyPrefix = sensorKeyPrefix + "Mounting/"; - fStream->writeAttribute(outputAttributes.TYPE, QString::fromStdString(sensorParameter.profile.type)); - fStream->writeAttribute(outputAttributes.MOUNTINGPOSITIONLONGITUDINAL, - QString::number(sensorParameter.position.longitudinal)); - fStream->writeAttribute(outputAttributes.MOUNTINGPOSITIONLATERAL, - QString::number(sensorParameter.position.lateral)); - fStream->writeAttribute(outputAttributes.MOUNTINGPOSITIONHEIGHT, - QString::number(sensorParameter.position.height)); - fStream->writeAttribute(outputAttributes.ORIENTATIONPITCH, QString::number(sensorParameter.position.pitch)); - fStream->writeAttribute(outputAttributes.ORIENTATIONYAW, QString::number(sensorParameter.position.yaw)); - fStream->writeAttribute(outputAttributes.ORIENTATIONROLL, QString::number(sensorParameter.position.roll)); + xmlFileStream->writeStartElement(outputTags.SENSOR); - const auto& parameters = sensorParameter.profile.parameter; + xmlFileStream->writeAttribute(outputAttributes.ID, QString::fromStdString(sensorId)); + xmlFileStream->writeAttribute(outputAttributes.TYPE, QString::fromStdString(std::get<std::string>(dataStore.GetStatic(sensorKeyPrefix + "Type").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.MOUNTINGPOSITIONLONGITUDINAL, QString::number(std::get<double>(dataStore.GetStatic(mountingKeyPrefix + "Position/Longitudinal").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.MOUNTINGPOSITIONLATERAL, QString::number(std::get<double>(dataStore.GetStatic(mountingKeyPrefix + "Position/Lateral").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.MOUNTINGPOSITIONHEIGHT, QString::number(std::get<double>(dataStore.GetStatic(mountingKeyPrefix + "Position/Height").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.ORIENTATIONYAW, QString::number(std::get<double>(dataStore.GetStatic(mountingKeyPrefix + "Orientation/Yaw").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.ORIENTATIONPITCH, QString::number(std::get<double>(dataStore.GetStatic(mountingKeyPrefix + "Orientation/Pitch").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.ORIENTATIONROLL, QString::number(std::get<double>(dataStore.GetStatic(mountingKeyPrefix + "Orientation/Roll").at(0)))); - if (auto latency = openpass::parameter::Get<double>(parameters, "Latency")) - { - fStream->writeAttribute(outputAttributes.LATENCY, QString::number(latency.value())); - } + xmlFileStream->writeAttribute(outputAttributes.LATENCY, QString::number(std::get<double>(dataStore.GetStatic(sensorKeyPrefix + "Parameters/Latency").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.OPENINGANGLEH, QString::number(std::get<double>(dataStore.GetStatic(sensorKeyPrefix + "Parameters/OpeningAngleH").at(0)))); + xmlFileStream->writeAttribute(outputAttributes.DETECTIONRANGE, QString::number(std::get<double>(dataStore.GetStatic(sensorKeyPrefix + "Parameters/Range").at(0)))); - if (auto openingAngleH = openpass::parameter::Get<double>(parameters, "OpeningAngleH")) + try { - fStream->writeAttribute(outputAttributes.OPENINGANGLEH, QString::number(openingAngleH.value())); + xmlFileStream->writeAttribute(outputAttributes.OPENINGANGLEV, QString::number(std::get<double>(dataStore.GetStatic(sensorKeyPrefix + "Parameters/OpeningAngleV").at(0)))); } - - if (auto openingAngleV = openpass::parameter::Get<double>(parameters, "OpeningAngleV")) + catch (const std::out_of_range&) { - fStream->writeAttribute(outputAttributes.OPENINGANGLEV, QString::number(openingAngleV.value())); } - if (auto detectionRange = openpass::parameter::Get<double>(parameters, "DetectionRange")) - { - fStream->writeAttribute(outputAttributes.DETECTIONRANGE, QString::number(detectionRange.value())); - } - - fStream->writeEndElement(); // Close Sensor Tag for this sensor + xmlFileStream->writeEndElement(); } -void ObservationFileHandler::AddHeader(std::shared_ptr<QXmlStreamWriter> fStream, ObservationCyclics& cyclics) +void ObservationFileHandler::AddHeader(ObservationCyclics& cyclics) { - fStream->writeStartElement(outputTags.HEADER); - - fStream->writeCharacters(QString::fromStdString(cyclics.GetHeader())); - - fStream->writeEndElement(); + xmlFileStream->writeStartElement(outputTags.HEADER); + xmlFileStream->writeCharacters(QString::fromStdString(cyclics.GetHeader())); + xmlFileStream->writeEndElement(); } -void ObservationFileHandler::AddSamples(std::shared_ptr<QXmlStreamWriter> fStream, ObservationCyclics& cyclics) +void ObservationFileHandler::AddSamples(ObservationCyclics& cyclics) { // write SamplesTag - fStream->writeStartElement(outputTags.SAMPLES); - auto timeSteps = cyclics.GetTimeSteps(); - for (unsigned int timeStepNumber = 0; timeStepNumber < timeSteps->size(); ++timeStepNumber) + xmlFileStream->writeStartElement(outputTags.SAMPLES); + const auto& timeSteps = cyclics.GetTimeSteps(); + + for (unsigned int timeStepNumber = 0; timeStepNumber < timeSteps.size(); ++timeStepNumber) { - fStream->writeStartElement(outputTags.SAMPLE); - fStream->writeAttribute(outputAttributes.TIME, QString::number(timeSteps->at(timeStepNumber))); - fStream->writeCharacters(QString::fromStdString(cyclics.GetSamplesLine(timeStepNumber))); + xmlFileStream->writeStartElement(outputTags.SAMPLE); + xmlFileStream->writeAttribute(outputAttributes.TIME, QString::number(timeSteps.at(timeStepNumber))); + xmlFileStream->writeCharacters(QString::fromStdString(cyclics.GetSamplesLine(timeStepNumber))); // close SampleTag - fStream->writeEndElement(); + xmlFileStream->writeEndElement(); } // close SamplesTag - fStream->writeEndElement(); + xmlFileStream->writeEndElement(); } -void ObservationFileHandler::AddReference(std::shared_ptr<QXmlStreamWriter> fStream, QString filename) +void ObservationFileHandler::AddReference(QString filename) { // write CyclicsFileTag - fStream->writeStartElement(outputTags.CYCLICSFILE); + xmlFileStream->writeStartElement(outputTags.CYCLICSFILE); - fStream->writeCharacters(filename); + xmlFileStream->writeCharacters(filename); // close CyclicsFileTag - fStream->writeEndElement(); + xmlFileStream->writeEndElement(); } void ObservationFileHandler::RemoveCsvCyclics(QString directory) @@ -399,7 +344,7 @@ void ObservationFileHandler::WriteCsvCyclics(QString filename, ObservationCyclic { QString path = folder + QDir::separator() + filename; - csvFile = std::make_shared<QFile>(path); + csvFile = std::make_unique<QFile>(path); if (!csvFile->open(QIODevice::WriteOnly | QIODevice::Text)) { std::stringstream ss; @@ -408,17 +353,64 @@ void ObservationFileHandler::WriteCsvCyclics(QString filename, ObservationCyclic throw std::runtime_error(ss.str()); } - QTextStream stream( csvFile.get() ); + QTextStream stream(csvFile.get()); stream << "Timestep, " << QString::fromStdString(cyclics.GetHeader()) << '\n'; - auto timeSteps = cyclics.GetTimeSteps(); - for (unsigned int timeStepNumber = 0; timeStepNumber < timeSteps->size(); ++timeStepNumber) + const auto& timeSteps = cyclics.GetTimeSteps(); + for (unsigned int timeStepNumber = 0; timeStepNumber < timeSteps.size(); ++timeStepNumber) { - stream << QString::number(timeSteps->at(timeStepNumber)) << ", " << QString::fromStdString(cyclics.GetSamplesLine(timeStepNumber)) << '\n'; + stream << QString::number(timeSteps.at(timeStepNumber)) << ", " << QString::fromStdString(cyclics.GetSamplesLine(timeStepNumber)) << '\n'; } csvFile->flush(); csvFile->close(); } + +void ObservationFileHandler::WriteEntities(const QString tag, const openpass::type::EntityIds &entities, bool mandatory) +{ + if (!entities.empty()) + { + xmlFileStream->writeStartElement(tag); + for (const auto &entity : entities) + { + xmlFileStream->writeStartElement(output::tag::ENTITY); + xmlFileStream->writeAttribute(output::attribute::ID, QString::number(entity)); + xmlFileStream->writeEndElement(); + } + xmlFileStream->writeEndElement(); + } + else if (mandatory) + { + xmlFileStream->writeEmptyElement(tag); + } +} + +void ObservationFileHandler::WriteParameter(const openpass::type::FlatParameter ¶meters, bool mandatory) +{ + constexpr auto tag = output::tag::PARAMETERS; + if (!parameters.empty()) + { + xmlFileStream->writeStartElement(tag); + + // No structured binding on purpose: + // see https://stackoverflow.com/questions/46114214/lambda-implicit-capture-fails-with-variable-declared-from-structured-binding + for (const auto &p : parameters) + { + auto parameterWriter = [&](const std::string &value) { + xmlFileStream->writeStartElement(output::tag::PARAMETER); + xmlFileStream->writeAttribute(output::attribute::KEY, QString::fromStdString(p.first)); + xmlFileStream->writeAttribute(output::attribute::VALUE, QString::fromStdString(value)); + xmlFileStream->writeEndElement(); + }; + + std::visit(openpass::utils::FlatParameter::to_string(parameterWriter), p.second); + } + xmlFileStream->writeEndElement(); + } + else if (mandatory) + { + xmlFileStream->writeEmptyElement(tag); + } +} diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationFileHandler.h b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationFileHandler.h index e469cec54d8dd0d08ad3ee921ff9a73c57cca8c5..baff46cbba19a7af8004430ddf38de4d09a5be52 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationFileHandler.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationFileHandler.h @@ -12,16 +12,18 @@ #pragma once #include <string> + +#include <QDirIterator> #include <QFile> #include <QFileInfo> +#include <QTemporaryFile> #include <QTextStream> #include <QXmlStreamWriter> -#include <QDirIterator> -#include "Interfaces/observationInterface.h" #include "Interfaces/eventNetworkInterface.h" -#include "observationLogConstants.h" +#include "Interfaces/observationInterface.h" #include "observationCyclics.h" +#include "observationLogConstants.h" #include "runStatistic.h" //----------------------------------------------------------------------------- @@ -39,11 +41,11 @@ class ObservationFileHandler public: const std::string COMPONENTNAME = "ObservationFileHandler"; - ObservationFileHandler() = default; - ObservationFileHandler(const ObservationFileHandler&) = delete; - ObservationFileHandler(ObservationFileHandler&&) = delete; - ObservationFileHandler& operator=(const ObservationFileHandler&) = delete; - ObservationFileHandler& operator=(ObservationFileHandler&&) = delete; + ObservationFileHandler(const DataStoreReadInterface& dataStore); + ObservationFileHandler(const ObservationFileHandler &) = delete; + ObservationFileHandler(ObservationFileHandler &&) = delete; + ObservationFileHandler &operator=(const ObservationFileHandler &) = delete; + ObservationFileHandler &operator=(ObservationFileHandler &&) = delete; ~ObservationFileHandler() = default; /*! @@ -51,17 +53,19 @@ public: * * \param outputDir path of output directory */ - void SetOutputDir(std::string outputDir) + void SetOutputLocation(const std::string& outputDir, const std::string& outputFile) { folder = QString::fromStdString(outputDir); + finalFilename = QString::fromStdString(outputFile); + finalPath = folder + QDir::separator() + finalFilename; } - void SetSceneryFile (std::string fileName) + void SetSceneryFile(const std::string& fileName) { sceneryFile = fileName; } - void SetCsvOutput (bool writeCsv) + void SetCsvOutput(bool writeCsv) { writeCyclicsToCsv = writeCsv; } @@ -69,7 +73,7 @@ public: /*! * \brief Creates the output file as simulationOutput.tmp and writes the basic header information */ - void WriteStartOfFile(const std::string& frameworkVersion); + void WriteStartOfFile(const std::string &frameworkVersion); /*! * \brief This function gets called after each run and writes all information about this run into the output file @@ -77,11 +81,9 @@ public: * \param runResult * \param runStatistik * \param cyclics - * \param world - * \param eventNetwork + * \param dataStore */ - void WriteRun(const RunResultInterface& runResult, RunStatistic runStatistik, ObservationCyclics& cyclics, - WorldInterface* world, SimulationSlave::EventNetworkInterface* eventNetwork); + void WriteRun(const RunResultInterface& runResult, RunStatistic runStatistik, ObservationCyclics& cyclics); /*! * \brief Closes the xml tags flushes the output file, closes it and renames it to simulationOutput.xlm @@ -89,23 +91,24 @@ public: void WriteEndOfFile(); private: - std::shared_ptr<QXmlStreamWriter> xmlFileStream; + std::unique_ptr<QXmlStreamWriter> xmlFileStream; + const DataStoreReadInterface& dataStore; - int runNumber; //!< run number + int runNumber; //!< run number std::string sceneryFile; - bool writeCyclicsToCsv {false}; + bool writeCyclicsToCsv{false}; - const OutputAttributes outputAttributes; - const OutputTags outputTags; + OutputAttributes outputAttributes; + OutputTags outputTags; QString folder; QString tmpFilename; QString finalFilename; QString tmpPath; QString finalPath; - std::shared_ptr<QFile> xmlFile; - std::shared_ptr<QFile> csvFile; + std::unique_ptr<QTemporaryFile> xmlFile; + std::unique_ptr<QFile> csvFile; //add infos to the file stream /*! @@ -113,7 +116,7 @@ private: * * @return true if agent has sensors, otherwise false. */ - inline bool ContainsSensor(const openpass::sensors::Parameters& sensorParameters) const; + inline bool ContainsSensor(const openpass::sensors::Parameters &sensorParameters) const; /*! * \brief Writes the sensor information into the simulation output. @@ -121,7 +124,7 @@ private: * @param[in] fStream Shared pointer of the stream writer. * @param[in] sensorParameter Parameters of the sensor. */ - void AddSensor(std::shared_ptr<QXmlStreamWriter> fStream, const openpass::sensors::Parameter& sensorParameter); + void AddSensor(const std::string& agentId, const std::string& sensorId); /*! * \brief Writes the sensor information into the simulation output. @@ -129,7 +132,7 @@ private: * @param[in] fStream Shared pointer of the stream writer. * @param[in] vehicleModelParameters Parameters of the vehicle. */ - void AddVehicleAttributes(std::shared_ptr<QXmlStreamWriter> fStream, const VehicleModelParameters &vehicleModelParameters); + void AddVehicleAttributes(const std::string& agentId); /*! * \brief Writes all sensor information of an agent into the simulation output. @@ -137,7 +140,7 @@ private: * @param[in] fStream Shared pointer of the stream writer. * @param[in] agent Pointer to the agent. */ - void AddSensors(std::shared_ptr<QXmlStreamWriter> fStream, const AgentInterface* agent); + void AddSensors(const std::string& agentId); /*! * \brief Writes the content of an agent into the simulation output. @@ -145,52 +148,35 @@ private: * @param[in] fStream Shared pointer of the stream writer. * @param[in] agent Pointer to the agent. */ - void AddAgent(std::shared_ptr<QXmlStreamWriter> fStream, const AgentInterface* agent); + void AddAgent(const std::string& agentId); /*! * \brief Writes the content of all agent into the simulation output. * * @param[in] fStream Shared pointer of the stream writer. */ - void AddAgents(std::shared_ptr<QXmlStreamWriter> fStream, WorldInterface* world); - - /*! - * \brief Writes all parameters of an event into the simulation output. - * - * @param[in] fStream Shared pointer of the stream writer. - * @param[in] eventParameters Parameters of an event in string representation. - */ - void AddEventParameters(std::shared_ptr<QXmlStreamWriter> fStream, - EventParameters eventParameters); - - /*! - * \brief Writes an event into the simulation output. - * - * @param[in] fStream Shared pointer of the stream writer. - * @param[in] event Shared pointer of the event. - */ - void AddEvent(std::shared_ptr<QXmlStreamWriter> fStream, std::shared_ptr<EventInterface> event); + void AddAgents(); /*! * \brief Writes all events into the simulation output. * * @param[in] fStream Shared pointer of the stream writer. */ - void AddEvents(std::shared_ptr<QXmlStreamWriter> fStream, SimulationSlave::EventNetworkInterface* eventNetwork); + void AddEvents(); /*! * \brief Writes the header into the simulation output during full logging. * * @param[in] fStream Shared pointer of the stream writer. */ - void AddHeader(std::shared_ptr<QXmlStreamWriter> fStream, ObservationCyclics& cyclics); + void AddHeader(ObservationCyclics& cyclics); /*! * \brief Writes the samples into the simulation output during full logging. * * @param[in] fStream Shared pointer of the stream writer. */ - void AddSamples(std::shared_ptr<QXmlStreamWriter> fStream, ObservationCyclics& cyclics); + void AddSamples(ObservationCyclics& cyclics); /*! * \brief Writes the filename for the cyclics file into the simulation output during full logging. @@ -198,7 +184,7 @@ private: * @param[in] fStream Shared pointer of the stream writer. * @param[in] filename Name of the file, where cyclics are written to. */ - void AddReference(std::shared_ptr<QXmlStreamWriter> fStream, QString filename); + void AddReference(QString filename); /*! * \brief Removes old cyclic files from directory. @@ -213,10 +199,27 @@ private: * @param[in] runId Id of the current run * @param[in] cyclics Cyclics of the current run */ - void WriteCsvCyclics(QString runId, ObservationCyclics& cyclics); + void WriteCsvCyclics(QString runId, ObservationCyclics &cyclics); + + /*! + * \brief Write entities to XML + * + * \param tag tag name + * \param entities list of entities + * \param mandatory if set, an emtpy tag is added if entities is empty (default false) + */ + void WriteEntities(const QString tag, const openpass::type::EntityIds &entities, bool mandatory = false); + + /*! + * \brief Write (event) parameter to XML + * + * \remark Might be used for generic parameters in the future - right now, only event parameters + * + * \param[in] parameters list of parameters + * \param[in] mandatory if set, an emtpy tag is added if parameters are empty (default false) + */ + void WriteParameter(const openpass::type::FlatParameter ¶meters, bool mandatory = false); private: const QString outputFileVersion = "0.2.1"; }; - - diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationLogConstants.h b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationLogConstants.h index 445492670c95636fed4331ae5f5d7a67da7ed0d1..c0e17f75f5b2e81617bb8339b45296de3e40f77a 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationLogConstants.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationLogConstants.h @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2017, 2018, 2019 in-tech GmbH +* Copyright (c) 2017, 2018, 2019, 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -17,7 +17,7 @@ struct OutputAttributes const QString FRAMEWORKVERSION = "FrameworkVersion"; const QString SCHEMAVERSION = "SchemaVersion"; const QString RUNID = "RunId"; - const QString FAILUREPROBABITLITY= "FailureProbability"; + const QString FAILUREPROBABITLITY = "FailureProbability"; const QString LATENCY = "Latency"; const QString OPENINGANGLEH = "OpeningAngleH"; const QString OPENINGANGLEV = "OpeningAngleV"; @@ -35,7 +35,6 @@ struct OutputAttributes const QString TIME = "Time"; const QString TYPE = "Type"; const QString NAME = "Name"; - const QString TRIGGERINGEVENTID = "TriggeringEventId"; const QString KEY = "Key"; const QString VALUE = "Value"; const QString ID = "Id"; @@ -66,4 +65,28 @@ struct OutputTags const QString SAMPLE = "Sample"; const QString SCENERYFILE = "SceneryFile"; const QString VEHICLEATTRIBUTES = "VehicleAttributes"; + const QString TRIGGERINGENTITIES = "TriggeringEntities"; + const QString AFFECTEDENTITIES = "AffectedEntities"; }; + +namespace output::tag { +static constexpr char ENTITY[] = "Entity"; +static constexpr char PARAMETERS[] = "Parameters"; +static constexpr char PARAMETER[] = "Parameter"; +} // namespace output::tag + +namespace output::attribute { +static constexpr char ID[] = "Id"; +static constexpr char TIME[] = "Time"; +static constexpr char TYPE[] = "Type"; +static constexpr char NAME[] = "Name"; +static constexpr char KEY[] = "Key"; +static constexpr char VALUE[] = "Value"; +} // namespace output::attribute + +namespace output::event::tag { +static constexpr char EVENTS[] = "NewEvents"; +static constexpr char EVENT[] = "Event"; +static constexpr char TRIGGERING_ENTITIES[] = "TriggeringEntities"; +static constexpr char AFFECTED_ENTITIES[] = "AffectedEntities"; +} // namespace output::event::tag diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationLogGlobal.h b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_LogGlobal.h similarity index 62% rename from OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationLogGlobal.h rename to OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_LogGlobal.h index cbc4e897ed75cc687eecd56a1fa75f69f506a4d8..58b705a82f233cf2329d3fae2ddc5f2a2a100121 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observationLogGlobal.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_LogGlobal.h @@ -1,6 +1,5 @@ /******************************************************************************* -* Copyright (c) 2017, 2019 in-tech GmbH -* 2016, 2017 ITK Engineering GmbH +* Copyright (c) 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -9,13 +8,10 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -//----------------------------------------------------------------------------- -/** @file ObservationLogGlobal.h -* @brief This file contains DLL export declarations -* -* This class contains all functionality of the module. -*/ -//----------------------------------------------------------------------------- +/** + * \file observation_LogGlobal.h + * \brief This file contains DLL export declarations + */ #pragma once diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_log.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_log.cpp index e764c170816d2ae3d212a3f59e20e83977478049..a649db84039de61eacf99d741308c94c2599a939 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_log.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_log.cpp @@ -1,6 +1,5 @@ /******************************************************************************* -* Copyright (c) 2017, 2018, 2019 in-tech GmbH -* 2016, 2017, 2018 ITK Engineering GmbH +* Copyright (c) 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -10,13 +9,15 @@ *******************************************************************************/ //----------------------------------------------------------------------------- -/** \file ObservationLog.cpp */ +/** \file observation_Log.cpp */ //----------------------------------------------------------------------------- #include "observation_log.h" #include "observation_logImplementation.h" -const std::string Version = "1.0.0"; //!< The version of the current module - has to be incremented manually +class DataStoreReadInterface; + +const std::string Version = "0.2.0"; //!< The version of the current module - has to be incremented manually static const CallbackInterface* Callbacks = nullptr; //----------------------------------------------------------------------------- @@ -43,17 +44,19 @@ extern "C" OBSERVATION_LOG_SHARED_EXPORT ObservationInterface* OpenPASS_CreateIn WorldInterface* world, SimulationSlave::EventNetworkInterface* eventNetwork, const ParameterInterface* parameters, - const CallbackInterface* callbacks) + const CallbackInterface* callbacks, + DataStoreReadInterface* dataStore) { Callbacks = callbacks; try { return (ObservationInterface*)(new (std::nothrow) ObservationLogImplementation(eventNetwork, - stochastics, - world, - parameters, - callbacks)); + stochastics, + world, + parameters, + callbacks, + dataStore)); } catch (const std::runtime_error& ex) { diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_log.h b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_log.h index b5649928c05b27eca27e6a726bc2203497ea7d11..7bc7f4d5100c537ca4ddb284073dcd4ca64edbd6 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_log.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_log.h @@ -1,6 +1,5 @@ /******************************************************************************* -* Copyright (c) 2017, 2019 in-tech GmbH -* 2016, 2017 ITK Engineering GmbH +* Copyright (c) 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -10,7 +9,7 @@ *******************************************************************************/ //----------------------------------------------------------------------------- -/** @file ObservationLog.h +/** @file observation_Log.h * @brief This file provides the exported methods. * * This file provides the exported methods which are available outside of the library. @@ -19,7 +18,7 @@ #pragma once -#include "observationLogGlobal.h" +#include "observation_LogGlobal.h" #include "Interfaces/observationInterface.h" diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_logImplementation.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_logImplementation.cpp index 219134ef86d35aa267e6f7709c1577bccaba2dfd..a17545b1e84a14832111bc6815f76d51c2291d74 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_logImplementation.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_logImplementation.cpp @@ -9,130 +9,98 @@ *******************************************************************************/ //----------------------------------------------------------------------------- -/** \file ObservationLogImplementation */ +/** \file observation_LogImplementation */ //----------------------------------------------------------------------------- -#include <cassert> -#include <sstream> -#include <QDir> +#include <unordered_map> +#include <variant> +#include <vector> +#include "Common/commonTools.h" +#include "Common/observationTypes.h" +#include "Common/openPassUtils.h" + +#include "Interfaces/dataStoreInterface.h" #include "Interfaces/stochasticsInterface.h" -#include "Interfaces/worldInterface.h" #include "Interfaces/parameterInterface.h" +#include "Interfaces/worldInterface.h" + #include "observation_logImplementation.h" + +#include "observationCyclics.h" #include "runStatisticCalculation.h" +#include "runStatistic.h" -ObservationLogImplementation::ObservationLogImplementation(SimulationSlave::EventNetworkInterface* eventNetwork, +ObservationLogImplementation::ObservationLogImplementation( + SimulationSlave::EventNetworkInterface* eventNetwork, StochasticsInterface* stochastics, WorldInterface* world, const ParameterInterface* parameters, - const CallbackInterface* callbacks) : + const CallbackInterface* callbacks, + DataStoreReadInterface* dataStore) : ObservationInterface(stochastics, world, parameters, - callbacks), + callbacks, + dataStore), runtimeInformation(parameters->GetRuntimeInformation()), - eventNetwork(eventNetwork) + eventNetwork(eventNetwork), + dataStore(dataStore), + fileHandler{*dataStore} +{ +} + +void ObservationLogImplementation::SlavePreHook() { - // read parameters + std::string filename{"simulationOutput.xml"}; + try { - fileHandler.SetSceneryFile(parameters->GetParametersString().at("SceneryFile")); - fileHandler.SetCsvOutput(parameters->GetParametersBool().at("LoggingCyclicsToCsv")); - auto loggingGroupsfromConfig = parameters->GetParametersStringVector().at("LoggingGroups"); - for (auto loggingGroup : loggingGroupsfromConfig) - { - if (loggingGroup == "Trace") - { - loggingGroups.push_back(LoggingGroup::Trace); - continue; - } - if (loggingGroup == "Visualization") - { - loggingGroups.push_back(LoggingGroup::Visualization); - continue; - } - if (loggingGroup == "RoadPosition") - { - loggingGroups.push_back(LoggingGroup::RoadPosition); - continue; - } - if (loggingGroup == "RoadPositionExtended") - { - loggingGroups.push_back(LoggingGroup::RoadPositionExtended); - continue; - } - if (loggingGroup == "Vehicle") - { - loggingGroups.push_back(LoggingGroup::Vehicle); - continue; - } - if (loggingGroup == "Sensor") - { - loggingGroups.push_back(LoggingGroup::Sensor); - continue; - } - if (loggingGroup == "SensorExtended") - { - loggingGroups.push_back(LoggingGroup::SensorExtended); - continue; - } - if (loggingGroup == "Driver") - { - loggingGroups.push_back(LoggingGroup::Driver); - continue; - } + filename = GetParameters()->GetParametersString().at("OutputFilename"); + } + catch (const std::out_of_range&) + { + LOG(CbkLogLevel::Warning, "Using default output filename: " + filename); + } - const std::string msg = "There is no logging group named " + loggingGroup; - LOG(CbkLogLevel::Error, msg); - throw std::runtime_error(msg); - } + try + { + fileHandler.SetCsvOutput(GetParameters()->GetParametersBool().at("LoggingCyclicsToCsv")); } - catch (...) + catch (const std::out_of_range&) { - const std::string msg = COMPONENTNAME + " could not init parameters"; + std::string msg = "Mandatory config parameter 'LoggingCyclicsToCsv' is missing"; LOG(CbkLogLevel::Error, msg); throw std::runtime_error(msg); } -} -//----------------------------------------------------------------------------- -//! \brief Logs a key/value pair -//! -//! @param[in] time current time -//! @param[in] agentId agent identifier -//! @param[in] group LoggingGroup the key/value pair should be assigned to -//! @param[in] key Key of the value to log -//! @param[in] value Value to log -//----------------------------------------------------------------------------- -void ObservationLogImplementation::Insert(int time, - int agentId, - LoggingGroup group, - const std::string& key, - const std::string& value) -{ - if (std::find(loggingGroups.cbegin(), loggingGroups.cend(), group) == loggingGroups.cend()) + try { - //ignore the value, because the specified group isn't logged - return; + for (const auto& loggingGroup : GetParameters()->GetParametersStringVector().at("LoggingGroups")) + { + try + { + const auto& groupColumns = LOGGINGGROUP_DEFINITIONS.at(loggingGroup); + selectedColumns.insert(groupColumns.begin(), groupColumns.end()); + } + catch (const std::out_of_range&) + { + std::string msg = "Unsupported LoggingGroup '" + loggingGroup + "'"; + LOG(CbkLogLevel::Error, msg); + throw std::runtime_error(msg); + } + } } - std::string extendedKey = (agentId < 10 ? "0" : "") + std::to_string(agentId) + ":" + key; - cyclics.Insert(time, extendedKey, value); -} + catch (const std::out_of_range&) + { + const auto& traceColumns = LOGGINGGROUP_DEFINITIONS.at("Trace"); + selectedColumns.insert(traceColumns.begin(), traceColumns.end()); -//----------------------------------------------------------------------------- -//! \brief Logs an event -//! -//! @param[in] event Shared pointer to the event to log -//----------------------------------------------------------------------------- -void ObservationLogImplementation::InsertEvent(std::shared_ptr<EventInterface> event) -{ - eventNetwork->InsertEvent(event); -} + LOG(CbkLogLevel::Warning, "No LoggingGroups configured. Defaulting to 'Trace'"); + } -void ObservationLogImplementation::SlavePreHook() -{ - fileHandler.SetOutputDir(runtimeInformation.directories.output); + fileHandler.SetOutputLocation(runtimeInformation.directories.output, filename); + fileHandler.SetSceneryFile(std::get<std::string>(dataStore->GetStatic("SceneryFile").at(0))); fileHandler.WriteStartOfFile(runtimeInformation.versions.framework.str()); } @@ -146,9 +114,24 @@ void ObservationLogImplementation::SlavePostRunHook(const RunResultInterface& ru { RunStatisticCalculation::DetermineEgoCollision(runStatistic, runResult, GetWorld()); runStatistic.VisibilityDistance = GetWorld()->GetVisibilityDistance(); - RunStatisticCalculation::CalculateTotalDistanceTraveled(runStatistic, GetWorld()); - fileHandler.WriteRun(runResult, runStatistic, cyclics, GetWorld(), eventNetwork); + const auto dsCyclics = dataStore->GetCyclic(std::nullopt, std::nullopt, "*"); + + for (const CyclicRow& dsCyclic : *dsCyclics) + { + std::stringstream entityStr; + entityStr << std::setw(2) << std::setfill('0') << dsCyclic.entityId; + + std::visit(openpass::utils::FlatParameter::to_string([this, &dsCyclic, &entityStr](const std::string& valueStr) + { + if (selectedColumns.find(dsCyclic.key) != selectedColumns.end()) + { + cyclics.Insert(dsCyclic.timestamp, entityStr.str() + ":" + dsCyclic.key, valueStr); + } + }), dsCyclic.value); + } + + fileHandler.WriteRun(runResult, runStatistic, cyclics); } void ObservationLogImplementation::SlavePostHook() diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_logImplementation.h b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_logImplementation.h index bff2e81ec3aa1946b027835cdf26948c5f4516b0..07242a5b20691114f4a70cc75d30f68202aeb9e2 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_logImplementation.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/observation_logImplementation.h @@ -19,14 +19,25 @@ #pragma once +#include <set> #include <string> #include <tuple> + #include <QFile> #include <QTextStream> -#include "runStatistic.h" + +#include "Common/runtimeInformation.h" +#include "Interfaces/observationInterface.h" + #include "observationCyclics.h" #include "observationFileHandler.h" -#include "Common/runtimeInformation.h" +#include "runStatistic.h" + +namespace SimulationSlave { +class EventNetworkInterface; +} + +class DataStoreReadInterface; //----------------------------------------------------------------------------- /** \brief This class adds the RunStatistic information to the simulation output. @@ -43,18 +54,17 @@ public: const std::string COMPONENTNAME = "ObservationLog"; ObservationLogImplementation(SimulationSlave::EventNetworkInterface* eventNetwork, - StochasticsInterface* stochastics, - WorldInterface* world, - const ParameterInterface* parameters, - const CallbackInterface* callbacks); + StochasticsInterface* stochastics, + WorldInterface* world, + const ParameterInterface* parameters, + const CallbackInterface* callbacks, + DataStoreReadInterface* dataStore); ObservationLogImplementation(const ObservationLogImplementation&) = delete; ObservationLogImplementation(ObservationLogImplementation&&) = delete; ObservationLogImplementation& operator=(const ObservationLogImplementation&) = delete; ObservationLogImplementation& operator=(ObservationLogImplementation&&) = delete; virtual ~ObservationLogImplementation() override = default; - virtual void Insert(int time, int agentId, LoggingGroup group, const std::string& key, const std::string& value) override; - virtual void InsertEvent(std::shared_ptr<EventInterface> event) override; virtual void SlavePreHook() override; virtual void SlavePreRunHook() override; virtual void SlavePostRunHook(const RunResultInterface& runResult) override; @@ -71,11 +81,12 @@ public: private: const openpass::common::RuntimeInformation& runtimeInformation; - RunStatistic runStatistic = RunStatistic(-1); - std::vector<LoggingGroup> loggingGroups{LoggingGroup::Trace}; - ObservationCyclics cyclics; - ObservationFileHandler fileHandler; SimulationSlave::EventNetworkInterface* eventNetwork; + DataStoreReadInterface* dataStore; + ObservationFileHandler fileHandler; + ObservationCyclics cyclics; + RunStatistic runStatistic = RunStatistic(-1); + std::set<std::string> selectedColumns; }; diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatistic.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatistic.cpp index d007949fc407b36eeda75aab9e7f2bde58036ff7..45a4bc9ea69281e4a6717247a9065ec9b56416af 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatistic.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatistic.cpp @@ -17,9 +17,7 @@ const QString RunStatistic::StopReasonsStrings[] = { - "Due to time out", - "Due to time after crash", - "Due to agent reached target position" + "Due to time out" }; RunStatistic::RunStatistic(std::uint32_t randomSeed): @@ -28,12 +26,12 @@ RunStatistic::RunStatistic(std::uint32_t randomSeed): void RunStatistic::AddStopReason(int time, StopReason reason) { - _stopReason = StopReasonsStrings[static_cast<int>(reason)]; + _stopReasonIdx = static_cast<int>(reason); StopTime = time; } // ----------------------------- writing out --------------------- // -void RunStatistic::WriteStatistics(std::shared_ptr<QXmlStreamWriter> fileStream) +void RunStatistic::WriteStatistics(QXmlStreamWriter* fileStream) { fileStream->writeStartElement("RandomSeed"); fileStream->writeCharacters(QString::number(_randomSeed)); @@ -44,7 +42,7 @@ void RunStatistic::WriteStatistics(std::shared_ptr<QXmlStreamWriter> fileStream) fileStream->writeEndElement(); fileStream->writeStartElement("StopReason"); - fileStream->writeCharacters(_stopReason); + fileStream->writeCharacters(StopReasonsStrings[_stopReasonIdx]); fileStream->writeEndElement(); fileStream->writeStartElement("StopTime"); @@ -52,7 +50,7 @@ void RunStatistic::WriteStatistics(std::shared_ptr<QXmlStreamWriter> fileStream) fileStream->writeEndElement(); fileStream->writeStartElement("EgoAccident"); - fileStream->writeCharacters(BoolToString(EgoCollision )); + fileStream->writeCharacters(BoolToString(EgoCollision)); fileStream->writeEndElement(); fileStream->writeStartElement("TotalDistanceTraveled"); diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatistic.h b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatistic.h index eca4ddb5760b8277ba92c62ac1309938f54d4f27..b71b8d1b1aea1c86f524d3bd0800468b2d94614a 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatistic.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatistic.h @@ -18,18 +18,18 @@ #include "Common/observationTypes.h" #include "Interfaces/observationInterface.h" -enum class StopReason -{ - DueToTimeOut -}; - class RunStatistic { public: + enum class StopReason + { + DueToTimeOut + }; + RunStatistic(std::uint32_t randomSeed); void AddStopReason(int time, StopReason reason); - void WriteStatistics(std::shared_ptr<QXmlStreamWriter> fileStream); + void WriteStatistics(QXmlStreamWriter* fileStream); // general int StopTime = -1; //this stays on UNDEFINED_NUMBER, if due time out -> replace in c# @@ -47,7 +47,7 @@ private: std::list<int> _followerIds; static const QString StopReasonsStrings[]; - QString _stopReason = StopReasonsStrings[static_cast<int>(StopReason::DueToTimeOut)]; + int _stopReasonIdx = static_cast<int>(StopReason::DueToTimeOut); }; // class RunStatistic diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatisticCalculation.cpp b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatisticCalculation.cpp index fa588f7c2aed6c244c765fbb22b6f1eee94adb29..69d7447911094d57a15254bd76d994110ec601cd 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatisticCalculation.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatisticCalculation.cpp @@ -11,29 +11,6 @@ #include "runStatisticCalculation.h" #include "Interfaces/worldInterface.h" -void RunStatisticCalculation::CalculateTotalDistanceTraveled(RunStatistic& runStatistic, WorldInterface* world) -{ - runStatistic.TotalDistanceTraveled = 0.0; - runStatistic.EgoDistanceTraveled = 0.0; - - const auto egoAgent = world->GetEgoAgent(); - - if (egoAgent) - { - runStatistic.EgoDistanceTraveled = egoAgent->GetDistanceTraveled(); - } - - for (const auto& agent : world->GetAgents()) - { - runStatistic.TotalDistanceTraveled += agent.second->GetDistanceTraveled(); - } - - for (const auto& agent : world->GetRemovedAgents()) - { - runStatistic.TotalDistanceTraveled += agent->GetDistanceTraveled(); - } -} - void RunStatisticCalculation::DetermineEgoCollision(RunStatistic& runStatistic, const RunResultInterface& runResult, WorldInterface* world) { auto egoAgent = world->GetEgoAgent(); diff --git a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatisticCalculation.h b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatisticCalculation.h index a2579cefce52baaaa71fdf3f17d45e413ce997ab..5f3d55b33b35503e8d9fb73d7d190df6be49f88f 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatisticCalculation.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/Observation_Log/runStatisticCalculation.h @@ -20,17 +20,6 @@ class WorldInterface; class RunStatisticCalculation { public: - /*! - * \brief Calculates the total distance traveled of all agents in the simulation - * - * The members `EgoDistanceTraveled` and `TotalDistanceTraveled` of the first parameter - * are used to store the result - * - * \param[out] runStatistic Result is stored here - * \param[in] world Pointer to the world - */ - static void CalculateTotalDistanceTraveled(RunStatistic& runStatistic, WorldInterface* world); - /*! * \brief Determines whether the ego had a collision and sets the related flag in the RunStatistic * diff --git a/OpenPass_Source_Code/openPASS/CoreModules/World_OSI/AgentAdapter.cpp b/OpenPass_Source_Code/openPASS/CoreModules/World_OSI/AgentAdapter.cpp index a25af3359595933d392546a4efe1224024d24135..3792f3c8513be0740daa77fb445ad5332d94290a 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/World_OSI/AgentAdapter.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules/World_OSI/AgentAdapter.cpp @@ -30,6 +30,10 @@ AgentAdapter::AgentAdapter(WorldInterface* world, { } +AgentAdapter::~AgentAdapter() +{ +} + bool AgentAdapter::InitAgentParameter(int id, AgentBlueprintInterface* agentBlueprint) { diff --git a/OpenPass_Source_Code/openPASS/CoreModules/World_OSI/AgentAdapter.h b/OpenPass_Source_Code/openPASS/CoreModules/World_OSI/AgentAdapter.h index dacd731b156e2f9b9e393af25708f8e36425d01d..bc7934eba8f0cf402677212a0fcfa9c5fce3cf50 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules/World_OSI/AgentAdapter.h +++ b/OpenPass_Source_Code/openPASS/CoreModules/World_OSI/AgentAdapter.h @@ -46,7 +46,7 @@ public: const std::string MODULENAME = "AGENTADAPTER"; AgentAdapter(WorldInterface* world, const CallbackInterface* callbacks, OWL::Interfaces::WorldData* worldData, const World::Localization::Localizer& localizer); - ~AgentAdapter() override = default; + ~AgentAdapter() override; ObjectTypeOSI GetType() const override { @@ -62,6 +62,7 @@ public: { return id; } + EgoAgentInterface& GetEgoAgent() override { return egoAgent; @@ -224,14 +225,6 @@ public: }); } - void SetDistanceTraveled(double value) override - { - world->QueueAgentUpdate([this, value]() - { - distanceTraveled = value; - }); - } - void SetVehicleModelParameter(const VehicleModelParameters& parameter) override { world->QueueAgentUpdate([this, parameter]() @@ -385,11 +378,6 @@ public: double GetVelocity(VelocityScope velocityScope = VelocityScope::Absolute) const override; - double GetDistanceTraveled() const override - { - return distanceTraveled; - } - void Unregister() const override; double GetLaneRemainder(const std::string& roadId, Side side) const override; diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm.cpp b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm.cpp index ab04a55103b437dfa249e073d122498ea5eb3e21..907f16a4247aa4ca8abd50a2c5338d9c8d459554 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm.cpp @@ -9,7 +9,6 @@ **********************************************************************/ #include "evaluation_pcm.h" -#include "observationInterface.h" #include "evaluation_pcm_implementation.h" const std::string Version = "1.1.0"; //!< version of the current module - has to be incremented manually diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm.h b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm.h index 108a05bec7428c29742c871db130d3ee3792ad52..b2499a30407a34c55cf0086fbc570e5fe1796c10 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm.h +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm.h @@ -17,6 +17,5 @@ #define EVALUATION_PCM_H #include "evaluation_pcm_global.h" -#include "observationInterface.h" #endif // EVALUATION_PCM_H diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm_implementation.h b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm_implementation.h index 5a7300072c8f24b61ad07f675677870cf8ee295f..b3c658588e68a5fa065f4d9b576faa511c84869f 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm_implementation.h +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/evaluation_pcm_implementation.h @@ -21,7 +21,6 @@ #include <fstream> #include <string> -#include "observationInterface.h" #include "agent.h" #include "runResult.h" #include "componentPorts.h" diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/runResult.h b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/runResult.h index f1b992042c3dcd269f883aa1e2dc7e00886179a8..76919a98b89769cc9f5bbee5c49b85cf5eb1a76c 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/runResult.h +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Evaluation_Pcm/runResult.h @@ -20,7 +20,6 @@ #include <list> #include <map> #include "worldInterface.h" -#include "observationInterface.h" //----------------------------------------------------------------------------- //! Class that has all informations on the run result diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision.cpp b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision.cpp index 9d67d9d94594fd0a1a4b9b89549e60053a01600a..192141b842af088220be41e7ccfb846cf4683220 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision.cpp @@ -14,7 +14,6 @@ //----------------------------------------------------------------------------- #include "observation_collision.h" -#include "observationInterface.h" #include "observation_collision_implementation.h" const std::string Version = "0.0.1"; //!< The version of the current module - has to be incremented manually diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision.h b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision.h index 9acdf7bac0238cb98346a558cfcc78cecab8d28b..59a3a8b921f950b06af953198cd09ab20cd3f611 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision.h +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision.h @@ -20,6 +20,5 @@ #define OBSERVATION_COLLISION_H #include "observation_collision_global.h" -#include "observationInterface.h" #endif // OBSERVATION_COLLISION_H diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision_implementation.h b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision_implementation.h index cec684dc75e39e4aa92d9caab441fd512cef48c9..897d17360505acd6b24830fc4cb8ddc067b0f822 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision_implementation.h +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_Collision/observation_collision_implementation.h @@ -18,7 +18,6 @@ #include <QTextStream> #include <QXmlStreamWriter> #include "componentPorts.h" -#include "observationInterface.h" /** * \addtogroup CoreModules_PCM openPASS CoreModules pcm diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger.cpp b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger.cpp index b988d3534bb3f0510c64e3370abd062bf8154040..f2abbbdf8cdb29a454188cec73b5fb8e304747a9 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger.cpp +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger.cpp @@ -15,7 +15,6 @@ //----------------------------------------------------------------------------- #include "observation_scopeLogger.h" -#include "observationInterface.h" #include "observation_scopeLogger_implementation.h" const std::string Version = "0.0.1"; //!< The version of the current module - has to be incremented manually diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger.h b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger.h index cb9d170fa293acba243ed83b51c5d9c79324e198..5b5bcdf9edcd723dfed4f59c403128c3cdd898a4 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger.h +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger.h @@ -21,6 +21,5 @@ #define OBSERVATION_SCOPELOGGER_H #include "observation_scopeLogger_global.h" -#include "observationInterface.h" #endif // OBSERVATION_SCOPELOGGER_H diff --git a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger_implementation.h b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger_implementation.h index fe6d6e4efdbe04d53a8ab2e4a818e563e90c53fe..0c6a147f1e8b4b4fa884e4a4da007f29e8b1976a 100644 --- a/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger_implementation.h +++ b/OpenPass_Source_Code/openPASS/CoreModules_PCM/Observation_ScopeLogger/observation_scopeLogger_implementation.h @@ -18,7 +18,6 @@ #include <QFile> #include <QTextStream> #include "agentInterface.h" -#include "observationInterface.h" #include "componentPorts.h" #include "XoscWriter/openScenarioWriter.h" diff --git a/OpenPass_Source_Code/openPASS/Interfaces/agentInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/agentInterface.h index 3781fafc5d9d51ecbd14635667fa9779958c2650..51d795c9fc8c5cc6806aef51119ae6fa07794e58 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/agentInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/agentInterface.h @@ -212,20 +212,6 @@ public: //----------------------------------------------------------------------------- virtual void SetYaw(double value) = 0; - //----------------------------------------------------------------------------- - //! Sets the total traveled distance of agent - //! - //! @param[in] distanceTraveled total traveled distance - //----------------------------------------------------------------------------- - virtual void SetDistanceTraveled(double distanceTraveled) = 0; - - //----------------------------------------------------------------------------- - //! Returns the total traveled distance of agent - //! - //! @return total traveled distance - //----------------------------------------------------------------------------- - virtual double GetDistanceTraveled() const = 0; - //----------------------------------------------------------------------------- //! Sets gear of vehicle //! diff --git a/OpenPass_Source_Code/openPASS/Interfaces/callbackInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/callbackInterface.h index 7edb5859f4d182b21cc425cf2ec7d9bda036ab71..7d5ebc00d2cfcf63c7ac51741f81b92f768c488f 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/callbackInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/callbackInterface.h @@ -14,14 +14,13 @@ //! interact with the framework. //----------------------------------------------------------------------------- -#ifndef CALLBACKINTERFACE_H -#define CALLBACKINTERFACE_H +#pragma once #include <string> //----------------------------------------------------------------------------- //! The following macro should only be called within classes providing a Log() member function -//! (e.g. classes derived from ModelInterface, ObservationInterface SpawnPointInterface). +//! (e.g. classes derived from ModelInterface SpawnPointInterface). //----------------------------------------------------------------------------- #define LOG(level, message) Log(level, __FILE__, __LINE__, message) #define LOGERROR(message) Log(CbkLogLevel::Error, __FILE__, __LINE__, message) @@ -65,5 +64,3 @@ public: int line, const std::string &message) const = 0; }; - -#endif // CALLBACKINTERFACE_H diff --git a/OpenPass_Source_Code/openPASS/Interfaces/componentInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/componentInterface.h index 5824f0eb88c580e71295629826a635a7de16fee3..8fb4f05793f8a3602a8274ab688c042996057e46 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/componentInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/componentInterface.h @@ -18,7 +18,10 @@ #pragma once #include "Interfaces/modelInterface.h" -#include "Interfaces/observationInterface.h" + +class PublisherInterface; + +class PublisherInterface; namespace SimulationSlave { diff --git a/OpenPass_Source_Code/openPASS/Interfaces/dataStoreInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/dataStoreInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..6161d200dca93f814674a9b33303bdb1490833d4 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/Interfaces/dataStoreInterface.h @@ -0,0 +1,413 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#pragma once + +#include <memory> +#include <optional> +#include <string> +#include <unordered_map> +#include <variant> +#include <vector> + +#include "Common/globalDefinitions.h" +#include "Common/observationTypes.h" +#include "Common/openPassTypes.h" +#include "Common/runtimeInformation.h" +#include "Interfaces/callbackInterface.h" + +namespace openpass::datastore { + +using Key = openpass::type::FlatParameterKey; +using Value = openpass::type::FlatParameterValue; +using Parameter = openpass::type::FlatParameter; + +static const std::string WILDCARD = "*"; //!< Wildcard to match any token inside a DataStore key string. Length of 1 is mandatory. +static const std::string SEPARATOR = "/"; //!< Separator for hierarchical DataStore key strings. Length of 1 is mandatory. + +/*! + * \brief Contains the triggering entities of an acyclic + * + * Might be enhanced in the future to hold additional information about the affected entities + */ +struct TriggeringEntities +{ + type::EntityIds entities; +}; + +/*! + * \brief Contains the affected entities of an acyclic + * + * Might be enhanced in the future to hold additional information about the affected entities + */ +struct AffectedEntities +{ + type::EntityIds entities; +}; + +/*! + * \brief Representation of an component event + */ +class ComponentEvent +{ +public: + ComponentEvent(openpass::type::FlatParameter parameter) : + parameter{std::move(parameter)} + { + } + +public: + openpass::type::FlatParameter parameter; //!< Generic parameter set associated with this event +}; + +/*! + * \brief Represents an acyclic occurence, like an event + */ +class Acyclic +{ +public: + Acyclic() = default; + Acyclic(std::string name, TriggeringEntities triggeringEntities, AffectedEntities affectedEntities, Parameter parameter) : + name{std::move(name)}, + triggeringEntities{std::move(triggeringEntities)}, + affectedEntities{std::move(affectedEntities)}, + parameter{std::move(parameter)} + { + } + + Acyclic(std::string name, openpass::type::EntityId entity, openpass::type::FlatParameter parameter) : + name{std::move(name)}, + parameter{std::move(parameter)} + { + triggeringEntities.entities.push_back(entity); + } + + bool operator==(const Acyclic& other) const + { + return name == other.name && + triggeringEntities.entities == other.triggeringEntities.entities && + affectedEntities.entities == other.affectedEntities.entities && + parameter == other.parameter; + } + + std::string name; //!< Name (or identifier) of this occurence + TriggeringEntities triggeringEntities; //!< List of entities causing this occurence + AffectedEntities affectedEntities; //!< List of entities affected by this occurence + Parameter parameter; //!< Generic parameter set associated with this occurence +}; + +/*! + * \brief Representation of an entry in the DataStore acyclics + */ +struct AcyclicRow +{ + AcyclicRow(openpass::type::Timestamp ts, openpass::type::EntityId id, Key k, Acyclic data) : + timestamp{ts}, + entityId{id}, + key{k}, + data{data} + { + } + + bool operator==(const AcyclicRow &other) const + { + return timestamp == other.timestamp && + entityId == other.entityId && + key == other.key && + data == other.data; + } + + openpass::type::Timestamp timestamp; //!< Simulation time timestamp [ms] + openpass::type::EntityId entityId; //!< Id of the entity (agent or object) + Key key; //!< Key (topic) associated with the data + Acyclic data; //!< Acyclic data container +}; + +/*! + * \brief Representation of an entry in the DataStore cyclics + */ +struct CyclicRow +{ + CyclicRow(openpass::type::Timestamp ts, openpass::type::EntityId id, Key k, Value v) : + timestamp{ts}, + entityId{id}, + key{k}, + value{v} + { + } + + bool operator==(const CyclicRow &other) const + { + return timestamp == other.timestamp && + entityId == other.entityId && + key == other.key && + value == other.value; + } + + openpass::type::Timestamp timestamp; //!< Simulation time timestamp [ms] + openpass::type::EntityId entityId; //!< Id of the entity (agent or object) + Key key; //!< Key (topic) associated with the data + Value value; //!< Data value +}; + +using Keys = std::vector<Key>; //!< List of keys used by the DataStore +using Values = std::vector<Value>; //!< List of values used by the DataStore +using CyclicRows = std::vector<CyclicRow>; //!< List of data rows used by the DataStore + +using CyclicRowRefs = std::vector<std::reference_wrapper<const CyclicRow>>; //!< List of references to rows inside the DataStore +using AcyclicRowRefs = std::vector<std::reference_wrapper<const AcyclicRow>>; //!< List of references to acyclic rows inside the DataStore + +/*! + * \brief A set of cyclic data elements representing a DataStore query result + * + * Basic forward iterator properties are provided for convenient result iteration. + * + * \code{.cpp} + * const auto cyclicResult = dataStore->GetCyclic(std::nullopt, std::nullopt, "*"); + * + * for (const CyclicRow& row : *cyclicResult) + * { + * ... + * } + * \endcode + * + */ +class CyclicResultInterface +{ +public: + virtual ~CyclicResultInterface() = default; + + virtual size_t size() const = 0; + virtual const CyclicRow& at(const size_t) const = 0; + virtual CyclicRowRefs::const_iterator begin() const = 0; + virtual CyclicRowRefs::const_iterator end() const = 0; +}; + +/*! + * \brief A set of acyclic data elements representing a DataStore query result + * + * Basic forward iterator properties are provided for convenient result iteration. + * + * \code{.cpp} + * const auto acyclicResult = dataStore->GetAcyclic(std::nullopt, std::nullopt, "*"); + * + * for (const AcyclicRow& row : *acyclicResult) + * { + * ... + * } + * \endcode + * + */ +class AcyclicResultInterface +{ +public: + virtual ~AcyclicResultInterface() = default; + + virtual size_t size() const = 0; + virtual const AcyclicRow& at(const size_t) const = 0; + virtual AcyclicRowRefs::const_iterator begin() const = 0; + virtual AcyclicRowRefs::const_iterator end() const = 0; +}; +} // namespace openpass::datastore + +using namespace openpass::datastore; + +/*! + * \brief The DataStoreReadInterface provides read-only access to an underlying DataStore implementation + * + * Topics (see Get* methods) for cyclics, acyclics and statics are independent of each other. + */ +class DataStoreReadInterface +{ +public: + DataStoreReadInterface() = default; + DataStoreReadInterface(const DataStoreReadInterface &) = delete; + DataStoreReadInterface(DataStoreReadInterface &&) = delete; + DataStoreReadInterface &operator=(const DataStoreReadInterface &) = delete; + DataStoreReadInterface &operator=(DataStoreReadInterface &&) = delete; + virtual ~DataStoreReadInterface() = default; + + static constexpr bool NO_DESCEND = false; + + /*! + * \brief Retrieves stored cyclic values from the data store + * + * \param[in] time Timestamp of interest + * \param[in] entityId Entity's id + * \param[in] key Unique topic identification + */ + virtual std::unique_ptr<CyclicResultInterface> GetCyclic(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key &key) const = 0; + + /*! + * \brief Retrieves stored acyclic values from the data store + * + * \param[in] time Timestamp of interest + * \param[in] entityId Entity's id + * \param[in] key Unique topic identification + * + * \note Current implementation ignores time and entityId + */ + virtual std::unique_ptr<AcyclicResultInterface> GetAcyclic(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key &key) const = 0; + + /*! + * \brief Retrieves stored static values from the data store + * + * \param[in] key Unique topic identification + */ + virtual Values GetStatic(const Key &key) const = 0; + + /*! + * \brief Retrieves keys at a specific node in the DataStore hierarchy. + * + * The key parameter has to be prefixed with "Cyclics/", "Acyclics/" or "Statics/" to + * get access to the different types of stored elements. + * + * The following example will retrieve the list of agent ids participating in the current simulation run: + * \code{.cpp} + * const auto agentIds = dataStore.GetKeys("Statics/Agents"); + * \endcode + * + * The following example will retrieve a list of instantiated sensors for agent 3: + * \code{.cpp} + * const std::string keyPrefix = "Agents/3/Vehicle/Sensors"; + * \endcode + * + * \param[in] key Unique topic identification, including prefix + */ + virtual Keys GetKeys(const Key &key) const = 0; + + /*! + * \brief Provides callback to LOG() macro + * + * \param[in] logLevel Importance of log + * \param[in] file Name of file where log is called + * \param[in] line Line within file where log is called + * \param[in] message Message to log + */ + virtual void Log(CbkLogLevel logLevel, const char *file, int line, const std::string &message) const = 0; +}; + +/*! + * \brief The DataStoreWriteInterface provides write-only access to an underlying DataStore implementation + * + * Topics (see Put* methods) for cyclics, acyclics and statics are independent of each other. + */ +class DataStoreWriteInterface +{ +public: + DataStoreWriteInterface() = default; + DataStoreWriteInterface(const DataStoreWriteInterface &) = delete; + DataStoreWriteInterface(DataStoreWriteInterface &&) = delete; + DataStoreWriteInterface &operator=(const DataStoreWriteInterface &) = delete; + DataStoreWriteInterface &operator=(DataStoreWriteInterface &&) = delete; + virtual ~DataStoreWriteInterface() = default; + + /*! + * \brief Writes cyclic information into the data store + * + * \param[in] time Timestamp associated with the provided key/value [ms] + * \param[in] entityId Id of the associated agent or object + * \param[in] key Unique topic identification + * \param[in] value Value to be written + */ + virtual void PutCyclic(const openpass::type::Timestamp time, const openpass::type::EntityId entityId, const Key &key, const Value &value) = 0; + + /*! + * \brief Writes acyclic information into the data store + * + * \param[in] time Timestamp associated with the provided key/value [ms] + * \param[in] entityId Id of the associated agent + * \param[in] key Unique topic identification + * \param[in] acyclic The acyclic element to be written + */ + virtual void PutAcyclic(const openpass::type::Timestamp time, const openpass::type::EntityId entityId, const Key &key, const openpass::datastore::Acyclic &acyclic) = 0; + + /*! + * \brief Writes static information into the data store + * + * \param[in] key Unique topic identification + * \param[in] value Value to be written + * \param[in] persist Make value persistent (not affected by Clear()) + */ + virtual void PutStatic(const Key &key, const Value &value, bool persist = false) = 0; + + /*! + * \brief Clears the datastore contents, except persistant static data + */ + virtual void Clear() = 0; + + /*! + * \brief Provides callback to LOG() macro + * + * \param[in] logLevel Importance of log + * \param[in] file Name of file where log is called + * \param[in] line Line within file where log is called + * \param[in] message Message to log + */ + virtual void Log(CbkLogLevel logLevel, const char *file, int line, const std::string &message) const = 0; +}; + +/*! + * \brief The DataStoreInterface provides read/write access to an underlying DataStore implementation + * + * This interface combines DataStoreReadInterface and DataStoreWriteInterface and adds some additional + * methods required for instantiation by the framework. + */ +class DataStoreInterface : public DataStoreReadInterface, public DataStoreWriteInterface +{ +public: + DataStoreInterface() = default; + DataStoreInterface(const openpass::common::RuntimeInformation *runtimeInformation, const CallbackInterface *callbacks) : + runtimeInformation(runtimeInformation), + callbacks(callbacks) + { + } + + DataStoreInterface(const DataStoreInterface &) = delete; + DataStoreInterface(DataStoreInterface &&) = delete; + DataStoreInterface &operator=(const DataStoreInterface &) = delete; + DataStoreInterface &operator=(DataStoreInterface &&) = delete; + virtual ~DataStoreInterface() override = default; + + /*! + * \brief Instantiates the data store + * + * \return true if instantiation was successful, false otherwise + */ + virtual bool Instantiate() + { + return false; + } + + /*! + * \brief Determines the instantiation status + * + * \return true if data store is instantiated, false otherwise + */ + virtual bool isInstantiated() const + { + return false; + } + + void Log(CbkLogLevel logLevel, const char *file, int line, const std::string &message) const override + { + if (callbacks) + { + callbacks->Log(logLevel, + file, + line, + message); + } + } + +protected: + const openpass::common::RuntimeInformation *runtimeInformation; //!< References the configuration parameters + const CallbackInterface *callbacks; //!< References the callback functions of the framework +}; diff --git a/OpenPass_Source_Code/openPASS/Interfaces/eventInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/eventInterface.h index 9469502274caff1af17acaef935e9cc85a058921..921c6d4ba17e2953dddcdd8c5193dc197b73ce30 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/eventInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/eventInterface.h @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2017, 2018, 2019 in-tech GmbH +* Copyright (c) 2017, 2018, 2019, 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -10,15 +10,15 @@ //----------------------------------------------------------------------------- /** \file eventInterface.h -* \brief This file provides the interface for the events -*/ + * \brief This file provides the interface for the events + */ //----------------------------------------------------------------------------- - #pragma once -#include<vector> +#include <vector> #include "Common/eventTypes.h" +#include "Common/openPassTypes.h" struct EventParameter { @@ -38,28 +38,83 @@ class EventInterface { public: EventInterface() = default; - EventInterface(const EventInterface&) = delete; - EventInterface(EventInterface&&) = delete; - EventInterface& operator=(const EventInterface&) = delete; - EventInterface& operator=(EventInterface&&) = delete; + EventInterface(const EventInterface &) = delete; + EventInterface(EventInterface &&) = delete; + EventInterface &operator=(const EventInterface &) = delete; + EventInterface &operator=(EventInterface &&) = delete; virtual ~EventInterface() = default; + /*! + * \brief Sets the Id of the event. + * \param[in] Id of the event. + */ virtual void SetId(const int eventId) = 0; + /*! + * \brief Returns the Id of the event. + * \return Id. + */ virtual int GetId() const = 0; + /*! + * \brief Returns the time of the event. + * \return Time in milliseconds. + */ virtual int GetEventTime() const = 0; - virtual EventDefinitions::EventCategory GetCategory() const = 0; + /*! + * \brief Returns the category of the event. + * \return EventCategory. + */ + virtual EventDefinitions::EventCategory GetCategory() const = 0; + /*! + * \brief Sets the Id of the event which triggered this event. + * \param[in] Event Id. + */ virtual void SetTriggeringEventId(const int triggeringEventId) = 0; + /*! + * \brief Returns the Id of the event which triggered this event. + * \return Event Id. + */ virtual int GetTriggeringEventId() const = 0; + /*! + * \brief Returns the name of the event. + * \return Name of the event as string. + */ virtual std::string GetName() const = 0; + /*! + * \brief Returns the name of the source component. + * \return Name of source component as string. + */ virtual std::string GetSource() const = 0; - virtual EventParameters GetParametersAsString() = 0; + /*! + * \brief GetTriggeringAgents + * \return List of triggering agents (might me empty) + */ + virtual const std::vector<int> GetTriggeringAgents() const = 0; + + /*! + * \brief GetActingAgents + * \return List of acting agents (might me empty) + */ + virtual const std::vector<int> GetActingAgents() const = 0; + + /*! + * \brief Returns all parameters of the event as string list. + * \details Returns the agentId as string list. + * \return List of string pairs of the event parameters. + */ + [[deprecated("Will be replaced by functionality of openpass::events::Parameter")]] virtual EventParameters GetParametersAsString() = 0; + + /*! + * \brief Returns all parameter in their raw form + * \see openpass::events::Parameter + * \return Parameter + */ + [[deprecated("will be replaced by specializations of the type")]] virtual const openpass::type::FlatParameter &GetParameter() const = 0; }; - diff --git a/OpenPass_Source_Code/openPASS/Interfaces/eventNetworkInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/eventNetworkInterface.h index 59692a26aae2720366dfebb60b68f578fd758418..0e96e96f7b904e776cac96dc7c5c361d22372d9e 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/eventNetworkInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/eventNetworkInterface.h @@ -18,14 +18,12 @@ #include "Interfaces/agentInterface.h" #include "Interfaces/eventInterface.h" -#include "Interfaces/observationInterface.h" #include "Interfaces/runResultInterface.h" using Events = std::map<EventDefinitions::EventCategory, std::list<std::shared_ptr<EventInterface>>>; using EventContainer = std::list<std::shared_ptr<EventInterface>>; -namespace SimulationSlave -{ +namespace SimulationSlave { //----------------------------------------------------------------------------- /** \brief This class provides the interface for the EventNetwork diff --git a/OpenPass_Source_Code/openPASS/Interfaces/frameworkModuleContainerInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/frameworkModuleContainerInterface.h index b4803f9a577d7b9b2d41322a35e705db54a6092d..c9c541b30c1814d62d9ffe8b47129f1e37d89e86 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/frameworkModuleContainerInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/frameworkModuleContainerInterface.h @@ -10,9 +10,11 @@ #pragma once +// TODO rb: replace by forward declarations #include "Interfaces/stochasticsInterface.h" class AgentBlueprintProviderInterface; +class DataStoreInterface; class WorldInterface; namespace SimulationSlave { @@ -29,6 +31,13 @@ class FrameworkModuleContainerInterface public: virtual ~FrameworkModuleContainerInterface() = default; + /*! + * \brief Returns a pointer to the agentBlueprintProvider + * + * @return agentBlueprintProvider pointer + */ + virtual AgentBlueprintProviderInterface* GetAgentBlueprintProvider() = 0; + /*! * \brief Returns a pointer to the AgentFactory * @@ -36,6 +45,13 @@ public: */ virtual AgentFactoryInterface* GetAgentFactory() = 0; + /*! + * \brief Returns a pointer to the data store + * + * @return data store pointer + */ + virtual DataStoreInterface* GetDataStore() = 0; + /*! * \brief Returns a pointer to the EventDetectorNetwork * @@ -84,14 +100,6 @@ public: * @return World pointer */ virtual WorldInterface* GetWorld() = 0; - - - /*! - * \brief Returns a pointer to the agentBlueprintProvider - * - * @return agentBlueprintProvider pointer - */ - virtual AgentBlueprintProviderInterface* GetAgentBlueprintProvider() = 0; }; } //namespace SimulationSlave diff --git a/OpenPass_Source_Code/openPASS/Interfaces/modelInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/modelInterface.h index 76455433d44c7572170e785799d85cd6fccb7451..a50b4d879d5ee63c89cd1d39cc55d2598851846a 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/modelInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/modelInterface.h @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2017, 2018, 2019 in-tech GmbH +* Copyright (c) 2017, 2018, 2019, 2020 in-tech GmbH * 2016, 2017, 2018 ITK Engineering GmbH * * This program and the accompanying materials are made @@ -32,15 +32,16 @@ #include "Interfaces/agentInterface.h" #include "Interfaces/callbackInterface.h" #include "Interfaces/signalInterface.h" +#include "Interfaces/publisherInterface.h" +#include "Interfaces/observationInterface.h" -class ObservationInterface; class ParameterInterface; class StochasticsInterface; class WorldInterface; namespace SimulationSlave { class EventNetworkInterface; -}; +} //----------------------------------------------------------------------------- //! Provides functionality to print information of signals @@ -201,14 +202,14 @@ public: int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks) : ModelInterface(isInit, priority, offsetTime, responseTime, cycleTime), callbacks(callbacks), componentName(componentName), stochastics(stochastics), parameters(parameters), - observations(observations) + publisher(publisher) {} RestrictedModelInterface(const RestrictedModelInterface&) = delete; RestrictedModelInterface(RestrictedModelInterface&&) = delete; @@ -248,14 +249,13 @@ protected: } //----------------------------------------------------------------------------- - //! Retrieves the references to the observation modules used to track and - //! observe information + //! Retrieves the reference to the publishing module for data recording //! - //! @return Mapping of observation modules. + //! @return Publisher //----------------------------------------------------------------------------- - const std::map<int, ObservationInterface*> *GetObservations() const + PublisherInterface* GetPublisher() { - return observations; + return publisher; } //----------------------------------------------------------------------------- @@ -287,7 +287,7 @@ private: std::string componentName; //!< Name of this component StochasticsInterface *stochastics; //!< Reference to the stochastics functionality of the framework const ParameterInterface *parameters; //!< Reference to the configuration parameters - const std::map<int, ObservationInterface*> *observations; //!< Mapping of observation modules + PublisherInterface * const publisher; //!< Reference to the publisher module }; //----------------------------------------------------------------------------- @@ -321,7 +321,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : RestrictedModelInterface(componentName, @@ -332,7 +332,7 @@ public: cycleTime, stochastics, parameters, - observations, + publisher, callbacks), agent(agent), world(world) @@ -405,7 +405,7 @@ public: int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : RestrictedModelInterface(componentName, @@ -416,7 +416,7 @@ public: cycleTime, stochastics, parameters, - observations, + publisher, callbacks), agent(agent) {} @@ -583,7 +583,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent, SimulationSlave::EventNetworkInterface * const eventNetwork): @@ -596,7 +596,7 @@ public: stochastics, world, parameters, - observations, + publisher, callbacks, agent), eventNetwork(eventNetwork) diff --git a/OpenPass_Source_Code/openPASS/Interfaces/observationInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/observationInterface.h index e06d49390d5f123b32701e81a23d3e9533324362..58b6b245805648bd6d10033ef2bac22a4d43f15c 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/observationInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/observationInterface.h @@ -31,6 +31,7 @@ #include "Common/observationTypes.h" class CallbackInterface; +class DataStoreReadInterface; class ParameterInterface; class StochasticsInterface; class WorldInterface; @@ -43,7 +44,8 @@ public: ObservationInterface(StochasticsInterface* stochastics, WorldInterface* world, const ParameterInterface* parameters, - const CallbackInterface* callbacks) : + const CallbackInterface* callbacks, + [[maybe_unused]] DataStoreReadInterface* dataStore) : stochastics(stochastics), world(world), parameters(parameters), @@ -108,24 +110,6 @@ public: //----------------------------------------------------------------------------- virtual const std::string SlaveResultFile() = 0; - //----------------------------------------------------------------------------- - //! \brief Inserts directly pushed information into the observation - //! - //! \param time insert time stamp - //! \param agentId corresponding agent - //! \param group logging group - //! \param key topic - //! \param value value - //----------------------------------------------------------------------------- - virtual void Insert(int time, int agentId, LoggingGroup group, const std::string& key, const std::string& value) = 0; - - //----------------------------------------------------------------------------- - /*! - * \brief Insert the event into the EventNetwork - */ - //----------------------------------------------------------------------------- - virtual void InsertEvent(std::shared_ptr<EventInterface> event) = 0; - protected: //----------------------------------------------------------------------------- //! Retrieves the stochastics functionality diff --git a/OpenPass_Source_Code/openPASS/Interfaces/observationNetworkInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/observationNetworkInterface.h index 55697f392b78da0484c613c84a1a32c6f31b5e59..e49d4ed41dceeadb5610200ad8ad098836eb6e50 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/observationNetworkInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/observationNetworkInterface.h @@ -17,8 +17,8 @@ #pragma once -#include "Interfaces/observationInterface.h" #include "Interfaces/eventNetworkInterface.h" +#include "Interfaces/stochasticsInterface.h" #include "Common/observationLibraryDefinitions.h" namespace SimulationSlave { @@ -59,7 +59,8 @@ public: StochasticsInterface* stochastics, WorldInterface* world, EventNetworkInterface* eventNetwork, - const std::string& sceneryPath) = 0; + const std::string& sceneryPath, + DataStoreReadInterface* dataStore) = 0; //----------------------------------------------------------------------------- //! Returns the observation module mapping. diff --git a/OpenPass_Source_Code/openPASS/Interfaces/profilesInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/profilesInterface.h index aa3784044a4cf1ad74b4847e830c8d59d9a53d65..6129e4aa7765fa38cc3670c252b6b2df9d3f6410 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/profilesInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/profilesInterface.h @@ -14,6 +14,7 @@ #include <memory> #include <unordered_map> +#include "Common/parameter.h" #include "Common/sensorDefinitions.h" using StringProbabilities = std::vector<std::pair<std::string, double>>; diff --git a/OpenPass_Source_Code/openPASS/Interfaces/publisherInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/publisherInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..982b66d1e49f672ad8dd22f1fd11213820d96e08 --- /dev/null +++ b/OpenPass_Source_Code/openPASS/Interfaces/publisherInterface.h @@ -0,0 +1,71 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +/*! + * + * \file writeInterface.h + * \brief This file contains the interface of the observation modules to + * interact with the framework + */ + +#pragma once + +#include <iostream> +#include <sstream> +#include <string> +#include <variant> +#include <vector> + +#include "Common/eventTypes.h" +#include "Interfaces/dataStoreInterface.h" + +//! Interface which has to be provided by observation modules +class PublisherInterface +{ +public: + PublisherInterface(DataStoreWriteInterface *const dataStore) : + dataStore(dataStore) + { + } + + PublisherInterface(const PublisherInterface &) = delete; + PublisherInterface &operator=(const PublisherInterface &) = delete; + + PublisherInterface(PublisherInterface &&) = default; + PublisherInterface &operator=(PublisherInterface &&) = default; + + virtual ~PublisherInterface() = default; + + /*! + * \brief Writes information into a data store backend + * + * \param key[in] Unique topic identification + * \param value[in] Value to be written + */ + virtual void Publish(const openpass::datastore::Key &key, const openpass::datastore::Value &value) + { + } + + /*! + * \brief Writes acyclic information into a data store backend + * + * \param value[in] The acyclic event + */ + virtual void Publish(const openpass::narrator::EventBase &event) + { + } + + virtual void Publish(const openpass::datastore::Key &key, const openpass::datastore::ComponentEvent &event) + { + } + +protected: + DataStoreWriteInterface *const dataStore; //!< References the datastore backend +}; diff --git a/OpenPass_Source_Code/openPASS/Interfaces/scenarioActionInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/scenarioActionInterface.h index 84eb82c7e26a7a4c0bf45caf9a00b6369581733f..b4827dbe8a990a949f53c70c5085cf05d11c7003 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/scenarioActionInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/scenarioActionInterface.h @@ -17,12 +17,6 @@ class ScenarioActionInterface { public: ScenarioActionInterface() = default; - ScenarioActionInterface(const ScenarioActionInterface&) = delete; - ScenarioActionInterface(ScenarioActionInterface&&) = delete; - ScenarioActionInterface& operator=(const ScenarioActionInterface&) = delete; - ScenarioActionInterface& operator=(ScenarioActionInterface&&) = delete; virtual ~ScenarioActionInterface() = default; - virtual const std::string& GetEventName() const = 0; -private: }; diff --git a/OpenPass_Source_Code/openPASS/Interfaces/signalInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/signalInterface.h index f4a0f88887dcc8ea729e7c965172d0633302fc88..06e1cf6862acd16599beec723c53c40ff80f35c9 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/signalInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/signalInterface.h @@ -22,9 +22,29 @@ enum class ComponentState Acting }; -const std::map<std::string, ComponentState> ComponentStateMapping = { { "Acting", ComponentState::Acting }, - { "Armed", ComponentState::Armed }, - { "Disabled", ComponentState::Disabled } }; +namespace openpass::utils { + +static constexpr std::array<const char *, 4> ComponentStateMapping{ + "Undefined", + "Disabled", + "Armed", + "Acting"}; + +constexpr const char *to_cstr(ComponentState state) +{ + return ComponentStateMapping[static_cast<size_t>(state)]; +} + +inline std::string to_string(ComponentState state) noexcept +{ + return std::string(to_cstr(state)); +} + +} // namespace openpass::utils + +const std::map<std::string, ComponentState> ComponentStateMapping = {{"Acting", ComponentState::Acting}, + {"Armed", ComponentState::Armed}, + {"Disabled", ComponentState::Disabled}}; enum class ComponentWarningLevel { @@ -32,8 +52,8 @@ enum class ComponentWarningLevel WARNING }; -const std::map<ComponentWarningLevel, std::string> ComponentWarningLevelMapping = { { ComponentWarningLevel::INFO , "Info" }, - { ComponentWarningLevel::WARNING, "Warning" } }; +const std::map<ComponentWarningLevel, std::string> ComponentWarningLevelMapping = {{ComponentWarningLevel::INFO, "Info"}, + {ComponentWarningLevel::WARNING, "Warning"}}; enum class ComponentWarningType { @@ -42,9 +62,9 @@ enum class ComponentWarningType HAPTIC }; -const std::map<ComponentWarningType, std::string> ComponentWarningTypeMapping = { { ComponentWarningType::OPTIC , "Optic" }, - { ComponentWarningType::ACOUSTIC, "Acoustic" }, - { ComponentWarningType::HAPTIC , "Haptic" } }; +const std::map<ComponentWarningType, std::string> ComponentWarningTypeMapping = {{ComponentWarningType::OPTIC, "Optic"}, + {ComponentWarningType::ACOUSTIC, "Acoustic"}, + {ComponentWarningType::HAPTIC, "Haptic"}}; enum class ComponentWarningIntensity { @@ -53,9 +73,9 @@ enum class ComponentWarningIntensity HIGH }; -const std::map<ComponentWarningIntensity, std::string> ComponentWarningIntensityMapping = { { ComponentWarningIntensity::LOW , "Low" }, - { ComponentWarningIntensity::MEDIUM, "Medium" }, - { ComponentWarningIntensity::HIGH , "High" } }; +const std::map<ComponentWarningIntensity, std::string> ComponentWarningIntensityMapping = {{ComponentWarningIntensity::LOW, "Low"}, + {ComponentWarningIntensity::MEDIUM, "Medium"}, + {ComponentWarningIntensity::HIGH, "High"}}; struct ComponentWarningInformation { @@ -95,11 +115,14 @@ class ComponentStateSignalInterface : public SignalInterface { public: ComponentStateSignalInterface() = default; - ComponentStateSignalInterface(ComponentState componentState):componentState{componentState}{} - ComponentStateSignalInterface(const ComponentStateSignalInterface&) = default; - ComponentStateSignalInterface(ComponentStateSignalInterface&&) = default; - ComponentStateSignalInterface& operator=(const ComponentStateSignalInterface&) = default; - ComponentStateSignalInterface& operator=(ComponentStateSignalInterface&&) = default; + ComponentStateSignalInterface(ComponentState componentState) : + componentState{componentState} + { + } + ComponentStateSignalInterface(const ComponentStateSignalInterface &) = default; + ComponentStateSignalInterface(ComponentStateSignalInterface &&) = default; + ComponentStateSignalInterface &operator=(const ComponentStateSignalInterface &) = default; + ComponentStateSignalInterface &operator=(ComponentStateSignalInterface &&) = default; virtual ~ComponentStateSignalInterface() = default; ComponentState componentState; diff --git a/OpenPass_Source_Code/openPASS/Interfaces/slaveConfigInterface.h b/OpenPass_Source_Code/openPASS/Interfaces/slaveConfigInterface.h index 1734a70dd5213b6073f901f4ed7b1e88c1d970ed..cf55c2678fe7815954760aa97d6fa9e8b4987d36 100644 --- a/OpenPass_Source_Code/openPASS/Interfaces/slaveConfigInterface.h +++ b/OpenPass_Source_Code/openPASS/Interfaces/slaveConfigInterface.h @@ -35,9 +35,7 @@ struct ExperimentConfig int experimentId; int numberOfInvocations; - bool logCyclicsToCsv; std::uint32_t randomSeed; - std::vector<std::string> loggingGroups; //!< Holds the names of enabled logging groups Libraries libraries; }; diff --git a/OpenPass_Source_Code/openPASS/OpenPass_OSI.pro b/OpenPass_Source_Code/openPASS/OpenPass_OSI.pro index aed699ce81f16398224a0757f6b5826d81d2477c..038baebce5339b3a31b63bf10ff61bd153f3539f 100644 --- a/OpenPass_Source_Code/openPASS/OpenPass_OSI.pro +++ b/OpenPass_Source_Code/openPASS/OpenPass_OSI.pro @@ -12,6 +12,7 @@ TEMPLATE = subdirs SUBDIRS = \ CoreFramework/OpenPassMaster \ CoreFramework/OpenPassSlave \ + CoreModules/BasicDataStore \ CoreModules/EventDetector \ CoreModules/Manipulator \ CoreModules/Observation_Log \ diff --git a/OpenPass_Source_Code/openPASS_Resource/OpenPass_OSI_UseCase/AEB/slaveConfig.xml b/OpenPass_Source_Code/openPASS_Resource/OpenPass_OSI_UseCase/AEB/slaveConfig.xml index 070d16c46c0fe6b5d758284f302e68756203dd4f..18460875f840723d8ae95694a493efa9c2cfceb0 100644 --- a/OpenPass_Source_Code/openPASS_Resource/OpenPass_OSI_UseCase/AEB/slaveConfig.xml +++ b/OpenPass_Source_Code/openPASS_Resource/OpenPass_OSI_UseCase/AEB/slaveConfig.xml @@ -1,27 +1,17 @@ -<slaveConfig SchemaVersion="0.7.0"> +<slaveConfig SchemaVersion="0.8.0"> <ProfilesCatalog>ProfilesCatalog.xml</ProfilesCatalog> - <ExperimentConfig> + <Experiment> <ExperimentID>0</ExperimentID> <NumberOfInvocations>1</NumberOfInvocations> <RandomSeed>0</RandomSeed> <Libraries> <WorldLibrary>World_OSI</WorldLibrary> - <ObservationLibrary>Observation_Log</ObservationLibrary> - <SpawnPointLibrary>SpawnPoint_OSI</SpawnPointLibrary> </Libraries> - <LoggingGroups> - <LoggingGroup>Trace</LoggingGroup> - <LoggingGroup>Visualization</LoggingGroup> - <LoggingGroup>RoadPosition</LoggingGroup> - <LoggingGroup>Sensor</LoggingGroup> - <LoggingGroup>Driver</LoggingGroup> - </LoggingGroups> - <LoggingCyclicsToCsv>false</LoggingCyclicsToCsv> - </ExperimentConfig> - <ScenarioConfig Name="Default Scenario"> + </Experiment> + <Scenario> <OpenScenarioFile>Scenario.xosc</OpenScenarioFile> - </ScenarioConfig> - <EnvironmentConfig Name="Default Environment"> + </Scenario> + <Environment> <TimeOfDays> <TimeOfDay Value="15" Probability="0.4"/> <TimeOfDay Value="18" Probability="0.6"/> @@ -37,24 +27,34 @@ <Weather Value="Rainy" Probability="0.5"/> <Weather Value="Snowy" Probability="0.5"/> </Weathers> - </EnvironmentConfig> - <SpawnPointsConfig> - <SpawnPoint> - <Library>SpawnPointScenario</Library> + </Environment> + <Observations> + <Observation> + <Library>Observation_Log</Library> + <Parameters> + <String Key="OutputFilename" Value="simulationOutput.xml"/> + <Bool Key="LoggingCyclicsToCsv" Value="false"/> + <StringVector Key="LoggingGroups" Value="Trace,Visualization,RoadPosition,Sensor,Driver"/> + </Parameters> + </Observation> + </Observations> + <Spawners> + <Spawner> + <Library>SpawnPointScenario_OSI</Library> <Type>PreRun</Type> <Priority>1</Priority> - </SpawnPoint> - <SpawnPoint> - <Library>SpawnPointPreRunCommon</Library> + </Spawner> + <Spawner> + <Library>SpawnPointPreRunCommon_OSI</Library> <Type>PreRun</Type> <Priority>0</Priority> <Profile>DefaultPreRunCommon</Profile> - </SpawnPoint> - <SpawnPoint> - <Library>SpawnPointRuntimeCommon</Library> + </Spawner> + <Spawner> + <Library>SpawnPointRuntimeCommon_OSI</Library> <Type>Runtime</Type> <Priority>0</Priority> <Profile>DefaultRuntimeCommon</Profile> - </SpawnPoint> - </SpawnPointsConfig> + </Spawner> + </Spawners> </slaveConfig> diff --git a/OpenPass_Source_Code/openPASS_Resource/OpenPass_OSI_UseCase/Static AgentProfiles/slaveConfig.xml b/OpenPass_Source_Code/openPASS_Resource/OpenPass_OSI_UseCase/Static AgentProfiles/slaveConfig.xml index 5ee2a38229c9365b4c972813e2ce40dd409c4020..2de6ae87c530bf1798fd95ba1dd33d0c900b7ae1 100644 --- a/OpenPass_Source_Code/openPASS_Resource/OpenPass_OSI_UseCase/Static AgentProfiles/slaveConfig.xml +++ b/OpenPass_Source_Code/openPASS_Resource/OpenPass_OSI_UseCase/Static AgentProfiles/slaveConfig.xml @@ -1,27 +1,17 @@ -<slaveConfig SchemaVersion="0.7.0"> +<slaveConfig SchemaVersion="0.8.0"> <ProfilesCatalog>ProfilesCatalog.xml</ProfilesCatalog> - <ExperimentConfig> - <ExperimentID>123</ExperimentID> + <Experiment> + <ExperimentID>0</ExperimentID> <NumberOfInvocations>1</NumberOfInvocations> <RandomSeed>532725206</RandomSeed> <Libraries> <WorldLibrary>World_OSI</WorldLibrary> - <ObservationLibrary>Observation_Log</ObservationLibrary> - <SpawnPointLibrary>SpawnPoint_OSI</SpawnPointLibrary> </Libraries> - <LoggingGroups> - <LoggingGroup>Trace</LoggingGroup> - <LoggingGroup>Visualization</LoggingGroup> - <LoggingGroup>RoadPosition</LoggingGroup> - <LoggingGroup>Sensor</LoggingGroup> - <LoggingGroup>Driver</LoggingGroup> - </LoggingGroups> - <LoggingCyclicsToCsv>false</LoggingCyclicsToCsv> - </ExperimentConfig> - <ScenarioConfig Name="Default Scenario"> + </Experiment> + <Scenario> <OpenScenarioFile>Scenario.xosc</OpenScenarioFile> - </ScenarioConfig> - <EnvironmentConfig Name="Default Environment"> + </Scenario> + <Environment> <TimeOfDays> <TimeOfDay Probability="0.4" Value="15"/> <TimeOfDay Probability="0.6" Value="18"/> @@ -37,24 +27,34 @@ <Weather Probability="0.5" Value="Rainy"/> <Weather Probability="0.5" Value="Snowy"/> </Weathers> - </EnvironmentConfig> - <SpawnPointsConfig> - <SpawnPoint> - <Library>SpawnPointScenario</Library> + </Environment> + <Observations> + <Observation> + <Library>Observation_Log</Library> + <Parameters> + <String Key="OutputFilename" Value="simulationOutput.xml"/> + <Bool Key="LoggingCyclicsToCsv" Value="false"/> + <StringVector Key="LoggingGroups" Value="Trace,Visualization,RoadPosition,Sensor,Driver"/> + </Parameters> + </Observation> + </Observations> + <Spawners> + <Spawner> + <Library>SpawnPointScenario_OSI</Library> <Type>PreRun</Type> <Priority>1</Priority> - </SpawnPoint> - <SpawnPoint> - <Library>SpawnPointPreRunCommon</Library> + </Spawner> + <Spawner> + <Library>SpawnPointPreRunCommon_OSI</Library> <Type>PreRun</Type> <Priority>0</Priority> <Profile>DefaultPreRunCommon</Profile> - </SpawnPoint> - <SpawnPoint> - <Library>SpawnPointRuntimeCommon</Library> + </Spawner> + <Spawner> + <Library>SpawnPointRuntimeCommon_OSI</Library> <Type>Runtime</Type> <Priority>0</Priority> <Profile>DefaultRuntimeCommon</Profile> - </SpawnPoint> - </SpawnPointsConfig> + </Spawner> + </Spawners> </slaveConfig> diff --git a/OpenPass_Test/fakes/gmock/fakeAgent.h b/OpenPass_Test/fakes/gmock/fakeAgent.h index 10ad2eaa001c426fb582291ad7769f6d10737d15..86a90c12f211014781df5ae0d2d06a915e13715b 100644 --- a/OpenPass_Test/fakes/gmock/fakeAgent.h +++ b/OpenPass_Test/fakes/gmock/fakeAgent.h @@ -45,8 +45,6 @@ class FakeAgent : public FakeWorldObject, public AgentInterface MOCK_METHOD1(SetVelocity, void(double value)); MOCK_METHOD1(SetAcceleration, void(double value)); MOCK_METHOD1(SetYaw, void(double value)); - MOCK_METHOD1(SetDistanceTraveled, void(double distanceTraveled)); - MOCK_CONST_METHOD0(GetDistanceTraveled, double()); MOCK_METHOD1(SetGear, void(int gear)); MOCK_METHOD1(SetEngineSpeed, void(double engineSpeed)); MOCK_METHOD1(SetEffAccelPedal, void(double percent)); diff --git a/OpenPass_Test/fakes/gmock/fakeAgentDataPublisher.h b/OpenPass_Test/fakes/gmock/fakeAgentDataPublisher.h new file mode 100644 index 0000000000000000000000000000000000000000..a2106218c934af2b9161399c92d9522704f72bb6 --- /dev/null +++ b/OpenPass_Test/fakes/gmock/fakeAgentDataPublisher.h @@ -0,0 +1,20 @@ +/********************************************************************* + * Copyright (c) 2020 in-tech + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + **********************************************************************/ + +#pragma once + +#include "gmock/gmock.h" +#include "Interfaces/publisherInterface.h" + +class FakeAgentDataPublisher : public PublisherInterface +{ +public: + MOCK_METHOD2(Publish, void(const openpass::datastore::Key&, const openpass::datastore::Value&)); +}; diff --git a/OpenPass_Test/fakes/gmock/fakeComponent.h b/OpenPass_Test/fakes/gmock/fakeComponent.h index 5dfc5ed6c5020c82aac100292a6c4d19b88ecc90..0fcb54e451038e8d379a0b05f180f0422e7a1355 100644 --- a/OpenPass_Test/fakes/gmock/fakeComponent.h +++ b/OpenPass_Test/fakes/gmock/fakeComponent.h @@ -23,8 +23,7 @@ class FakeComponent : public ComponentInterface { std::map<int, Channel*>&()); MOCK_METHOD0(GetOutputLinks, std::map<int, Channel*>&()); - MOCK_CONST_METHOD0(GetObservations, - const std::map<int, ObservationInterface*>&()); + MOCK_CONST_METHOD0(GetObservations, const std::map<int, ObservationInterface*>& ()); MOCK_METHOD1(TriggerCycle, bool(int time)); MOCK_METHOD2(AcquireOutputData, diff --git a/OpenPass_Test/fakes/gmock/fakeDataStore.h b/OpenPass_Test/fakes/gmock/fakeDataStore.h new file mode 100644 index 0000000000000000000000000000000000000000..5e16ba0c78c9de891c6d4324f7788d54c554849c --- /dev/null +++ b/OpenPass_Test/fakes/gmock/fakeDataStore.h @@ -0,0 +1,28 @@ +/********************************************************************* + * Copyright (c) 2020 in-tech + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + **********************************************************************/ + +#pragma once + +#include "gmock/gmock.h" + +#include "Interfaces/dataStoreInterface.h" + +class FakeDataStore : public DataStoreInterface +{ +public: + MOCK_CONST_METHOD3(GetCyclic, std::unique_ptr<CyclicResultInterface>(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key& key)); + MOCK_CONST_METHOD3(GetAcyclic, std::unique_ptr<AcyclicResultInterface>(const std::optional<openpass::type::Timestamp> time, const std::optional<openpass::type::EntityId> entityId, const Key& key)); + MOCK_CONST_METHOD1(GetStatic, Values(const Key& key)); + MOCK_CONST_METHOD1(GetKeys, Keys(const Key& key)); + MOCK_METHOD4(PutCyclic, void(const openpass::type::Timestamp time, const openpass::type::EntityId entityId, const Key& key, const Value& value)); + MOCK_METHOD4(PutAcyclic, void(const openpass::type::Timestamp time, const openpass::type::EntityId entityId, const Key& key, const Acyclic& event)); + MOCK_METHOD3(PutStatic, void(const Key& key, const Value& value, bool persist)); + MOCK_METHOD0(Clear, void()); +}; diff --git a/OpenPass_Test/fakes/gmock/fakeEvent.h b/OpenPass_Test/fakes/gmock/fakeEvent.h index a9718e5cc51159b5b2bd06b4e1bc4c60e8786261..7e601f4780e4f1fa94f321bd82e93a35c478f98c 100644 --- a/OpenPass_Test/fakes/gmock/fakeEvent.h +++ b/OpenPass_Test/fakes/gmock/fakeEvent.h @@ -1,5 +1,5 @@ /********************************************************************* -* Copyright (c) 2018 - 2019 in-tech +* Copyright (c) 2018, 2019, 2020 in-tech * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -10,27 +10,22 @@ #pragma once -#include "gmock/gmock.h" #include "Interfaces/eventInterface.h" +#include "gmock/gmock.h" -class FakeEvent : public EventInterface { - public: - MOCK_METHOD1(SetId, - void(int)); - MOCK_CONST_METHOD0(GetId, - int()); - MOCK_CONST_METHOD0(GetEventTime, - int()); - MOCK_CONST_METHOD0(GetCategory, - EventDefinitions::EventCategory()); - MOCK_METHOD1(SetTriggeringEventId, - void(int)); - MOCK_CONST_METHOD0(GetTriggeringEventId, - int()); - MOCK_CONST_METHOD0(GetSource, - std::string()); - MOCK_CONST_METHOD0(GetName, - std::string()); - MOCK_METHOD0(GetParametersAsString, - EventParameters()); +class FakeEvent : public EventInterface +{ +public: + MOCK_METHOD1(SetId, void(int)); + MOCK_CONST_METHOD0(GetId, int()); + MOCK_CONST_METHOD0(GetEventTime, int()); + MOCK_CONST_METHOD0(GetCategory, EventDefinitions::EventCategory()); + MOCK_METHOD1(SetTriggeringEventId, void(int)); + MOCK_CONST_METHOD0(GetTriggeringEventId, int()); + MOCK_CONST_METHOD0(GetSource, std::string()); + MOCK_CONST_METHOD0(GetName, std::string()); + MOCK_CONST_METHOD0(GetTriggeringAgents, const std::vector<int>()); + MOCK_CONST_METHOD0(GetActingAgents, const std::vector<int>()); + MOCK_METHOD0(GetParametersAsString, EventParameters()); + MOCK_CONST_METHOD0(GetParameter, const openpass::type::FlatParameter&()); }; diff --git a/OpenPass_Test/fakes/gmock/fakeEventNetwork.h b/OpenPass_Test/fakes/gmock/fakeEventNetwork.h index 473da48c70d8f56a4c91f66f10fe5dfb481cb9f2..f67503f0d319ef6315cfa2ed53ed37b42a4854cd 100644 --- a/OpenPass_Test/fakes/gmock/fakeEventNetwork.h +++ b/OpenPass_Test/fakes/gmock/fakeEventNetwork.h @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2019 in-tech GmbH +* Copyright (c) 2019, 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -9,30 +9,20 @@ *******************************************************************************/ #pragma once -#include "gmock/gmock.h" #include "Interfaces/eventNetworkInterface.h" +#include "gmock/gmock.h" class FakeEventNetwork : public SimulationSlave::EventNetworkInterface { public: - MOCK_METHOD0(GetActiveEvents, - Events*()); - MOCK_METHOD0(GetArchivedEvents, - Events*()); - MOCK_METHOD1(GetActiveEventCategory, - EventContainer(const EventDefinitions::EventCategory)); - MOCK_METHOD1(RemoveOldEvents, - void(int)); - MOCK_METHOD1(InsertEvent, - void(std::shared_ptr<EventInterface>)); - MOCK_METHOD0(ClearActiveEvents, - void()); - MOCK_METHOD0(Clear, - void()); - MOCK_METHOD1(Respawn, - void(int)); - MOCK_METHOD1(AddCollision, - void(const int)); - MOCK_METHOD1(Initialize, - void(RunResultInterface*)); + MOCK_METHOD0(GetActiveEvents, Events *()); + MOCK_METHOD0(GetArchivedEvents, Events *()); + MOCK_METHOD1(GetActiveEventCategory, EventContainer(const EventDefinitions::EventCategory)); + MOCK_METHOD1(RemoveOldEvents, void(int)); + MOCK_METHOD1(InsertEvent, void(std::shared_ptr<EventInterface>)); + MOCK_METHOD0(ClearActiveEvents, void()); + MOCK_METHOD0(Clear, void()); + MOCK_METHOD1(Respawn, void(int)); + MOCK_METHOD1(AddCollision, void(const int)); + MOCK_METHOD1(Initialize, void(RunResultInterface *)); }; diff --git a/OpenPass_Test/fakes/gmock/fakeObservation.h b/OpenPass_Test/fakes/gmock/fakeObservation.h index 0fecda9705a34522859b1b890cf40edf263e3ed6..554557b82a4e585d8ab406ed85e9b3245ccfbef2 100644 --- a/OpenPass_Test/fakes/gmock/fakeObservation.h +++ b/OpenPass_Test/fakes/gmock/fakeObservation.h @@ -11,7 +11,6 @@ #pragma once #include "gmock/gmock.h" -#include "Interfaces/observationInterface.h" class FakeObservation : public ObservationInterface { diff --git a/OpenPass_Test/fakes/gmock/fakeObservationNetwork.h b/OpenPass_Test/fakes/gmock/fakeObservationNetwork.h index 8074e24bf15b8ec9aa014b838c569a8939b40959..5fcae4ec2f609627143baa5799c4b21c10243ca5 100644 --- a/OpenPass_Test/fakes/gmock/fakeObservationNetwork.h +++ b/OpenPass_Test/fakes/gmock/fakeObservationNetwork.h @@ -15,8 +15,8 @@ class FakeObservationNetwork : public SimulationSlave::ObservationNetworkInterface { public: - MOCK_METHOD5(Instantiate, - bool(const ObservationInstanceCollection&, StochasticsInterface*, WorldInterface*, EventNetworkInterface*, const std::string&)); + MOCK_METHOD6(Instantiate, + bool(const ObservationInstanceCollection&, StochasticsInterface*, WorldInterface*, EventNetworkInterface*, const std::string&, DataStoreReadInterface*)); MOCK_METHOD0(GetObservationModules, const std::map<int, ObservationModule*>&()); MOCK_METHOD0(InitAll, diff --git a/OpenPass_Test/fakes/gmock/fakePublisher.h b/OpenPass_Test/fakes/gmock/fakePublisher.h new file mode 100644 index 0000000000000000000000000000000000000000..8bc08c7294ee62be13f110d53c43fd06ab9b6203 --- /dev/null +++ b/OpenPass_Test/fakes/gmock/fakePublisher.h @@ -0,0 +1,31 @@ +/********************************************************************* + * Copyright (c) 2020 in-tech + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + **********************************************************************/ + +#pragma once + +#include "gmock/gmock.h" +#include "Interfaces/publisherInterface.h" + +#include "fakeDataStore.h" +using ::testing::NiceMock; + +class FakePublisher : public PublisherInterface +{ +public: + NiceMock<FakeDataStore> fakeDataStore; + FakePublisher() : PublisherInterface(&fakeDataStore) {} + + MOCK_METHOD2(Publish, + void(const openpass::datastore::Key &key, const openpass::datastore::Value &value)); + MOCK_METHOD1(Publish, + void(const openpass::narrator::EventBase &event)); + MOCK_METHOD2(Publish, + void(const openpass::datastore::Key &key, const openpass::datastore::ComponentEvent &event)); +}; diff --git a/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/OpenPassSlave_IntegrationTests.pro b/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/OpenPassSlave_IntegrationTests.pro index 86ededfe7680ec82687eac826725e9a7564f2915..63065dff97fcfbc044f67965975380a9aa93a937 100644 --- a/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/OpenPassSlave_IntegrationTests.pro +++ b/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/OpenPassSlave_IntegrationTests.pro @@ -91,6 +91,7 @@ INC_SLAVECONFIG = $$OPENPASS_SLAVE/importer/slaveConfig.h \ SRC_SLAVECONFIG = $$OPENPASS_SLAVE/importer/slaveConfig.cpp \ $$OPENPASS_SLAVE/importer/slaveConfigImporter.cpp \ + $$OPENPASS_SLAVE/importer/parameterImporter.cpp \ $$OPENPASS_SLAVE/framework/directories.cpp SRC_CORESHARE = $$CORE_SHARE/xmlParser.cpp \ diff --git a/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/Resources/ImporterTest/invalidSpawnPointSlaveConfig.xml b/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/Resources/ImporterTest/invalidSpawnPointSlaveConfig.xml index 5f62f9e30dbfdc2b642b0e8954e0140e29527eeb..8bd39d033de90053b7263ea075cf6048c5b161bd 100644 --- a/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/Resources/ImporterTest/invalidSpawnPointSlaveConfig.xml +++ b/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/Resources/ImporterTest/invalidSpawnPointSlaveConfig.xml @@ -1,52 +1,49 @@ <!-- Invalid Type for SpawnPoint --> -<Combination SchemaVersion="0.7.0" id="544"> - <ProfilesCatalog>ProfilesCatalog.xml</ProfilesCatalog> - <ExperimentConfig> - <ExperimentID>123</ExperimentID> - <NumberOfInvocations>1</NumberOfInvocations> - <RandomSeed>532725206</RandomSeed> - <Libraries> - <WorldLibrary>World_OSI</WorldLibrary> - <ObservationLibrary>Observation_Log</ObservationLibrary> - <SpawnPointLibrary>SpawnPoint_OSI</SpawnPointLibrary> - </Libraries> - <LoggingGroups> - <LoggingGroup>Trace</LoggingGroup> - <LoggingGroup>Visualization</LoggingGroup> - <LoggingGroup>RoadPosition</LoggingGroup> - <LoggingGroup>Sensor</LoggingGroup> - <LoggingGroup>Driver</LoggingGroup> - </LoggingGroups> - <LoggingCyclicsToCsv>false</LoggingCyclicsToCsv> - </ExperimentConfig> - - <SpawnPointsConfig> - <SpawnPoint> - <Library>SpawnPointScenery_OSI</Library> - <Type>ThisTypeDoesNotExist</Type> - <Priority>1</Priority> - </SpawnPoint> - </SpawnPointsConfig> - - <ScenarioConfig Name="Default Scenario"> - <OpenScenarioFile>Scenario.xosc</OpenScenarioFile> - </ScenarioConfig> - - <EnvironmentConfig Name="Default Environment"> - <TimeOfDays> - <TimeOfDay Probability="0.4" Value="15" /> - <TimeOfDay Probability="0.6" Value="18" /> - </TimeOfDays> - <VisibilityDistances> - <VisibilityDistance Probability="0.7" Value="300" /> - <VisibilityDistance Probability="0.3" Value="400" /> - </VisibilityDistances> - <Frictions> - <Friction Probability="1.0" Value="1.0" /> - </Frictions> - <Weathers> - <Weather Probability="0.5" Value="Rainy" /> - <Weather Probability="0.5" Value="Snowy" /> - </Weathers> - </EnvironmentConfig> -</Combination> +<slaveConfig SchemaVersion="0.8.0"> + <ProfilesCatalog>ProfilesCatalog.xml</ProfilesCatalog> + <Experiment> + <ExperimentID>0</ExperimentID> + <NumberOfInvocations>1</NumberOfInvocations> + <RandomSeed>0</RandomSeed> + <Libraries> + <WorldLibrary>World_OSI</WorldLibrary> + </Libraries> + </Experiment> + <Scenario> + <OpenScenarioFile>Scenario.xosc</OpenScenarioFile> + </Scenario> + <Environment> + <TimeOfDays> + <TimeOfDay Value="15" Probability="0.4"/> + <TimeOfDay Value="18" Probability="0.6"/> + </TimeOfDays> + <VisibilityDistances> + <VisibilityDistance Value="125" Probability="0.7"/> + <VisibilityDistance Value="250" Probability="0.3"/> + </VisibilityDistances> + <Frictions> + <Friction Value="1.0" Probability="1.0"/> + </Frictions> + <Weathers> + <Weather Value="Rainy" Probability="0.5"/> + <Weather Value="Snowy" Probability="0.5"/> + </Weathers> + </Environment> + <Observations> + <Observation> + <Library>Observation_Log</Library> + <Parameters> + <String Key="OutputFilename" Value="simulationOutput.xml"/> + <Bool Key="LoggingCyclicsToCsv" Value="false"/> + <StringVector Key="LoggingGroups" Value="Trace,Visualization,RoadPosition,Sensor,Driver"/> + </Parameters> + </Observation> + </Observations> + <Spawners> + <Spawner> + <Library>SpawnPointScenario_OSI</Library> + <Type>ThisTypeDoesNotExist</Type> + <Priority>1</Priority> + </Spawner> + </Spawners> +</slaveConfig> diff --git a/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/Resources/ImporterTest/validSpawnPointSlaveConfig.xml b/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/Resources/ImporterTest/validSpawnPointSlaveConfig.xml index 6d3fb1a0a53aa884c7e0a83813352b4c9f77952b..18460875f840723d8ae95694a493efa9c2cfceb0 100644 --- a/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/Resources/ImporterTest/validSpawnPointSlaveConfig.xml +++ b/OpenPass_Test/integrationTests/OpenPassSlave_IntegrationTests/Resources/ImporterTest/validSpawnPointSlaveConfig.xml @@ -1,51 +1,60 @@ -<Combination SchemaVersion="0.7.0" id="544"> - <ProfilesCatalog>ProfilesCatalog.xml</ProfilesCatalog> - <ExperimentConfig> - <ExperimentID>123</ExperimentID> - <NumberOfInvocations>1</NumberOfInvocations> - <RandomSeed>532725206</RandomSeed> - <Libraries> - <WorldLibrary>World_OSI</WorldLibrary> - <ObservationLibrary>Observation_Log</ObservationLibrary> - <SpawnPointLibrary>SpawnPoint_OSI</SpawnPointLibrary> - </Libraries> - <LoggingGroups> - <LoggingGroup>Trace</LoggingGroup> - <LoggingGroup>Visualization</LoggingGroup> - <LoggingGroup>RoadPosition</LoggingGroup> - <LoggingGroup>Sensor</LoggingGroup> - <LoggingGroup>Driver</LoggingGroup> - </LoggingGroups> - <LoggingCyclicsToCsv>false</LoggingCyclicsToCsv> - </ExperimentConfig> - - <SpawnPointsConfig> - <SpawnPoint> - <Library>SpawnPointScenerio_OSI</Library> - <Type>PreRun</Type> - <Priority>1</Priority> - </SpawnPoint> - </SpawnPointsConfig> - - <ScenarioConfig Name="Default Scenario"> - <OpenScenarioFile>Scenario.xosc</OpenScenarioFile> - </ScenarioConfig> - - <EnvironmentConfig Name="Default Environment"> - <TimeOfDays> - <TimeOfDay Probability="0.4" Value="15" /> - <TimeOfDay Probability="0.6" Value="18" /> - </TimeOfDays> - <VisibilityDistances> - <VisibilityDistance Probability="0.7" Value="300" /> - <VisibilityDistance Probability="0.3" Value="400" /> - </VisibilityDistances> - <Frictions> - <Friction Probability="1.0" Value="1.0" /> - </Frictions> - <Weathers> - <Weather Probability="0.5" Value="Rainy" /> - <Weather Probability="0.5" Value="Snowy" /> - </Weathers> - </EnvironmentConfig> -</Combination> +<slaveConfig SchemaVersion="0.8.0"> + <ProfilesCatalog>ProfilesCatalog.xml</ProfilesCatalog> + <Experiment> + <ExperimentID>0</ExperimentID> + <NumberOfInvocations>1</NumberOfInvocations> + <RandomSeed>0</RandomSeed> + <Libraries> + <WorldLibrary>World_OSI</WorldLibrary> + </Libraries> + </Experiment> + <Scenario> + <OpenScenarioFile>Scenario.xosc</OpenScenarioFile> + </Scenario> + <Environment> + <TimeOfDays> + <TimeOfDay Value="15" Probability="0.4"/> + <TimeOfDay Value="18" Probability="0.6"/> + </TimeOfDays> + <VisibilityDistances> + <VisibilityDistance Value="125" Probability="0.7"/> + <VisibilityDistance Value="250" Probability="0.3"/> + </VisibilityDistances> + <Frictions> + <Friction Value="1.0" Probability="1.0"/> + </Frictions> + <Weathers> + <Weather Value="Rainy" Probability="0.5"/> + <Weather Value="Snowy" Probability="0.5"/> + </Weathers> + </Environment> + <Observations> + <Observation> + <Library>Observation_Log</Library> + <Parameters> + <String Key="OutputFilename" Value="simulationOutput.xml"/> + <Bool Key="LoggingCyclicsToCsv" Value="false"/> + <StringVector Key="LoggingGroups" Value="Trace,Visualization,RoadPosition,Sensor,Driver"/> + </Parameters> + </Observation> + </Observations> + <Spawners> + <Spawner> + <Library>SpawnPointScenario_OSI</Library> + <Type>PreRun</Type> + <Priority>1</Priority> + </Spawner> + <Spawner> + <Library>SpawnPointPreRunCommon_OSI</Library> + <Type>PreRun</Type> + <Priority>0</Priority> + <Profile>DefaultPreRunCommon</Profile> + </Spawner> + <Spawner> + <Library>SpawnPointRuntimeCommon_OSI</Library> + <Type>Runtime</Type> + <Priority>0</Priority> + <Profile>DefaultRuntimeCommon</Profile> + </Spawner> + </Spawners> +</slaveConfig> diff --git a/OpenPass_Test/unitTests/Common/Common_Tests.pro b/OpenPass_Test/unitTests/Common/Common_Tests.pro index 8f8e832e2ccea05c60118f1007c824c77c1c4978..add22e9c54b74ad7bf463c1ab0627662d1fd72c3 100644 --- a/OpenPass_Test/unitTests/Common/Common_Tests.pro +++ b/OpenPass_Test/unitTests/Common/Common_Tests.pro @@ -25,8 +25,11 @@ INCLUDEPATH += \ $$OPEN_SRC/CoreFramework/OpenPassSlave/modelElements HEADERS += \ - $$UNIT_UNDER_TEST/commonTools.h \ + $$UNIT_UNDER_TEST/commonTools.h + + SOURCES += \ $$UNIT_UNDER_TEST/vector2d.cpp \ + vectorToString_Tests.cpp \ ttcCalculation_Tests.cpp diff --git a/OpenPass_Test/unitTests/Common/ttcCalculation_Tests.cpp b/OpenPass_Test/unitTests/Common/ttcCalculation_Tests.cpp index e8e9c6d5fecac2e42c6d84e86b1e1d9837157340..9ce629dda8b5963f4fc491dd7e5433c6c9b92450 100644 --- a/OpenPass_Test/unitTests/Common/ttcCalculation_Tests.cpp +++ b/OpenPass_Test/unitTests/Common/ttcCalculation_Tests.cpp @@ -14,7 +14,6 @@ #include "gmock/gmock.h" #include "fakeAgent.h" -#include "fakeObservation.h" #include "fakeParameter.h" #include "fakeWorld.h" #include "fakeWorldObject.h" @@ -93,7 +92,7 @@ TEST_P(TtcCalcualtionTest, CalculateObjectTTC_ReturnsCorrectTtc) ASSERT_THAT(result, DoubleNear(data.expectedTtc, 0.001)); } -INSTANTIATE_TEST_CASE_P(TtcCalculationTestCase, TtcCalcualtionTest, Values( +INSTANTIATE_TEST_CASE_P(TtcCalculationTestCase, TtcCalcualtionTest, ::testing::Values( // Ego opponent // x, y, v_x, v_y, a, yaw, yawRate, yawAcc, x, y, v_x, v_y, a, yaw, yawRate, yawAcc, long, lat, ttc TtcCalculationTest_Data{ -20.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 12.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, DBL_MAX}, diff --git a/OpenPass_Test/unitTests/Common/vectorToString_Tests.cpp b/OpenPass_Test/unitTests/Common/vectorToString_Tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..927c71fe088cb4e1e5375a5dfce793acd5d8a48f --- /dev/null +++ b/OpenPass_Test/unitTests/Common/vectorToString_Tests.cpp @@ -0,0 +1,49 @@ +#/********************************************************************* +# * Copyright (c) 2020 in-tech GmbH +# * +# * This program and the accompanying materials are made +# * available under the terms of the Eclipse Public License 2.0 +# * which is available at https://www.eclipse.org/legal/epl-2.0/ +# * +# * SPDX-License-Identifier: EPL-2.0 +# **********************************************************************/ +#include "Common/openPassUtils.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +TEST(vectorToString, Empty_ReturnsEmtpy) +{ + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<bool>{}), ""); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<int>{}), ""); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<double>{}), ""); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<std::string>{}), ""); +} + +TEST(vectorToString, OneElement_ReturnsSingleElementWithoutDelimiter) +{ + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<bool>{true}), "1"); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<int>{123}), "123"); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<double>{12.3}), "12.3"); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<std::string>{"Test"}), "Test"); +} + +TEST(vectorToString, SeveralElementsAndNoDelimiter_ReturnsElementsWithDefaultDelimiter) +{ + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<bool>{true, false, true}), "1,0,1"); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<int>{123, 456, 789}), "123,456,789"); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<double>{12.3, 45.6, 78.9}), "12.3,45.6,78.9"); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<std::string>{"Test1", "Test2", "Test3"}), "Test1,Test2,Test3"); +} + +TEST(vectorToString, SeveralElementsAndCustomDelimiter_ReturnsElementsWithCustomDelimiter) +{ + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<int>{123, 456, 789}, "/"), "123/456/789"); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<int>{123, 456, 789}, "/ "), "123/ 456/ 789"); + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<int>{123, 456, 789}, "_THIS_IS_A_WEIRD_DELIMITER_"), "123_THIS_IS_A_WEIRD_DELIMITER_456_THIS_IS_A_WEIRD_DELIMITER_789"); +} + +TEST(vectorToString, DoublesWithLargeBandwidthAndCustomDelimiter_ReturnsElementsWithCustomDelimiter) +{ + // let see if compilers behave in the same way w.r.t std::to_string + ASSERT_THAT(openpass::utils::vector::to_string(std::vector<double>{1.23e-6, 1e-3, 1, 1000.00001, 1.23e6}, " ### "), "1.23e-06 ### 0.001 ### 1 ### 1000 ### 1.23e+06"); +} diff --git a/OpenPass_Test/unitTests/Components/AlgorithmAEB/AlgorithmAebOSIUnitTests.h b/OpenPass_Test/unitTests/Components/AlgorithmAEB/AlgorithmAebOSIUnitTests.h index 2dd0fe3ea6353a5ffdc435263b38588a41ebf0ce..e99957991737de0524cdfbf5bd18d1822a447fcf 100644 --- a/OpenPass_Test/unitTests/Components/AlgorithmAEB/AlgorithmAebOSIUnitTests.h +++ b/OpenPass_Test/unitTests/Components/AlgorithmAEB/AlgorithmAebOSIUnitTests.h @@ -8,17 +8,15 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -#include "gtest/gtest.h" -#include "gmock/gmock.h" - +#include "algorithm_autonomousEmergencyBrakingImplementation.h" #include "fakeAgent.h" -#include "fakeObservation.h" #include "fakeParameter.h" +#include "fakePublisher.h" #include "fakeStochastics.h" #include "fakeWorld.h" #include "fakeWorldObject.h" -#include "Interfaces/observationInterface.h" -#include "algorithm_autonomousEmergencyBrakingImplementation.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" using ::testing::NiceMock; @@ -32,10 +30,10 @@ public: delete implementation; } - void SetEgoValues (double velocity, double acceleration, double yawRate); + void SetEgoValues(double velocity, double acceleration, double yawRate); - AlgorithmAutonomousEmergencyBrakingImplementation* implementation; + AlgorithmAutonomousEmergencyBrakingImplementation *implementation; NiceMock<FakeWorld> fakeWorldInterface; NiceMock<FakeAgent> fakeEgoAgent; - NiceMock<FakeObservation> fakeObservation; + NiceMock<FakePublisher> fakePublisher; }; diff --git a/OpenPass_Test/unitTests/Components/AlgorithmAEB/AlgorithmAeb_Tests.cpp b/OpenPass_Test/unitTests/Components/AlgorithmAEB/AlgorithmAeb_Tests.cpp index e7978cd5decb85676953ee5bc17f8cd743ed21bb..d6aa7fc59a453da16320334d1146b7d80664de97 100644 --- a/OpenPass_Test/unitTests/Components/AlgorithmAEB/AlgorithmAeb_Tests.cpp +++ b/OpenPass_Test/unitTests/Components/AlgorithmAEB/AlgorithmAeb_Tests.cpp @@ -10,22 +10,18 @@ #include <cmath> -#include "gtest/gtest.h" -#include "gmock/gmock.h" - -#include "fakeAgent.h" -#include "fakeObservation.h" -#include "fakeWorldObject.h" -#include "fakeParameter.h" - #include "AlgorithmAebOSIUnitTests.h" #include "algorithm_autonomousEmergencyBrakingImplementation.h" - +#include "fakeAgent.h" +#include "fakeParameter.h" +#include "fakeWorldObject.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" using ::testing::_; +using ::testing::NiceMock; using ::testing::Return; using ::testing::ReturnRef; -using ::testing::NiceMock; TEST_F(AlgorithmAutonomousEmergencyBraking_UnitTest, ActualTTCLessThanBrakeTTCWithStationaryObject_ShouldActivateAEB) { @@ -92,27 +88,24 @@ TEST_F(AlgorithmAutonomousEmergencyBraking_UnitTest, ActualTTCMoreThanBrakeTTC_S AlgorithmAutonomousEmergencyBraking_UnitTest::AlgorithmAutonomousEmergencyBraking_UnitTest() { - std::map<std::string, int> intParametersSensorLink = { { "SensorId", 0 } } ; - std::map<std::string, const std::string> stringParametersSensorLink = { { "InputId", "Camera" } } ; + std::map<std::string, int> intParametersSensorLink = {{"SensorId", 0}}; + std::map<std::string, const std::string> stringParametersSensorLink = {{"InputId", "Camera"}}; auto sensorLink = std::make_shared<NiceMock<FakeParameter>>(); ON_CALL(*sensorLink, GetParametersString()).WillByDefault(ReturnRef(stringParametersSensorLink)); ON_CALL(*sensorLink, GetParametersInt()).WillByDefault(ReturnRef(intParametersSensorLink)); std::map<std::string, ParameterInterface::ParameterLists> parameterLists = - { - {"SensorLinks", {sensorLink} } - }; + { + {"SensorLinks", {sensorLink}}}; - std::map<std::string, double> doubleParameters = { { "TTC", 4.0 }, - { "Acceleration", -4 }, - { "CollisionDetectionLateralBoundary", 0.0 }, - { "CollisionDetectionLongitudinalBoundary", 0.0 } }; + std::map<std::string, double> doubleParameters = {{"TTC", 4.0}, + {"Acceleration", -4}, + {"CollisionDetectionLateralBoundary", 0.0}, + {"CollisionDetectionLongitudinalBoundary", 0.0}}; auto aebParameters = std::make_shared<NiceMock<FakeParameter>>(); ON_CALL(*aebParameters, GetParameterLists()).WillByDefault(ReturnRef(parameterLists)); ON_CALL(*aebParameters, GetParametersDouble()).WillByDefault(ReturnRef(doubleParameters)); - const std::map<int, ObservationInterface*> fakeObservationMap = {{0, &fakeObservation}}; - ON_CALL(fakeEgoAgent, GetLength()).WillByDefault(Return(2.0)); ON_CALL(fakeEgoAgent, GetWidth()).WillByDefault(Return(1.0)); ON_CALL(fakeEgoAgent, GetDistanceReferencePointToLeadingEdge()).WillByDefault(Return(1.0)); @@ -127,7 +120,7 @@ AlgorithmAutonomousEmergencyBraking_UnitTest::AlgorithmAutonomousEmergencyBrakin fakeCycleTime, nullptr, aebParameters.get(), - &fakeObservationMap, + &fakePublisher, nullptr, &fakeEgoAgent); } diff --git a/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testAlgorithmLateralImplementation.h b/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testAlgorithmLateralImplementation.h index dc1f67465301331c2c669a92b12edc0980457544..f746863effd806ca8031c5ba092a7dde2e0701af 100644 --- a/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testAlgorithmLateralImplementation.h +++ b/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testAlgorithmLateralImplementation.h @@ -18,8 +18,8 @@ #include "fakeStochastics.h" #include "fakeParameter.h" #include "fakeAgent.h" -#include "fakeObservation.h" #include "algorithm_lateralImplementation.h" +#include "fakePublisher.h" /**********************************************************/ // Define fake classes necessary for testing @@ -37,7 +37,7 @@ public: int cycleTime, StochasticsInterface* stochastics, const ParameterInterface* parameters, - const std::map<int, ObservationInterface*> *observations, + PublisherInterface * const publisher, const CallbackInterface* callbacks, AgentInterface* agent) : AlgorithmLateralImplementation( @@ -49,7 +49,7 @@ public: cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent){} diff --git a/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testResourceManager.cpp b/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testResourceManager.cpp index 715d564bd6d8dddfec0b260500019b43ae14585d..22e59eade4464c388cb1fa227592aab5b1c1a817 100644 --- a/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testResourceManager.cpp +++ b/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testResourceManager.cpp @@ -25,8 +25,7 @@ TestResourceManager::TestResourceManager() fakeStochasticsInterface = new testing::NiceMock<FakeStochastics>(); fakeParameters = new testing::NiceMock<FakeParameter>(); fakeAgent = new FakeAgent; - stubObservation = new testing::NiceMock<FakeObservation>; - stubObservations = new std::map<int, ObservationInterface*>({{0, stubObservation}}); + fakePublisher = new testing::NiceMock<FakePublisher>; CallbackInterface* callbacks = nullptr; std::map<std::string, int> intParameters {{"DebugLoggingType", 0}, {"SensorModelType", 0}}; @@ -43,7 +42,7 @@ TestResourceManager::TestResourceManager() 100, fakeStochasticsInterface, fakeParameters, - stubObservations, + fakePublisher, callbacks, fakeAgent); } @@ -65,15 +64,10 @@ TestResourceManager::~TestResourceManager() delete fakeAgent; fakeAgent = nullptr; } - if (stubObservation) + if (fakePublisher) { - delete stubObservation; - stubObservation = nullptr; - } - if (stubObservations) - { - delete stubObservations; - stubObservations = nullptr; + delete fakePublisher; + fakePublisher = nullptr; } if (stubLateralDriver) { diff --git a/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testResourceManager.h b/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testResourceManager.h index 3e438776cc2570169c44694c9df43188e72bed44..91c7ddfc1529a29e11c96414275515b93afc280f 100644 --- a/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testResourceManager.h +++ b/OpenPass_Test/unitTests/Components/Algorithm_Lateral/testResourceManager.h @@ -27,6 +27,5 @@ private: FakeStochastics* fakeStochasticsInterface{nullptr}; FakeParameter* fakeParameters{nullptr}; FakeAgent* fakeAgent; - FakeObservation* stubObservation{nullptr}; - const std::map<int, ObservationInterface*>* stubObservations{nullptr}; + FakePublisher* fakePublisher{nullptr}; }; diff --git a/OpenPass_Test/unitTests/Components/Dynamics_TrajectoryFollower/trajectoryTester.cpp b/OpenPass_Test/unitTests/Components/Dynamics_TrajectoryFollower/trajectoryTester.cpp index 9c29f535de6a72834c7ade3f9422d9ab9c1b964e..6ca283357f92b5485dc978bc3a13d3bec5404b19 100644 --- a/OpenPass_Test/unitTests/Components/Dynamics_TrajectoryFollower/trajectoryTester.cpp +++ b/OpenPass_Test/unitTests/Components/Dynamics_TrajectoryFollower/trajectoryTester.cpp @@ -18,44 +18,18 @@ TrajectoryTester::TrajectoryTester(const int cycleTime) ON_CALL(fakeAgent, GetId()).WillByDefault(Return(1)); trajectoryFollower = std::make_shared<TrajectoryFollowerImplementation>( - "trajectoryFollower", - false, - DontCare<int>(), - DontCare<int>(), - DontCare<int>(), - cycleTime, - nullptr, - nullptr, - &fakeParameters, - &fakeObservations, - nullptr, - &fakeAgent, - &fakeEventNetwork); -} - -TrajectoryTester::TrajectoryTester(const int cycleTime, - SimulationSlave::EventNetworkInterface * eventNetwork) -{ - fakeBools.insert({"EnforceTrajectory", DontCare<bool>}); - fakeBools.insert({"AutomaticDeactivation", DontCare<bool>}); - ON_CALL(fakeParameters, GetParametersBool()).WillByDefault(ReturnRef(fakeBools)); - - ON_CALL(fakeAgent, GetId()).WillByDefault(Return(1)); - - trajectoryFollower = std::make_shared<TrajectoryFollowerImplementation>( - "trajectoryFollower", - false, - DontCare<int>(), - DontCare<int>(), - DontCare<int>(), - cycleTime, - nullptr, - nullptr, - &fakeParameters, - &fakeObservations, - nullptr, - &fakeAgent, - eventNetwork); + "trajectoryFollower", + false, + DontCare<int>(), + DontCare<int>(), + DontCare<int>(), + cycleTime, + nullptr, + nullptr, + &fakeParameters, + &fakePublisher, + nullptr, + &fakeAgent); } TrajectoryTester::TrajectoryTester(const bool enforceTrajectory, const bool automaticDeactivation, const int cycleTime) @@ -67,19 +41,18 @@ TrajectoryTester::TrajectoryTester(const bool enforceTrajectory, const bool auto ON_CALL(fakeAgent, GetId()).WillByDefault(Return(1)); trajectoryFollower = std::make_shared<TrajectoryFollowerImplementation>( - "trajectoryFollower", - false, - DontCare<int>(), - DontCare<int>(), - DontCare<int>(), - cycleTime, - nullptr, - nullptr, - &fakeParameters, - &fakeObservations, - nullptr, - &fakeAgent, - &fakeEventNetwork); + "trajectoryFollower", + false, + DontCare<int>(), + DontCare<int>(), + DontCare<int>(), + cycleTime, + nullptr, + nullptr, + &fakeParameters, + &fakePublisher, + nullptr, + &fakeAgent); } TrajectoryTester::TrajectoryTester(const bool enforceTrajectory, @@ -94,19 +67,18 @@ TrajectoryTester::TrajectoryTester(const bool enforceTrajectory, ON_CALL(fakeAgent, GetId()).WillByDefault(Return(1)); trajectoryFollower = std::make_shared<TrajectoryFollowerImplementation>( - "trajectoryFollower", - false, - DontCare<int>(), - DontCare<int>(), - DontCare<int>(), - cycleTime, - nullptr, - fakeWorld, - &fakeParameters, - &fakeObservations, - nullptr, - &fakeAgent, - &fakeEventNetwork); + "trajectoryFollower", + false, + DontCare<int>(), + DontCare<int>(), + DontCare<int>(), + cycleTime, + nullptr, + fakeWorld, + &fakeParameters, + &fakePublisher, + nullptr, + &fakeAgent); } TrajectoryTester::TrajectoryTester(const bool enforceTrajectory, @@ -122,17 +94,16 @@ TrajectoryTester::TrajectoryTester(const bool enforceTrajectory, ON_CALL(*fakeAgent, GetId()).WillByDefault(Return(1)); trajectoryFollower = std::make_shared<TrajectoryFollowerImplementation>( - "trajectoryFollower", - false, - DontCare<int>(), - DontCare<int>(), - DontCare<int>(), - cycleTime, - nullptr, - fakeWorld, - &fakeParameters, - &fakeObservations, - nullptr, - fakeAgent, - &fakeEventNetwork); + "trajectoryFollower", + false, + DontCare<int>(), + DontCare<int>(), + DontCare<int>(), + cycleTime, + nullptr, + fakeWorld, + &fakeParameters, + &fakePublisher, + nullptr, + fakeAgent); } diff --git a/OpenPass_Test/unitTests/Components/Dynamics_TrajectoryFollower/trajectoryTester.h b/OpenPass_Test/unitTests/Components/Dynamics_TrajectoryFollower/trajectoryTester.h index f24807881c1d9f94738788bcc85e9dfd5ac5ba99..6574636f5afa744c054ae22e414d972edfa91cad 100644 --- a/OpenPass_Test/unitTests/Components/Dynamics_TrajectoryFollower/trajectoryTester.h +++ b/OpenPass_Test/unitTests/Components/Dynamics_TrajectoryFollower/trajectoryTester.h @@ -13,11 +13,10 @@ #include "gmock/gmock.h" #include "dontCare.h" -#include "fakeEventNetwork.h" +#include "fakePublisher.h" #include "fakeParameter.h" #include "fakeAgent.h" #include "fakeWorld.h" -#include "fakeObservation.h" #include "trajectoryFollowerImplementation.h" @@ -40,23 +39,17 @@ public: EventContainer fakeActivatingEventContainer = {fakeEvent}; EventContainer fakeEmptyEventContainer = {}; - NiceMock<FakeEventNetwork> fakeEventNetwork; + NiceMock<FakePublisher> fakePublisher; std::map<std::string, bool> fakeBools; NiceMock<FakeParameter> fakeParameters; NiceMock<FakeAgent> fakeAgent; - NiceMock<FakeObservation> fakeObservation; - std::map<int, ObservationInterface*> fakeObservations{{0, &fakeObservation}}; - std::shared_ptr<TrajectoryFollowerImplementation> trajectoryFollower; TrajectoryTester(const int cycleTime = 100); - TrajectoryTester(const int cycleTime, - SimulationSlave::EventNetworkInterface * eventNetwork); - TrajectoryTester(const bool enforceTrajectory, const bool automaticDeactivation, const int cycleTime = 100); diff --git a/OpenPass_Test/unitTests/Components/Sensor_OSI/sensorOSI_Tests.cpp b/OpenPass_Test/unitTests/Components/Sensor_OSI/sensorOSI_Tests.cpp index 4ad12ce1df2009d9f24f38de8608d9522c13b603..328c33a3e5b8c0b0800db828b21b3530a189bfba 100644 --- a/OpenPass_Test/unitTests/Components/Sensor_OSI/sensorOSI_Tests.cpp +++ b/OpenPass_Test/unitTests/Components/Sensor_OSI/sensorOSI_Tests.cpp @@ -14,7 +14,7 @@ #include "gmock/gmock.h" #include "fakeAgent.h" -#include "fakeObservation.h" +#include "fakePublisher.h" #include "fakeParameter.h" #include "fakeStochastics.h" #include "fakeWorld.h" @@ -200,8 +200,6 @@ public: fakeBools = {}; ON_CALL(fakeParameters, GetParametersBool()).WillByDefault(ReturnRef(fakeBools)); - observations = {{0, &fakeObservation}}; - ON_CALL(fakeWorldInterface, GetWorldData()).WillByDefault(Return(&fakeWorldData)); } @@ -209,14 +207,13 @@ public: osi3::SensorView sensorView; NiceMock<FakeStochastics> fakeStochastics; NiceMock<FakeParameter> fakeParameters; - NiceMock<FakeObservation> fakeObservation; + NiceMock<FakePublisher> fakePublisher; NiceMock<FakeWorld> fakeWorldInterface; NiceMock<OWL::Fakes::WorldData> fakeWorldData; NiceMock<FakeAgent> fakeAgent; std::map<std::string, double> fakeDoubles; std::map<std::string, int> fakeInts; std::map<std::string, bool> fakeBools; - std::map<int, ObservationInterface*> observations; }; void AddMovingObjectToSensorView (osi3::SensorView &sensorView, MovingObjectParameter &objectParameter) @@ -277,7 +274,7 @@ TEST_P(DetectObjects, StoresSensorDataWithDetectedObjects) &fakeStochastics, &fakeWorldInterface, &fakeParameters, - &observations, + &fakePublisher, nullptr, &fakeAgent); diff --git a/OpenPass_Test/unitTests/Components/Sensor_OSI/sensorOSI_Tests.h b/OpenPass_Test/unitTests/Components/Sensor_OSI/sensorOSI_Tests.h index 4073671a8664fb95e881145817b624a338d33729..127c048c49be17d8c8f4eb64648ed321fae8fdc1 100644 --- a/OpenPass_Test/unitTests/Components/Sensor_OSI/sensorOSI_Tests.h +++ b/OpenPass_Test/unitTests/Components/Sensor_OSI/sensorOSI_Tests.h @@ -11,10 +11,8 @@ #include "gtest/gtest.h" #include "fakeAgent.h" -#include "fakeObservation.h" #include "fakeWorld.h" #include "fakeWorldObject.h" -#include "Interfaces/observationInterface.h" #include "fakeParameter.h" #include "fakeStochastics.h" @@ -34,7 +32,6 @@ public: const polygon_t& GetBBByAgentId(size_t id); SensorGeometric2D* sensor = nullptr; - FakeObservation fakeObservation; private: ::testing::NiceMock<FakeWorld> fakeWorldInterface; @@ -53,8 +50,6 @@ private: std::map<std::string, bool> fakeBools; - std::map<int, ObservationInterface*> observations = { { 0, &fakeObservation } }; - ::testing::NiceMock<FakeAgent> fakeEgoAgent; std::vector<const WorldObjectInterface*> fakeObjects; std::vector<const polygon_t*> boundingBoxes; diff --git a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/agentParser_Tests.cpp b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/agentParser_Tests.cpp index 832453a7f1d619906f747d22ea033debadd0f74e..5002f8c5e9197afd6524d78c6515bd6c2301dbc5 100644 --- a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/agentParser_Tests.cpp +++ b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/agentParser_Tests.cpp @@ -8,21 +8,19 @@ * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -#include "gtest/gtest.h" -#include "gmock/gmock.h" - -#include "fakeAgent.h" -#include "fakeWorld.h" -#include "fakeComponent.h" -#include "fakeAgentBlueprint.h" +#include <map> -#include "schedulerTasks.h" -#include "agentParser.h" #include "Interfaces/componentInterface.h" +#include "agentParser.h" #include "channel.h" #include "component.h" - -#include <map> +#include "fakeAgent.h" +#include "fakeAgentBlueprint.h" +#include "fakeComponent.h" +#include "fakeWorld.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "schedulerTasks.h" using ::testing::_; using ::testing::Contains; @@ -34,16 +32,7 @@ using ::testing::Return; using ::testing::ReturnRef; using namespace SimulationSlave; -using namespace SimulationSlave::Scheduling; - -//class FakeTaskProvider : public TaskProviderInterface -//{ -//public: -// MOCK_CONST_METHOD1(GetTrigger, std::function<void(int)>(std::string)); -// MOCK_CONST_METHOD1(GetUpdateOutput, std::function<void(int)>(std::string)); -// MOCK_CONST_METHOD1(GetUpdateInput, std::function<void(int)>(std::string)); -//}; - +using namespace openpass::scheduling; TEST(AgentParser, RecurringComponent_IsParsed) { @@ -54,7 +43,7 @@ TEST(AgentParser, RecurringComponent_IsParsed) Channel testChannel(1); Component testTargetComponent("", &testAgent); testChannel.AddTarget(&testTargetComponent, 0); - std::map<int, Channel*> testChannels = {{0, &testChannel}}; + std::map<int, Channel *> testChannels = {{0, &testChannel}}; auto fakeComponent = new NiceMock<FakeComponent>(); ON_CALL(*fakeComponent, GetPriority()).WillByDefault(Return(0)); @@ -91,7 +80,7 @@ TEST(AgentParser, ThreeRecurringComponents_AreParsed) Channel testChannel(1); Component testTargetComponent("", &testAgent); testChannel.AddTarget(&testTargetComponent, 0); - std::map<int, Channel*> testChannels = {{0, &testChannel}}; + std::map<int, Channel *> testChannels = {{0, &testChannel}}; auto fakeComponent = new NiceMock<FakeComponent>(); ON_CALL(*fakeComponent, GetCycleTime()).WillByDefault(Return(100)); @@ -146,7 +135,7 @@ TEST(AgentParser, NonRecurringComponent_IsParsed) Channel testChannel(1); Component testTargetComponent("", &testAgent); testChannel.AddTarget(&testTargetComponent, 0); - std::map<int, Channel*> testChannels = {{0, &testChannel}}; + std::map<int, Channel *> testChannels = {{0, &testChannel}}; auto fakeComponent = new NiceMock<FakeComponent>(); ON_CALL(*fakeComponent, GetPriority()).WillByDefault(Return(0)); @@ -182,7 +171,7 @@ TEST(AgentParser, MixedComponents_AreParsedWithRightTaskType) Channel testChannel(1); Component testTargetComponent("", &testAgent); testChannel.AddTarget(&testTargetComponent, 0); - std::map<int, Channel*> testChannels = {{0, &testChannel}}; + std::map<int, Channel *> testChannels = {{0, &testChannel}}; auto fakeComponent = new NiceMock<FakeComponent>(); ON_CALL(*fakeComponent, GetCycleTime()).WillByDefault(Return(100)); diff --git a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/schedulerTasks_Tests.cpp b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/schedulerTasks_Tests.cpp index 759f3a6bfa9236c1edf35f6a6c10989e6790c972..3abc7cdec523c0e50ed19b8313833b151d6f1987 100644 --- a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/schedulerTasks_Tests.cpp +++ b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/schedulerTasks_Tests.cpp @@ -1,25 +1,26 @@ -#include "gtest/gtest.h" -#include "gmock/gmock.h" +#define OPENPASS_TESTING_ON -#include <list> +#include <functional> #include <iostream> +#include <list> #include <set> -#include <functional> +#include "gmock/gmock.h" +#include "gtest/gtest.h" #include "schedulerTasks.h" using ::testing::_; -using ::testing::Return; -using ::testing::ReturnRef; +using ::testing::ContainerEq; +using ::testing::Contains; using ::testing::Each; -using ::testing::SizeIs; +using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Field; -using ::testing::ContainerEq; -using ::testing::ElementsAre; -using ::testing::Contains; +using ::testing::Return; +using ::testing::ReturnRef; +using ::testing::SizeIs; -using namespace SimulationSlave::Scheduling; +using namespace openpass::scheduling; int currentTimestamp = 0; @@ -40,12 +41,12 @@ TEST(Tasks_Test, AddedTask_FillTasksCorrect) std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 0, std::ref(currentTimestamp)); - TriggerTaskItem firstTaskItem {0, 0, 50, 0, triggerFunc}; + TriggerTaskItem firstTaskItem{0, 0, 50, 0, triggerFunc}; TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; - UpdateTaskItem thirdTaskItem {0, 0, 100, 0, updateFunc}; - UpdateTaskItem fourthTaskItem {0, 0, 0, 0, updateFunc}; + UpdateTaskItem thirdTaskItem{0, 0, 100, 0, updateFunc}; + UpdateTaskItem fourthTaskItem{0, 0, 0, 0, updateFunc}; UpdateTaskItem fifthTaskItem{0, 10, 100, 0, updateFunc}; - UpdateTaskItem sixthTaskItem {0, 0, 100, 10, updateFunc}; + UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; Tasks testTasks; testTasks.AddTask(firstTaskItem); @@ -65,12 +66,12 @@ TEST(Tasks_Test, DeletedTasks_FilterTasksCorrect) { std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); - TriggerTaskItem firstTaskItem {0, 0, 0, 0, triggerFunc}; + TriggerTaskItem firstTaskItem{0, 0, 0, 0, triggerFunc}; TriggerTaskItem secondTaskItem{1, 10, 100, 0, triggerFunc}; - TriggerTaskItem thirdTaskItem {1, 0, 50, 0, triggerFunc}; + TriggerTaskItem thirdTaskItem{1, 0, 50, 0, triggerFunc}; TriggerTaskItem fourthTaskItem{2, 10, 0, 0, triggerFunc}; - TriggerTaskItem fifthTaskItem {3, 0, 100, 0, triggerFunc}; - TriggerTaskItem sixthTaskItem {2, 0, 100, 10, triggerFunc}; + TriggerTaskItem fifthTaskItem{3, 0, 100, 0, triggerFunc}; + TriggerTaskItem sixthTaskItem{2, 0, 100, 10, triggerFunc}; Tasks testTasks; testTasks.AddTask(firstTaskItem); @@ -97,7 +98,7 @@ TEST(Tasks_Test, DeletedLastTasks_FilterTasksCorrect) { std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); - TriggerTaskItem firstTaskItem {0, 0, 0, 0, triggerFunc}; + TriggerTaskItem firstTaskItem{0, 0, 0, 0, triggerFunc}; TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; Tasks testTasks; testTasks.AddTask(firstTaskItem); @@ -115,9 +116,9 @@ TEST(SchedulerTasks_Test, ScheduleComponentTasks_UpdateScheduledTimestamps) { std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); - TriggerTaskItem firstTaskItem {0, 0, 100, 10, triggerFunc}; - TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem thirdTaskItem {0, 0, 25, 0, triggerFunc}; + TriggerTaskItem firstTaskItem{0, 0, 100, 10, triggerFunc}; + TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem thirdTaskItem{0, 0, 25, 0, triggerFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem, thirdTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -133,10 +134,10 @@ TEST(SchedulerTasks_Test, ScheduleComponentTasksWithLargerValueThanUpperBound_Up { std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); - TriggerTaskItem firstTaskItem {0, 0, 100, 10, triggerFunc}; - TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem thirdTaskItem {0, 0, 25, 0, triggerFunc}; - TriggerTaskItem fourthTaskItem{0, 10, 250, 0, triggerFunc}; + TriggerTaskItem firstTaskItem{0, 0, 100, 10, triggerFunc}; + TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem thirdTaskItem{0, 0, 25, 0, triggerFunc}; + TriggerTaskItem fourthTaskItem{0, 10, 250, 0, triggerFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem, thirdTaskItem, fourthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -152,9 +153,9 @@ TEST(SchedulerTasks_Test, ScheduleComponentTasksWithLargerDelayThanBound_UpdateS { std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); - TriggerTaskItem firstTaskItem {0, 0, 100, 10, triggerFunc}; - TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem thirdTaskItem {0, 0, 50, 300, triggerFunc}; + TriggerTaskItem firstTaskItem{0, 0, 100, 10, triggerFunc}; + TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem thirdTaskItem{0, 0, 50, 300, triggerFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem, thirdTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -170,12 +171,12 @@ TEST(SchedulerTasks_Test, ScheduleComponentTasksWithMultipleLargerHorizons_Updat { std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); - TriggerTaskItem firstTaskItem {0, 0, 100, 10, triggerFunc}; - TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem thirdTaskItem {0, 0, 250, 0, triggerFunc}; - TriggerTaskItem fourthTaskItem{0, 10, 250, 10, triggerFunc}; - TriggerTaskItem fifthTaskItem{0, 10, 300, 0, triggerFunc}; - TriggerTaskItem sixthTaskItem{0, 10, 400, 0, triggerFunc}; + TriggerTaskItem firstTaskItem{0, 0, 100, 10, triggerFunc}; + TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem thirdTaskItem{0, 0, 250, 0, triggerFunc}; + TriggerTaskItem fourthTaskItem{0, 10, 250, 10, triggerFunc}; + TriggerTaskItem fifthTaskItem{0, 10, 300, 0, triggerFunc}; + TriggerTaskItem sixthTaskItem{0, 10, 400, 0, triggerFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem, thirdTaskItem, fourthTaskItem, fifthTaskItem, sixthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -191,7 +192,7 @@ TEST(SchedulerTasks_Test, ScheduleComponentTasks_FillNonRecurringTasksCorrect) { std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); - TriggerTaskItem firstTaskItem {0, 0, 0, 0, triggerFunc}; + TriggerTaskItem firstTaskItem{0, 0, 0, 0, triggerFunc}; TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem}; @@ -211,19 +212,19 @@ TEST(SchedulerTasks_Test, DeleteAgentTasks_FilterAllAffectedTasks) std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - UpdateTaskItem firstTaskItem {normalAgent, 0, 0, 0, updateFunc}; - TriggerTaskItem secondTaskItem{removeAgent, 10, 0, 0, triggerFunc}; + UpdateTaskItem firstTaskItem{normalAgent, 0, 0, 0, updateFunc}; + TriggerTaskItem secondTaskItem{removeAgent, 10, 0, 0, triggerFunc}; std::list<TaskItem> testTasksNonRecurring{firstTaskItem, secondTaskItem}; - TriggerTaskItem thirdTaskItem{removeAgent, 10, 100, 0, triggerFunc}; - TriggerTaskItem fourthTaskItem {removeAgent, 0, 50, 0, triggerFunc}; - UpdateTaskItem fifthTaskItem {normalAgent, 0, 100, 0, updateFunc}; - UpdateTaskItem sixthTaskItem {normalAgent, 0, 100, 10, updateFunc}; + TriggerTaskItem thirdTaskItem{removeAgent, 10, 100, 0, triggerFunc}; + TriggerTaskItem fourthTaskItem{removeAgent, 0, 50, 0, triggerFunc}; + UpdateTaskItem fifthTaskItem{normalAgent, 0, 100, 0, updateFunc}; + UpdateTaskItem sixthTaskItem{normalAgent, 0, 100, 10, updateFunc}; std::list<TaskItem> testTasksRecurring{thirdTaskItem, fourthTaskItem, fifthTaskItem, sixthTaskItem}; - ManipulatorTaskItem firstCommonTaskItem {100, triggerFunc}; + ManipulatorTaskItem firstCommonTaskItem{100, triggerFunc}; EventDetectorTaskItem secondCommonTaskItem{100, triggerFunc}; - SpawningTaskItem thirdCommonTaskItem {100, triggerFunc}; + SpawningTaskItem thirdCommonTaskItem{100, triggerFunc}; ObservationTaskItem fourthCommonTaskItem{100, triggerFunc}; std::list<TaskItem> testCommonTasks{firstCommonTaskItem, secondCommonTaskItem, thirdCommonTaskItem, fourthCommonTaskItem}; @@ -236,26 +237,23 @@ TEST(SchedulerTasks_Test, DeleteAgentTasks_FilterAllAffectedTasks) std::multiset<TaskItem> recurringTasks = testSchedulerTasks.recurringTasks.tasks; auto recurringIt = std::find_if(recurringTasks.begin(), recurringTasks.end(), - [removeAgent](const TaskItem &TaskItem) - { - return removeAgent == TaskItem.agentId; - }); + [removeAgent](const TaskItem &TaskItem) { + return removeAgent == TaskItem.agentId; + }); ASSERT_TRUE(recurringIt == recurringTasks.end()); std::multiset<TaskItem> nonRecurringTasks = testSchedulerTasks.nonRecurringTasks.tasks; auto nonRecurringIt = std::find_if(nonRecurringTasks.begin(), nonRecurringTasks.end(), - [removeAgent](const TaskItem &TaskItem) - { - return removeAgent == TaskItem.agentId; - }); + [removeAgent](const TaskItem &TaskItem) { + return removeAgent == TaskItem.agentId; + }); ASSERT_TRUE(nonRecurringIt == nonRecurringTasks.end()); std::multiset<TaskItem> commonTasks = testSchedulerTasks.commonTasks.tasks; auto commonIt = std::find_if(commonTasks.begin(), commonTasks.end(), - [removeAgent](const TaskItem &TaskItem) - { - return removeAgent == TaskItem.agentId; - }); + [removeAgent](const TaskItem &TaskItem) { + return removeAgent == TaskItem.agentId; + }); ASSERT_TRUE(commonIt == commonTasks.end()); } @@ -265,11 +263,11 @@ TEST(SchedulerTasks_Test, DeleteAgentTasks_CreateNewScheduledTimestamps) std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - UpdateTaskItem firstTaskItem{0, 0, 100, 0, updateFunc}; - TriggerTaskItem secondTaskItem{removeAgent,10, 25, 0, triggerFunc}; - UpdateTaskItem thirdTaskItem{0, 0, 100, 0, updateFunc}; - TriggerTaskItem fourthTaskItem{removeAgent,10, 100, 10, triggerFunc}; - UpdateTaskItem fifthtTaskItem{0, 0, 50, 0, updateFunc}; + UpdateTaskItem firstTaskItem{0, 0, 100, 0, updateFunc}; + TriggerTaskItem secondTaskItem{removeAgent, 10, 25, 0, triggerFunc}; + UpdateTaskItem thirdTaskItem{0, 0, 100, 0, updateFunc}; + TriggerTaskItem fourthTaskItem{removeAgent, 10, 100, 10, triggerFunc}; + UpdateTaskItem fifthtTaskItem{0, 0, 50, 0, updateFunc}; TriggerTaskItem sixthTaskItem{removeAgent, 10, 10, 0, triggerFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem, thirdTaskItem, fourthTaskItem, fifthtTaskItem, sixthTaskItem}; @@ -289,10 +287,10 @@ TEST(SchedulerTasks_Test, ScheduleComponentTasks_FillRecurringTasksCorrect) std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - TriggerTaskItem firstTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem secondTaskItem {0, 0, 50, 0, triggerFunc}; - UpdateTaskItem thirdTaskItem {0, 0, 100, 0, updateFunc}; - UpdateTaskItem fourthTaskItem {0, 0, 100, 10, updateFunc}; + TriggerTaskItem firstTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem secondTaskItem{0, 0, 50, 0, triggerFunc}; + UpdateTaskItem thirdTaskItem{0, 0, 100, 0, updateFunc}; + UpdateTaskItem fourthTaskItem{0, 0, 100, 10, updateFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem, thirdTaskItem, fourthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -322,10 +320,10 @@ TEST(SchedulerTasks_Test, GetNextTimestamp_CreateNewScheduledTimestamps) std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - UpdateTaskItem firstTaskItem {0, 0, 50, 0, updateFunc}; - TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem thirdTaskItem {0, 0, 100, 10, triggerFunc}; - TriggerTaskItem fourthTaskItem{0, 10, 50, 0, triggerFunc}; + UpdateTaskItem firstTaskItem{0, 0, 50, 0, updateFunc}; + TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem thirdTaskItem{0, 0, 100, 10, triggerFunc}; + TriggerTaskItem fourthTaskItem{0, 10, 50, 0, triggerFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem, thirdTaskItem, fourthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -346,10 +344,10 @@ TEST(SchedulerTasks_Test, GetNextTimestampWithUnscheduledTimestamp_MakesCorrectS std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - UpdateTaskItem firstTaskItem {0, 0, 50, 0, updateFunc}; - TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem thirdTaskItem {0, 0, 100, 10, triggerFunc}; - TriggerTaskItem fourthTaskItem{0, 10, 50, 0, triggerFunc}; + UpdateTaskItem firstTaskItem{0, 0, 50, 0, updateFunc}; + TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem thirdTaskItem{0, 0, 100, 10, triggerFunc}; + TriggerTaskItem fourthTaskItem{0, 10, 50, 0, triggerFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem, thirdTaskItem, fourthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -368,14 +366,14 @@ TEST(SchedulerTasks_Test, GetAllCurrentTasks_DeliversFilteredTasks) std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - UpdateTaskItem firstTaskItem{0, 0, 0, 0, updateFunc}; - TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; + UpdateTaskItem firstTaskItem{0, 0, 0, 0, updateFunc}; + TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; std::list<TaskItem> testTasksNonRecurring{firstTaskItem, secondTaskItem}; - TriggerTaskItem thirdTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem fourthTaskItem{0, 0, 25, 0, triggerFunc}; - UpdateTaskItem fifthTaskItem{0, 0, 100, 20, updateFunc}; - UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; + TriggerTaskItem thirdTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem fourthTaskItem{0, 0, 25, 0, triggerFunc}; + UpdateTaskItem fifthTaskItem{0, 0, 100, 20, updateFunc}; + UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; std::list<TaskItem> testTasksRecurring{thirdTaskItem, fourthTaskItem, fifthTaskItem, sixthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -392,12 +390,12 @@ TEST(SchedulerTasks_Test, GetAllCurrentTasks_DeliversFilteredTasksOnSecondTimest std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - UpdateTaskItem firstTaskItem {0, 0, 50, 0, updateFunc}; - TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem thirdTaskItem {0, 0, 25, 0, triggerFunc}; - TriggerTaskItem fourthTaskItem{0, 10, 50, 0, triggerFunc}; - UpdateTaskItem fifthTaskItem {0, 0, 100, 20, updateFunc}; - UpdateTaskItem sixthTaskItem {0, 0, 100, 10, updateFunc}; + UpdateTaskItem firstTaskItem{0, 0, 50, 0, updateFunc}; + TriggerTaskItem secondTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem thirdTaskItem{0, 0, 25, 0, triggerFunc}; + TriggerTaskItem fourthTaskItem{0, 10, 50, 0, triggerFunc}; + UpdateTaskItem fifthTaskItem{0, 0, 100, 20, updateFunc}; + UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; std::list<TaskItem> testTasks{firstTaskItem, secondTaskItem, thirdTaskItem, fourthTaskItem, fifthTaskItem, sixthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -415,14 +413,14 @@ TEST(SchedulerTasks_Test, GetAllCurrentTasksWithUnscheduledTimestamp_DeliversEmp int unscheduledTimestamp = 1; - UpdateTaskItem firstTaskItem{0, 0, 0, 0, updateFunc}; - TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; + UpdateTaskItem firstTaskItem{0, 0, 0, 0, updateFunc}; + TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; std::list<TaskItem> testTasksNonRecurring{firstTaskItem, secondTaskItem}; - TriggerTaskItem thirdTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem fourthTaskItem{0, 0, 25, 0, triggerFunc}; - UpdateTaskItem fifthTaskItem{0, 0, 100, 20, updateFunc}; - UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; + TriggerTaskItem thirdTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem fourthTaskItem{0, 0, 25, 0, triggerFunc}; + UpdateTaskItem fifthTaskItem{0, 0, 100, 20, updateFunc}; + UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; std::list<TaskItem> testTasksRecurring{thirdTaskItem, fourthTaskItem, fifthTaskItem, sixthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -438,14 +436,14 @@ TEST(SchedulerTasks_Test, GetAllCurrentTasksWithinFirstBoundaries_DeliversFilter std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - UpdateTaskItem firstTaskItem{0, 0, 0, 0, updateFunc}; - TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; + UpdateTaskItem firstTaskItem{0, 0, 0, 0, updateFunc}; + TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; std::list<TaskItem> testTasksNonRecurring{firstTaskItem, secondTaskItem}; - TriggerTaskItem thirdTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem fourthTaskItem{0, 0, 25, 0, triggerFunc}; - UpdateTaskItem fifthTaskItem{0, 0, 100, 20, updateFunc}; - UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; + TriggerTaskItem thirdTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem fourthTaskItem{0, 0, 25, 0, triggerFunc}; + UpdateTaskItem fifthTaskItem{0, 0, 100, 20, updateFunc}; + UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; std::list<TaskItem> testTasksRecurring{thirdTaskItem, fourthTaskItem, fifthTaskItem, sixthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -470,14 +468,14 @@ TEST(SchedulerTasks_Test, GetAllCurrentTasksWithTimestampHigherBound_DeliversFil std::function<bool(void)> triggerFunc = std::bind(&TriggerFunc, std::ref(currentTimestamp)); std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - UpdateTaskItem firstTaskItem{0, 0, 0, 0, updateFunc}; - TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; + UpdateTaskItem firstTaskItem{0, 0, 0, 0, updateFunc}; + TriggerTaskItem secondTaskItem{0, 10, 0, 0, triggerFunc}; std::list<TaskItem> testTasksNonRecurring{firstTaskItem, secondTaskItem}; - TriggerTaskItem thirdTaskItem{0, 10, 100, 0, triggerFunc}; - TriggerTaskItem fourthTaskItem{0, 0, 25, 0, triggerFunc}; - UpdateTaskItem fifthTaskItem{0, 0, 100, 20, updateFunc}; - UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; + TriggerTaskItem thirdTaskItem{0, 10, 100, 0, triggerFunc}; + TriggerTaskItem fourthTaskItem{0, 0, 25, 0, triggerFunc}; + UpdateTaskItem fifthTaskItem{0, 0, 100, 20, updateFunc}; + UpdateTaskItem sixthTaskItem{0, 0, 100, 10, updateFunc}; std::list<TaskItem> testTasksRecurring{thirdTaskItem, fourthTaskItem, fifthTaskItem, sixthTaskItem}; SchedulerTasks testSchedulerTasks(std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, std::list<TaskItem>{}, 200); @@ -495,8 +493,8 @@ TEST(SchedulerTasks_Test, UpdateTasks_ListedInCorrectOrder) { std::function<bool(void)> updateFunc = std::bind(&UpdateFunc, 42, std::ref(currentTimestamp)); - UpdateTaskItem outputTaskItem{0, 0, 0, 0, updateFunc}; - UpdateTaskItem inputTaskItem{1, 0, 0, 0, updateFunc}; + UpdateTaskItem outputTaskItem{0, 0, 0, 0, updateFunc}; + UpdateTaskItem inputTaskItem{1, 0, 0, 0, updateFunc}; std::list<TaskItem> taskItems; taskItems.push_back(outputTaskItem); diff --git a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/scheduler_Tests.cpp b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/scheduler_Tests.cpp index d54afc496125f22b5727d4bdbc2c31cf1f083d77..0488d380d7a8861ca8f4c84edb85fd347a5e7dcb 100644 --- a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/scheduler_Tests.cpp +++ b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/scheduler_Tests.cpp @@ -1,33 +1,31 @@ -#include "gtest/gtest.h" -#include "gmock/gmock.h" - -#include <list> +#include <functional> #include <iostream> +#include <list> #include <set> -#include <functional> -#include "fakeWorld.h" -#include "fakeSpawnPointNetwork.h" +#include "eventDetector.h" +#include "eventDetectorLibrary.h" #include "fakeEventDetectorNetwork.h" -#include "fakeManipulatorNetwork.h" #include "fakeEventNetwork.h" +#include "fakeManipulatorNetwork.h" #include "fakeObservationNetwork.h" - -#include "eventDetector.h" -#include "eventDetectorLibrary.h" +#include "fakeSpawnPointNetwork.h" +#include "fakeWorld.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" #include "scheduler.h" #include "schedulerTasks.h" -using namespace SimulationSlave::Scheduling; +using namespace openpass::scheduling; using testing::NiceMock; -using testing::ReturnRef; using testing::Return; +using testing::ReturnRef; -template<typename T> +template <typename T> void ExecuteTasks(T tasks) { - for(auto& task : tasks) + for (auto &task : tasks) { task.func(); } @@ -72,7 +70,7 @@ TEST(DISABLED_Scheduler, RunWorks) SimulationSlave::EventDetector e1(&fakeEventDetector, &edl); SimulationSlave::EventDetector e2(&fakeEventDetector, &edl); - std::vector<const SimulationSlave::EventDetector*> fakeEventDetectors; + std::vector<const SimulationSlave::EventDetector *> fakeEventDetectors; fakeEventDetectors.push_back(&e1); fakeEventDetectors.push_back(&e2); diff --git a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/scheduler_Tests.pro b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/scheduler_Tests.pro index b8655fa5cb108f1f2b9583116acf8ecdca36e2c2..a1087eb4d8bcfe9bdd570b2f212acd54da1c5cdf 100644 --- a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/scheduler_Tests.pro +++ b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/scheduler_Tests.pro @@ -60,4 +60,6 @@ SOURCES += \ taskBuilder_Tests.cpp \ schedulerTasks_Tests.cpp \ agentParser_Tests.cpp \ - scheduler_Tests.cpp + scheduler_Tests.cpp \ + \ # unknown dependency (@reinhard)! + $$OPEN_PASS_SLAVE/framework/agentDataPublisher.cpp diff --git a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/taskBuilder_Tests.cpp b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/taskBuilder_Tests.cpp index 745feec9fe430cabf132ad15dc684c8d9e807c42..c14001757854e7933291a8941b908a505e775278 100644 --- a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/taskBuilder_Tests.cpp +++ b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/Scheduler/taskBuilder_Tests.cpp @@ -1,30 +1,28 @@ -#include "gtest/gtest.h" -#include "gmock/gmock.h" #include <vector> #include "Interfaces/scenarioInterface.h" - +#include "eventDetector.h" #include "fakeEventDetectorNetwork.h" #include "fakeManipulatorNetwork.h" #include "fakeSpawnPointNetwork.h" #include "fakeWorld.h" -#include "eventDetector.h" - +#include "gmock/gmock.h" +#include "gtest/gtest.h" #include "taskBuilder.h" using ::testing::_; -using ::testing::Invoke; -using ::testing::Gt; -using ::testing::SizeIs; using ::testing::Contains; -using ::testing::Not; -using ::testing::Field; using ::testing::Eq; +using ::testing::Field; +using ::testing::Gt; +using ::testing::Invoke; using ::testing::NiceMock; +using ::testing::Not; using ::testing::Return; +using ::testing::SizeIs; using namespace SimulationSlave; -using namespace SimulationSlave::Scheduling; +using namespace openpass::scheduling; TEST(TaskBuilder, CommonTaskCreation_Works) { @@ -35,7 +33,7 @@ TEST(TaskBuilder, CommonTaskCreation_Works) SimulationSlave::EventDetector e1(&fakeEventDetector, &edl); SimulationSlave::EventDetector e2(&fakeEventDetector, &edl); - std::vector<const SimulationSlave::EventDetector*> fakeEventDetectors; + std::vector<const SimulationSlave::EventDetector *> fakeEventDetectors; fakeEventDetectors.push_back(&e1); fakeEventDetectors.push_back(&e2); diff --git a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/agentDataPublisher_Tests.cpp b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/agentDataPublisher_Tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..04bd4f8ad18c9608dc6f6fb7ea03d61ac93274ce --- /dev/null +++ b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/agentDataPublisher_Tests.cpp @@ -0,0 +1,103 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#include "agentDataPublisher.h" +#include "dontCare.h" +#include "fakeCallback.h" +#include "fakeDataStore.h" +#include "fakeEventNetwork.h" +#include "fakeParameter.h" +#include "fakeStochastics.h" +#include "fakeWorld.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "scheduler/timeKeeper.h" + +using ::testing::_; +using ::testing::DontCare; +using ::testing::NiceMock; +using ::testing::NotNull; +using ::testing::Return; +using ::testing::ReturnRef; + +using namespace openpass::datastore; +using namespace openpass::publisher; +using namespace openpass::type; + +struct TimeManipulatior : public openpass::scheduling::TimeKeeper +{ + static void Set(int faketime) + { + time = faketime; + } +}; + +TEST(AgentDataPublisher, CallingPublish_ForwardsParametersToDataStore) +{ + FakeDataStore fakeDataStore; + + const Timestamp timestamp = 3; + const EntityId agentId = 1; + const Key key = "theKey"; + const Value value = 2; + + auto adp = std::make_unique<AgentDataPublisher>(&fakeDataStore, agentId); + + TimeManipulatior::Set(timestamp); + EXPECT_CALL(fakeDataStore, PutCyclic(timestamp, agentId, key, value)); + + ASSERT_THAT(adp, NotNull()); + + adp->Publish(key, value); +} + +TEST(AgentDataPublisher, UpdatedScheulderTime_IsAccessibleByPublisher) +{ + FakeDataStore fakeDataStore; + + const EntityId agentId = 1; + const Key key = "theKey"; + const Value value = 2; + const Timestamp timestep1 = 1; + const Timestamp timestep2 = 2; + + auto adp = std::make_unique<AgentDataPublisher>(&fakeDataStore, agentId); + + EXPECT_CALL(fakeDataStore, PutCyclic(timestep1, _, _, _)); + EXPECT_CALL(fakeDataStore, PutCyclic(timestep2, _, _, _)); + + ASSERT_THAT(adp, NotNull()); + + TimeManipulatior::Set(timestep1); + adp->Publish(key, value); + + TimeManipulatior::Set(timestep2); + adp->Publish(key, value); +} + +TEST(AgentDataPublisher, PublishingSameTimestampTwice_Succeeds) +{ + FakeDataStore fakeDataStore; + + const EntityId agentId = 1; + const Key key = "theKey"; + const Value value = 2; + const Timestamp timestep = 1; + + auto adp = std::make_unique<AgentDataPublisher>(&fakeDataStore, agentId); + + EXPECT_CALL(fakeDataStore, PutCyclic(timestep, _, _, _)).Times(2); + + ASSERT_THAT(adp, NotNull()); + + TimeManipulatior::Set(timestep); + ASSERT_NO_THROW(adp->Publish(key, value)); + ASSERT_NO_THROW(adp->Publish(key, value)); +} diff --git a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/eventNetwork_Tests.cpp b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/eventNetwork_Tests.cpp index 96810fd3094bb6deac609fad4eded0e8121dcf17..9f802ad217b818eaec29f662bba8a6b15271e96f 100644 --- a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/eventNetwork_Tests.cpp +++ b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/eventNetwork_Tests.cpp @@ -1,5 +1,5 @@ /******************************************************************************* -* Copyright (c) 2019 in-tech GmbH +* Copyright (c) 2019, 2020 in-tech GmbH * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -7,175 +7,171 @@ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -#include "gtest/gtest.h" -#include "gmock/gmock.h" - #include "eventNetwork.h" - +#include "fakeDataStore.h" #include "fakeEvent.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" +using ::testing::_; +using ::testing::IsEmpty; using ::testing::Ne; using ::testing::NiceMock; using ::testing::Return; using ::testing::SizeIs; -TEST(EventNetwork_UnitTests, InsertEventInNotExistingCategory) +TEST(DISABLED_EventNetwork, InsertEvent_LogsEvent) { - auto fakeEvent = std::make_shared<NiceMock<FakeEvent>>(); - EXPECT_CALL(*fakeEvent, GetCategory()).Times(1).WillOnce(Return(EventDefinitions::EventCategory::Conditional)); + NiceMock<FakeDataStore> mockDataStore; - SimulationSlave::EventNetwork eventNetwork; + std::vector<int> setOf3Ids{1, 2, 3}; + std::vector<int> setOf2Ids{4, 5}; + auto fakeEvent1 = std::make_shared<BasicEvent>(100, "test_event_1", "dont_care", setOf3Ids, setOf2Ids); + auto fakeEvent2 = std::make_shared<BasicEvent>(200, "test_event_2", "dont_care", setOf2Ids, setOf3Ids); - eventNetwork.InsertEvent(fakeEvent); + SimulationSlave::EventNetwork eventNetwork(&mockDataStore); - std::list<std::shared_ptr<EventInterface>> resultAgentBasedEventList = - eventNetwork.GetActiveEvents()->at(EventDefinitions::EventCategory::Conditional); + eventNetwork.InsertEvent(fakeEvent1); + eventNetwork.InsertEvent(fakeEvent2); - ASSERT_EQ(resultAgentBasedEventList.size(), size_t(1)); + EXPECT_CALL(mockDataStore, PutAcyclic(_, _, _, _)).Times(2); } -TEST(EventNetwork_UnitTests, InsertEventInExistingCategory) +TEST(EventNetwork, GetCategoryWithoutEvent_IsEmpty) { - auto fakeEvent = std::make_shared<NiceMock<FakeEvent>>(); - EXPECT_CALL(*fakeEvent, GetCategory()).Times(1).WillOnce(Return(EventDefinitions::EventCategory::Conditional)); - - std::list<std::shared_ptr<EventInterface>> fakeAgentBasedEventList; - fakeAgentBasedEventList.push_back(fakeEvent); - - Events fakeEvents{{EventDefinitions::EventCategory::Conditional, fakeAgentBasedEventList}}; - - SimulationSlave::EventNetwork eventNetwork; - *(eventNetwork.GetActiveEvents()) = fakeEvents; - - eventNetwork.InsertEvent(fakeEvent); - - std::list<std::shared_ptr<EventInterface>> resultAgentBasedEventList = - eventNetwork.GetActiveEvents()->at(EventDefinitions::EventCategory::Conditional); + NiceMock<FakeDataStore> fds; + SimulationSlave::EventNetwork eventNetwork(&fds); + ASSERT_THAT(eventNetwork.GetActiveEventCategory(EventDefinitions::EventCategory::OpenSCENARIO), IsEmpty()); +} - ASSERT_EQ(resultAgentBasedEventList.size(), size_t(2)); +std::shared_ptr<EventInterface> GENERATE_FAKE_CONDITIONAL_EVENT() +{ + return std::make_shared<ConditionalEvent>(0, "dont_care", "dont_care", std::vector<int>{}, std::vector<int>{}); } -TEST(EventNetwork_UnitTests, GetActiveEventCategoryWithOneExisting) +TEST(EventNetwork, InsertEventOnEmptyNetwork_AddsToNewCategory) { - auto fakeEvent = std::make_shared<FakeEvent>(); + NiceMock<FakeDataStore> fds; + SimulationSlave::EventNetwork eventNetwork(&fds); - EventContainer fakeEventList; - fakeEventList.push_back(fakeEvent); + eventNetwork.InsertEvent(GENERATE_FAKE_CONDITIONAL_EVENT()); + ASSERT_THAT(eventNetwork.GetActiveEvents()->at(EventDefinitions::EventCategory::OpenSCENARIO), SizeIs(1)); +} - Events fakeEvents {{EventDefinitions::EventCategory::Conditional, fakeEventList}}; +TEST(EventNetwork, InsertEventOfAlreadyAddedCategory_AddsToExistingCategory) +{ + NiceMock<FakeDataStore> fds; + SimulationSlave::EventNetwork eventNetwork(&fds); - SimulationSlave::EventNetwork eventNetwork; - *(eventNetwork.GetActiveEvents()) = fakeEvents; + eventNetwork.GetActiveEvents()->insert({EventDefinitions::EventCategory::OpenSCENARIO, {GENERATE_FAKE_CONDITIONAL_EVENT()}}); - EventContainer resultEventList = eventNetwork.GetActiveEventCategory(EventDefinitions::EventCategory::Conditional); + eventNetwork.InsertEvent(GENERATE_FAKE_CONDITIONAL_EVENT()); - ASSERT_THAT(resultEventList, SizeIs(Ne(0))); + ASSERT_THAT(eventNetwork.GetActiveEvents()->at(EventDefinitions::EventCategory::OpenSCENARIO), SizeIs(2)); } -TEST(EventNetwork_UnitTests, GetActiveEventCategoryWithoutExisting) +TEST(EventNetwork, InsertEventOnNewCategory_AddsToNewCategory) { - EventContainer fakeEventList; - Events fakeEvents {{EventDefinitions::EventCategory::Basic, fakeEventList}}; + NiceMock<FakeDataStore> fds; + SimulationSlave::EventNetwork eventNetwork(&fds); - SimulationSlave::EventNetwork eventNetwork; - *(eventNetwork.GetActiveEvents()) = fakeEvents; + eventNetwork.GetActiveEvents()->insert({EventDefinitions::EventCategory::Basic, + {std::make_shared<BasicEvent>(0, "dont_care", "dont_care")}}); - EventContainer resultEventList = eventNetwork.GetActiveEventCategory(EventDefinitions::EventCategory::Conditional); + eventNetwork.InsertEvent(GENERATE_FAKE_CONDITIONAL_EVENT()); - ASSERT_THAT(resultEventList, SizeIs(0)); + ASSERT_THAT(eventNetwork.GetActiveEvents()->at(EventDefinitions::EventCategory::Basic), SizeIs(1)); + ASSERT_THAT(eventNetwork.GetActiveEvents()->at(EventDefinitions::EventCategory::OpenSCENARIO), SizeIs(1)); } -TEST(EventNetwork_UnitTests, RemoveOldEventsWithTwoOldEventsOfTheSameCategory) +TEST(EventNetwork, RemoveOldEventsWithTwoOldEventsOfTheSameCategory) { int actualTime = 3; auto fakeEvent = std::make_shared<NiceMock<FakeEvent>>(); - EXPECT_CALL(*fakeEvent, GetEventTime()).Times(3) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .WillOnce(Return(actualTime)); + EXPECT_CALL(*fakeEvent, GetEventTime()).Times(3).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(Return(actualTime)); EventContainer fakeConditionalEvents; fakeConditionalEvents.push_back(fakeEvent); fakeConditionalEvents.push_back(fakeEvent); fakeConditionalEvents.push_back(fakeEvent); - Events fakeEvents {{EventDefinitions::EventCategory::Conditional, fakeConditionalEvents}}; + Events fakeEvents{{EventDefinitions::EventCategory::OpenSCENARIO, fakeConditionalEvents}}; + + NiceMock<FakeDataStore> fds; + SimulationSlave::EventNetwork eventNetwork(&fds); - SimulationSlave::EventNetwork eventNetwork; *(eventNetwork.GetArchivedEvents()) = fakeEvents; eventNetwork.RemoveOldEvents(actualTime); - EventContainer resultEventList = eventNetwork.GetArchivedEvents()->at(EventDefinitions::EventCategory::Conditional); + EventContainer resultEventList = eventNetwork.GetArchivedEvents()->at(EventDefinitions::EventCategory::OpenSCENARIO); ASSERT_THAT(resultEventList, SizeIs(1)); } -TEST(EventNetwork_UnitTests, RemoveOldEventsWithTwoOldEventsOfDifferentCategories) +TEST(EventNetwork, RemoveOldEventsWithTwoOldEventsOfDifferentCategories) { int actualTime = 2; auto fakeEventFirst = std::make_shared<NiceMock<FakeEvent>>(); - EXPECT_CALL(*fakeEventFirst, GetEventTime()).Times(2) - .WillOnce(Return(1)) - .WillOnce(Return(actualTime)); + EXPECT_CALL(*fakeEventFirst, GetEventTime()).Times(2).WillOnce(Return(1)).WillOnce(Return(actualTime)); EventContainer fakeConditionalEvents; fakeConditionalEvents.push_back(fakeEventFirst); fakeConditionalEvents.push_back(fakeEventFirst); auto fakeEventSecond = std::make_shared<NiceMock<FakeEvent>>(); - EXPECT_CALL(*fakeEventSecond, GetEventTime()).Times(2) - .WillOnce(Return(1)) - .WillOnce(Return(actualTime)); + EXPECT_CALL(*fakeEventSecond, GetEventTime()).Times(2).WillOnce(Return(1)).WillOnce(Return(actualTime)); EventContainer fakeBasicEvents; fakeBasicEvents.push_back(fakeEventSecond); fakeBasicEvents.push_back(fakeEventSecond); - Events fakeEvents {{EventDefinitions::EventCategory::Conditional, fakeConditionalEvents}, - {EventDefinitions::EventCategory::Basic, fakeBasicEvents}}; + Events fakeEvents{{EventDefinitions::EventCategory::OpenSCENARIO, fakeConditionalEvents}, + {EventDefinitions::EventCategory::Basic, fakeBasicEvents}}; + + NiceMock<FakeDataStore> fds; + SimulationSlave::EventNetwork eventNetwork(&fds); - SimulationSlave::EventNetwork eventNetwork; *(eventNetwork.GetArchivedEvents()) = fakeEvents; eventNetwork.RemoveOldEvents(actualTime); - EventContainer conditionalEvents = eventNetwork.GetArchivedEvents()->at(EventDefinitions::EventCategory::Conditional); + EventContainer conditionalEvents = eventNetwork.GetArchivedEvents()->at(EventDefinitions::EventCategory::OpenSCENARIO); EventContainer basicEvents = eventNetwork.GetArchivedEvents()->at(EventDefinitions::EventCategory::Basic); ASSERT_THAT(conditionalEvents, SizeIs(1)); ASSERT_THAT(basicEvents, SizeIs(1)); } -TEST(EventNetwork_UnitTests, RemoveOldEventsWithNoOldEvents) +TEST(EventNetwork, RemoveOldEventsWithNoOldEvents) { int actualTime = 2; auto fakeEventFirst = std::make_shared<NiceMock<FakeEvent>>(); - EXPECT_CALL(*fakeEventFirst, GetEventTime()).Times(1) - .WillOnce(Return(actualTime)); + EXPECT_CALL(*fakeEventFirst, GetEventTime()).Times(1).WillOnce(Return(actualTime)); EventContainer fakeConditionalEvents; fakeConditionalEvents.push_back(fakeEventFirst); auto fakeEventSecond = std::make_shared<NiceMock<FakeEvent>>(); - EXPECT_CALL(*fakeEventSecond, GetEventTime()).Times(1) - .WillOnce(Return(actualTime)); + EXPECT_CALL(*fakeEventSecond, GetEventTime()).Times(1).WillOnce(Return(actualTime)); EventContainer fakeBasicEvents; fakeBasicEvents.push_back(fakeEventSecond); - Events fakeEvents {{EventDefinitions::EventCategory::Conditional, fakeConditionalEvents}, - {EventDefinitions::EventCategory::Basic, fakeBasicEvents}}; + Events fakeEvents{{EventDefinitions::EventCategory::OpenSCENARIO, fakeConditionalEvents}, + {EventDefinitions::EventCategory::Basic, fakeBasicEvents}}; + + NiceMock<FakeDataStore> fds; + SimulationSlave::EventNetwork eventNetwork(&fds); - SimulationSlave::EventNetwork eventNetwork; *(eventNetwork.GetArchivedEvents()) = fakeEvents; eventNetwork.RemoveOldEvents(actualTime); - EventContainer conditionalEvents = eventNetwork.GetArchivedEvents()->at(EventDefinitions::EventCategory::Conditional); + EventContainer conditionalEvents = eventNetwork.GetArchivedEvents()->at(EventDefinitions::EventCategory::OpenSCENARIO); EventContainer basicEvents = eventNetwork.GetArchivedEvents()->at(EventDefinitions::EventCategory::Basic); ASSERT_THAT(conditionalEvents, SizeIs(1)); diff --git a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/openPassSlave_Tests.pro b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/openPassSlave_Tests.pro index 642742307df2afc0fa178b537ed181196642db3c..8ba32cb7625ca0bb8fd4d32d670bb842217322b5 100644 --- a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/openPassSlave_Tests.pro +++ b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/openPassSlave_Tests.pro @@ -73,6 +73,7 @@ VEHICLEMODELIMPORTER_TESTS = \ EVENTDETECTOR_TESTS = \ $$UNIT_UNDER_TEST/importer/eventDetectorImporter.cpp \ $$UNIT_UNDER_TEST/framework/eventNetwork.cpp \ + $$UNIT_UNDER_TEST/framework/eventNetworkDataPublisher.cpp \ \ eventNetwork_Tests.cpp @@ -118,6 +119,11 @@ DIRECTORIES_TESTS = \ \ directories_Tests.cpp \ +PUBLISHER_TESTS = \ + $$UNIT_UNDER_TEST/framework/agentDataPublisher.cpp \ + \ + agentDataPublisher_Tests.cpp + SOURCES += \ $$DEPENDENCIES \ $$SLAVECONFIGIMPORTER_TESTS \ @@ -132,4 +138,5 @@ SOURCES += \ $$VEHICLEMODELIMPORTER_TESTS \ $$DIRECTORIES_TESTS \ $$COMMANDLINERPARSER_TESTS \ - $$AGENTSAMPLER_TESTS + $$AGENTSAMPLER_TESTS \ + $$PUBLISHER_TESTS diff --git a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/slaveConfigImporter_Tests.cpp b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/slaveConfigImporter_Tests.cpp index 2f76b28b84ae955f0cc16cc6d5fe6fd8f76686b7..31ee18d4253731f796ab9a7835b4b537ac00c2b2 100644 --- a/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/slaveConfigImporter_Tests.cpp +++ b/OpenPass_Test/unitTests/CoreFramework/OpenPassSlave/slaveConfigImporter_Tests.cpp @@ -15,6 +15,7 @@ #include "slaveConfigImporter.h" using ::testing::SizeIs; +using ::testing::Eq; using ::testing::Pair; using ::testing::UnorderedElementsAre; using ::testing::EndsWith; @@ -22,27 +23,27 @@ using ::testing::ElementsAre; using namespace Importer; -TEST(SlaveConfigImporter_UnitTests, ImportSpawnPointsConfigSuccessfully) +TEST(SlaveConfigImporter_UnitTests, ImportSpawnersSuccessfully) { QDomElement fakeDocumentRoot = documentRootFromString( "<root>" - "<SpawnPoint>" + "<Spawner>" "<Library>Test_Library</Library>" "<Type>PreRun</Type>" "<Priority>1</Priority>" - "</SpawnPoint>" - "<SpawnPoint>" + "</Spawner>" + "<Spawner>" "<Library>Test_Library</Library>" "<Type>Runtime</Type>" "<Priority>0</Priority>" "<Profile>ExampleProfile</Profile>" - "</SpawnPoint>" + "</Spawner>" "</root>" ); SpawnPointLibraryInfoCollection spawnPointsConfig {}; - EXPECT_NO_THROW(SlaveConfigImporter::ImportSpawnPointsConfig(fakeDocumentRoot, spawnPointsConfig)); + EXPECT_NO_THROW(SlaveConfigImporter::ImportSpawners(fakeDocumentRoot, spawnPointsConfig)); EXPECT_THAT(spawnPointsConfig, SizeIs(2)); const auto resultSpawnPointLibraryInfo1 = spawnPointsConfig.at(0); const auto resultSpawnPointLibraryInfo2 = spawnPointsConfig.at(1); @@ -57,37 +58,70 @@ TEST(SlaveConfigImporter_UnitTests, ImportSpawnPointsConfigSuccessfully) EXPECT_THAT(resultSpawnPointLibraryInfo2.profileName, "ExampleProfile"); } -TEST(SlaveConfigImporter_UnitTests, ImportSpawnPointConfigUnsuccessfully) +TEST(SlaveConfigImporter_UnitTests, ImportSpawnersUnsuccessfully) { QDomElement fakeDocumentRootMissingLibrary = documentRootFromString( "<root>" - "<SpawnPoint>" + "<Spawner>" "<Type>PreRun</Type>" "<Priority>1</Priority>" - "</SpawnPoint>" + "</Spawner>" "</root>" ); QDomElement fakeDocumentRootMissingType = documentRootFromString( "<root>" - "<SpawnPoint>" + "<Spawner>" "<Library>Test_Library</Library>" "<Priority>1</Priority>" - "</SpawnPoint>" + "</Spawner>" "</root>" ); QDomElement fakeDocumentRootMissingPriority = documentRootFromString( "<root>" - "<SpawnPoint>" + "<Spawner>" "<Library>Test_Library</Library>" "<Type>PreRun</Type>" - "</SpawnPoint>" + "</Spawner>" "</root>" ); SpawnPointLibraryInfoCollection spawnPointsConfig; - ASSERT_THROW(SlaveConfigImporter::ImportSpawnPointsConfig(fakeDocumentRootMissingLibrary, spawnPointsConfig), std::runtime_error); - ASSERT_THROW(SlaveConfigImporter::ImportSpawnPointsConfig(fakeDocumentRootMissingType, spawnPointsConfig), std::runtime_error); - ASSERT_THROW(SlaveConfigImporter::ImportSpawnPointsConfig(fakeDocumentRootMissingPriority, spawnPointsConfig), std::runtime_error); + ASSERT_THROW(SlaveConfigImporter::ImportSpawners(fakeDocumentRootMissingLibrary, spawnPointsConfig), std::runtime_error); + ASSERT_THROW(SlaveConfigImporter::ImportSpawners(fakeDocumentRootMissingType, spawnPointsConfig), std::runtime_error); + ASSERT_THROW(SlaveConfigImporter::ImportSpawners(fakeDocumentRootMissingPriority, spawnPointsConfig), std::runtime_error); +} + +TEST(SlaveConfigImporter_UnitTests, ImportObserversSuccessfully) +{ + QDomElement fakeDocumentRoot = documentRootFromString( + "<root>" + "<Observation>" + "<Library>Test_Library</Library>" + "<Parameters>" + "</Parameters>" + "</Observation>" + "<Observation>" + "<Library>Test_Library</Library>" + "<Parameters>" + "<Int Key=\"TestParameter\" Value=\"1\" />" + "</Parameters>" + "</Observation>" + "</root>" + ); + + ObservationInstanceCollection observations {}; + + EXPECT_NO_THROW(SlaveConfigImporter::ImportObservations(fakeDocumentRoot, observations)); + EXPECT_THAT(observations, SizeIs(2)); + const auto observation1 = observations.at(0); + const auto observation2 = observations.at(1); + + EXPECT_THAT(observation1.libraryName, "Test_Library"); + EXPECT_THAT(observation1.parameters, SizeIs(0)); + EXPECT_THAT(observation2.libraryName, "Test_Library"); + EXPECT_THAT(observation2.parameters, SizeIs(1)); + EXPECT_THAT(observation2.parameters.at(0).first, Eq("TestParameter")); + EXPECT_THAT(std::get<int>(std::get<openpass::parameter::internal::ParameterValue>(observation2.parameters.at(0).second)), Eq(1)); } TEST(SlaveConfigImporter_UnitTests, ImportExperimentConfigSuccessfully) @@ -97,31 +131,25 @@ TEST(SlaveConfigImporter_UnitTests, ImportExperimentConfigSuccessfully) "<ExperimentID>1337</ExperimentID>" "<NumberOfInvocations>5</NumberOfInvocations>" "<RandomSeed>12345</RandomSeed>" - "<LoggingGroups>" - "<LoggingGroup>Group1</LoggingGroup>" - "<LoggingGroup>Group2</LoggingGroup>" - "</LoggingGroups>" "</root>" ); ExperimentConfig experimentConfig; - EXPECT_NO_THROW(SlaveConfigImporter::ImportExperimentConfig(fakeDocumentRoot, experimentConfig)); + EXPECT_NO_THROW(SlaveConfigImporter::ImportExperiment(fakeDocumentRoot, experimentConfig)); EXPECT_THAT(experimentConfig.experimentId, 1337); EXPECT_THAT(experimentConfig.numberOfInvocations, 5); EXPECT_THAT(experimentConfig.randomSeed, 12345); - EXPECT_THAT(experimentConfig.loggingGroups, UnorderedElementsAre("Group1", "Group2")); } TEST(SlaveConfigImporter_UnitTests, ImportExperimentConfigUnsuccessfully) { - QDomElement fakeDocumentRootMissingLoggingTag = documentRootFromString( + QDomElement fakeDocumentRootMissingRandomSeed = documentRootFromString( "<root>" "<ExperimentID>1337</ExperimentID>" "<NumberOfInvocations>5</NumberOfInvocations>" - "<RandomSeed>12345</RandomSeed>" "</root>" ); @@ -130,7 +158,6 @@ TEST(SlaveConfigImporter_UnitTests, ImportExperimentConfigUnsuccessfully) "<ExperimentID>1337</ExperimentID>" "<NumberOfInvocations>abc</NumberOfInvocations>" "<RandomSeed>12345</RandomSeed>" - "<LoggingGroups/>" "</root>" ); @@ -139,52 +166,16 @@ TEST(SlaveConfigImporter_UnitTests, ImportExperimentConfigUnsuccessfully) "<Experimentid>1337</Experimentid>" "<NumberOfInvocations>5</NumberOfInvocations>" "<RandomSeed>12345</RandomSeed>" - "<LoggingGroups/>" "</root>" ); ExperimentConfig experimentConfig; - ASSERT_THROW(SlaveConfigImporter::ImportExperimentConfig(fakeDocumentRootMissingLoggingTag, experimentConfig), std::runtime_error); - ASSERT_THROW(SlaveConfigImporter::ImportExperimentConfig(fakeDocumentRootWrongDataType, experimentConfig), std::runtime_error); - ASSERT_THROW(SlaveConfigImporter::ImportExperimentConfig(fakeDocumentRootWrongTagName, experimentConfig), std::runtime_error); -} - -TEST(SlaveConfigImporter_UnitTests, ImportValidLoggingGroups_Succeeds) -{ - QDomElement fakeDocumentRoot = documentRootFromString( - "<root>" - "<LoggingGroups>" - "<LoggingGroup>Group01</LoggingGroup>" - "<LoggingGroup>Group02</LoggingGroup>" - "<LoggingGroup>AnotherGroup</LoggingGroup>" - "</LoggingGroups>" - "</root>" - ); - - - std::vector<std::string> loggingGroups; - - EXPECT_NO_THROW(SlaveConfigImporter::ImportLoggingGroups(fakeDocumentRoot, loggingGroups)); - - EXPECT_THAT(loggingGroups, UnorderedElementsAre("Group01", "Group02", "AnotherGroup")); + ASSERT_THROW(SlaveConfigImporter::ImportExperiment(fakeDocumentRootMissingRandomSeed, experimentConfig), std::runtime_error); + ASSERT_THROW(SlaveConfigImporter::ImportExperiment(fakeDocumentRootWrongDataType, experimentConfig), std::runtime_error); + ASSERT_THROW(SlaveConfigImporter::ImportExperiment(fakeDocumentRootWrongTagName, experimentConfig), std::runtime_error); } -TEST(SlaveConfigImporter_UnitTests, ImportEmptyLoggingGroupString_Fails) -{ - QDomElement fakeDocumentRootEmptyString = documentRootFromString( - "<root>" - "<LoggingGroups>" - "<LoggingGroup></LoggingGroup>" - "</LoggingGroups>" - "</root>" - ); - - std::vector<std::string> loggingGroups; - ASSERT_THROW(SlaveConfigImporter::ImportLoggingGroups(fakeDocumentRootEmptyString, loggingGroups), std::runtime_error); -} - - TEST(SlaveConfigImporter_UnitTests, ImportMissingLibraries_LoadsDefaults) { QDomElement fakeDocumentRoot = documentRootFromString("<root/>"); @@ -263,7 +254,7 @@ TEST(SlaveConfigImporter_UnitTests, ImportScenarioConfigSuccessfully) ScenarioConfig scenarioConfig; - EXPECT_NO_THROW(SlaveConfigImporter::ImportScenarioConfig(fakeDocumentRoot, "configs", scenarioConfig)); + EXPECT_NO_THROW(SlaveConfigImporter::ImportScenario(fakeDocumentRoot, "configs", scenarioConfig)); ASSERT_THAT(scenarioConfig.scenarioPath, EndsWith("configs/scenarioFile.xml")); } @@ -278,7 +269,7 @@ TEST(SlaveConfigImporter_UnitTests, ImportScenarioConfigUnsuccessfullyMissingTag ScenarioConfig scenarioConfig; - ASSERT_THROW(SlaveConfigImporter::ImportScenarioConfig(fakeDocumentRoot, "configs", scenarioConfig), std::runtime_error); + ASSERT_THROW(SlaveConfigImporter::ImportScenario(fakeDocumentRoot, "configs", scenarioConfig), std::runtime_error); } TEST(SlaveConfigImporter_UnitTests, ImportEnvironmentConfigSuccessfully) @@ -307,7 +298,7 @@ TEST(SlaveConfigImporter_UnitTests, ImportEnvironmentConfigSuccessfully) EnvironmentConfig environmentConfig; - EXPECT_NO_THROW(SlaveConfigImporter::ImportEnvironmentConfig(fakeDocumentRoot, environmentConfig)); + EXPECT_NO_THROW(SlaveConfigImporter::ImportEnvironment(fakeDocumentRoot, environmentConfig)); ASSERT_THAT(environmentConfig.timeOfDays, ElementsAre(Pair("12", 0.5), Pair("18", 0.5))); @@ -380,10 +371,10 @@ TEST(SlaveConfigImporter_UnitTests, ImportEnvironmentConfigUnsuccessfully) EnvironmentConfig environmentConfig; - ASSERT_THROW(SlaveConfigImporter::ImportEnvironmentConfig(fakeDocumentRootWrongProbabilities, environmentConfig), + ASSERT_THROW(SlaveConfigImporter::ImportEnvironment(fakeDocumentRootWrongProbabilities, environmentConfig), std::runtime_error); - ASSERT_THROW(SlaveConfigImporter::ImportEnvironmentConfig(fakeDocumentRootMissingAtLeastOneElement, environmentConfig), + ASSERT_THROW(SlaveConfigImporter::ImportEnvironment(fakeDocumentRootMissingAtLeastOneElement, environmentConfig), std::runtime_error); - ASSERT_THROW(SlaveConfigImporter::ImportEnvironmentConfig(fakeDocumentRootMissingTag, environmentConfig), + ASSERT_THROW(SlaveConfigImporter::ImportEnvironment(fakeDocumentRootMissingTag, environmentConfig), std::runtime_error); } diff --git a/OpenPass_Test/unitTests/CoreModules/BasicDataStore/basicDataStore_Tests.cpp b/OpenPass_Test/unitTests/CoreModules/BasicDataStore/basicDataStore_Tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9e5925d41ff8f1178831cf5adf6b9cf40aa7bd3 --- /dev/null +++ b/OpenPass_Test/unitTests/CoreModules/BasicDataStore/basicDataStore_Tests.cpp @@ -0,0 +1,639 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#include "Common/openPassTypes.h" +#include "Common/openPassUtils.h" + +#include "Common/runtimeInformation.h" + +#include "basicDataStoreImplementation.h" + +#include "fakeAgentDataPublisher.h" +#include "fakeCallback.h" +#include "fakeParameter.h" +#include "fakeStochastics.h" + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +using ::testing::_; +using ::testing::ElementsAre; +using ::testing::Eq; +using ::testing::NiceMock; +using ::testing::NotNull; +using ::testing::Pair; +using ::testing::Return; +using ::testing::ReturnRef; +using ::testing::SizeIs; +using ::testing::UnorderedElementsAre; + +using namespace openpass::type; + +const openpass::common::RuntimeInformation fakeRti{{openpass::common::Version{0, 0, 0}}, {"", "", ""}}; + +class TestBasicDataStore : public BasicDataStoreImplementation +{ +public: + TestBasicDataStore(const openpass::common::RuntimeInformation *runtimeInformation, const CallbackInterface *callbacks) : + BasicDataStoreImplementation(runtimeInformation, callbacks) + { + } + + AcyclicStore &GetAcyclicStore() + { + return acyclicStore; + } + + void SetAcyclicStore(AcyclicStore &newStore) + { + acyclicStore = newStore; + } + + StaticStore &GetStaticStore() + { + return staticStore; + } + + void SetStaticStore(StaticStore &newStore) + { + staticStore = newStore; + } + + CyclicStore &GetStore() + { + return cyclicStore; + } + + void SetStore(CyclicStore &newStore) + { + cyclicStore = newStore; + } + + StoreIndex<Timestamp> &GetTimestampIndex() + { + return timestampIndex; + } + + StoreIndex<EntityId> &GetEntityIdIndex() + { + return entityIdIndex; + } + + StoreIndex<Timestamp, EntityId> &GetTimeAndEntityIdIndex() + { + return timeAndEntityIdIndex; + } +}; + +class BasicDataStore_GetCyclic_Test : public ::testing::Test +{ +public: + BasicDataStore_GetCyclic_Test() + { + implementation = std::make_unique<BasicDataStoreImplementation>(&fakeRti, &fakeCallback); + + // fill some test data + + // value types according to openpass::datastore::Value + // bool, char, int, size_t, float, double, std::string and std::vector of each type + + implementation->PutCyclic(0, 0, "boolVal", true); + implementation->PutCyclic(0, 0, "charVal", 'a'); + implementation->PutCyclic(0, 0, "intVal", 1); + implementation->PutCyclic(0, 0, "sizeVal", static_cast<size_t>(2)); + implementation->PutCyclic(0, 0, "floatVal", 3.3f); + implementation->PutCyclic(0, 0, "doubleVal", 4.4); + implementation->PutCyclic(0, 0, "stringVal", "str"); + + implementation->PutCyclic(0, 0, "boolVec", std::vector<bool>{true, false}); + implementation->PutCyclic(0, 0, "charVec", std::vector<char>{'a'}); + implementation->PutCyclic(0, 0, "intVec", std::vector<char>{1, 2}); + implementation->PutCyclic(0, 0, "sizeVec", std::vector<size_t>{3, 4}); + implementation->PutCyclic(0, 0, "floatVec", std::vector<float>{5.5f, 6.6f}); + implementation->PutCyclic(0, 0, "doubleVec", std::vector<double>{7.7, 8.8}); + implementation->PutCyclic(0, 0, "stringVec", std::vector<std::string>{"str1", "str2"}); + + // data with additional timestamps and entity ids + + implementation->PutCyclic(0, 1, "intVal", 2); + implementation->PutCyclic(0, 2, "intVal", 3); + implementation->PutCyclic(1, 0, "intVal", 4); + implementation->PutCyclic(1, 1, "intVal", 5); + implementation->PutCyclic(1, 2, "intVal", 6); + implementation->PutCyclic(2, 0, "intVal", 7); + implementation->PutCyclic(2, 1, "intVal", 8); + implementation->PutCyclic(2, 2, "intVal", 9); + + implementation->PutCyclic(2, 2, "intVal2", 22); + implementation->PutCyclic(2, 2, "intVal2", 33); + implementation->PutCyclic(2, 2, "intVal2", 44); + implementation->PutCyclic(2, 2, "intVal2", 55); + + implementation->PutCyclic(3, 3, "intVal3", 66); + implementation->PutCyclic(3, 3, "intVal3", 77); + implementation->PutCyclic(3, 3, "intVal3", 88); + implementation->PutCyclic(3, 3, "intVal3", 99); + } + + std::unique_ptr<DataStoreInterface> implementation; + +private: + NiceMock<FakeCallback> fakeCallback; +}; + +class BasicDataStore_GetAcyclic_Test : public ::testing::Test +{ +public: + BasicDataStore_GetAcyclic_Test() + { + implementation = std::make_unique<BasicDataStoreImplementation>(&fakeRti, &fakeCallback); + + // fill some test data + Parameter params{{"param1", 1}, + {"param2", 2.0} + }; + + implementation->PutAcyclic(0, 0, "key1", Acyclic{"name", {{0, 1}}, {{2, 3}}, {{"param1", 1}}}); + implementation->PutAcyclic(0, 1, "key2", Acyclic{"name", {{1, 2}}, {{3, 4}}, {{"param2", 2.0}}}); + implementation->PutAcyclic(1, 0, "key1", Acyclic{"name", {{2, 3}}, {{4, 5}}, {{"param3", "paramVal3"}}}); + implementation->PutAcyclic(2, 0, "key1", Acyclic{"name", {{3, 4}}, {{5, 6}}, {{"param4", std::vector<int>{0, 1, 2}}}}); + } + + std::unique_ptr<DataStoreInterface> implementation; + +private: + NiceMock<FakeCallback> fakeCallback; +}; + +class BasicDataStore_Persistence_Test : public ::testing::Test +{ +public: + BasicDataStore_Persistence_Test() + { + implementation = std::make_unique<BasicDataStoreImplementation>(&fakeRti, &fakeCallback); + + implementation->PutStatic("nonpersistentKey", 0, false); + implementation->PutStatic("persistentKey", 1, true); + implementation->PutCyclic(0, 0, "cyclicKey", 2); + implementation->PutAcyclic(0, 0, "acyclicKey", Acyclic{"name", {{0, 1}}, {{2, 3}}, {{"param1", 1}}}); + } + + std::unique_ptr<DataStoreInterface> implementation; + +private: + NiceMock<FakeCallback> fakeCallback; +}; + +class BasicDataStore_GetStatic_Test : public ::testing::Test +{ +public: + BasicDataStore_GetStatic_Test() + { + implementation = std::make_unique<BasicDataStoreImplementation>(&fakeRti, &fakeCallback); + + // fill some test data + implementation->PutStatic("boolVal", true); + implementation->PutStatic("intVal", 1); + implementation->PutStatic("doubleVal", 2.0); + } + + std::unique_ptr<DataStoreInterface> implementation; + +private: + NiceMock<FakeCallback> fakeCallback; +}; + +class BasicDataStore_GetKeys_Test : public ::testing::Test +{ +public: + BasicDataStore_GetKeys_Test() + { + implementation = std::make_unique<BasicDataStoreImplementation>(&fakeRti, &fakeCallback); + + // fill some test data + implementation->PutStatic("level1a", 0); + implementation->PutStatic("level1b/level2a", 0); + implementation->PutStatic("level1b/level2b", 0); + implementation->PutStatic("level1c/level2c/level3a", 0); + implementation->PutStatic("level1c/level2c/level3b", 0); + + implementation->PutCyclic(0, 0, "level1c", 0); + implementation->PutCyclic(0, 0, "level1d/level2a", 0); + implementation->PutCyclic(0, 0, "level1d/level2b", 0); + implementation->PutCyclic(0, 0, "level1e/level2c", 0); + implementation->PutCyclic(0, 0, "level1e/level2d", 0); + implementation->PutCyclic(0, 1, "level1f", 0); + implementation->PutCyclic(1, 0, "level1g", 0); + implementation->PutCyclic(1, 0, "level1h", 0); + + //implementation->PutAcyclic(0, 0, "level1i", Acyclic{"name", {{0, 1}}, {{2, 3}}, {}}); + } + + std::unique_ptr<DataStoreInterface> implementation; + +private: + NiceMock<FakeCallback> fakeCallback; +}; + +namespace openpass::datastore { + +std::ostream& operator<<(std::ostream& stream, CyclicRow const& row) +{ + stream << "{timestamp = " << row.timestamp << ", entityId = " << row.entityId << ", key = " << row.key << " , value = "; + + std::visit(openpass::utils::FlatParameter::to_string([&stream](const std::string& valueStr) + { + stream << valueStr; + }, "|"), row.value); + + return stream << "}"; +} + +} + +TEST(BasicDataStore, PutCyclicData_StoresData) +{ + FakeCallback fakeCallback; + FakeStochastics fakeStochastics; + + const Timestamp timestamp = 0; + const EntityId agentId = 1; + const int value = 2; + const std::string key{"key/one/two"}; + const CyclicRow expectedRow{timestamp, agentId, key, value}; + + auto ds = std::make_unique<TestBasicDataStore>(&fakeRti, &fakeCallback); + + ASSERT_THAT(ds, NotNull()); + + ds->PutCyclic(timestamp, agentId, key, value); + + EXPECT_THAT(ds->GetStore().back(), Eq(expectedRow)); +} + +TEST(BasicDataStore, PutCyclicData_CreatesIndices) +{ + FakeCallback fakeCallback; + FakeStochastics fakeStochastics; + + const Timestamp timestamp = 0; + const EntityId agentId = 1; + const int value = 2; + const std::string key{"key/one/two"}; + const CyclicRow expectedRow{timestamp, agentId, key, value}; + const size_t expectedIndex = 0; + + auto ds = std::make_unique<TestBasicDataStore>(&fakeRti, &fakeCallback); + + ASSERT_THAT(ds, NotNull()); + + ds->PutCyclic(timestamp, agentId, key, value); + + auto &timeIdx = ds->GetTimestampIndex(); + auto &entityIdx = ds->GetEntityIdIndex(); + auto &timeAndEntityIdx = ds->GetTimeAndEntityIdIndex(); + + auto firstTimeIdx = timeIdx.equal_range(timestamp).first; + auto firstEntityIdx = entityIdx.equal_range(agentId).first; + auto firstTimeAndEntityIdx = timeAndEntityIdx.equal_range({timestamp, agentId}).first; + + EXPECT_THAT(firstTimeIdx->second, Eq(expectedIndex)); + EXPECT_THAT(firstEntityIdx->second, Eq(expectedIndex)); + EXPECT_THAT(firstTimeAndEntityIdx->second, Eq(expectedIndex)); +} + +TEST_F(BasicDataStore_GetCyclic_Test, GivenTimestampAndEntityIdAndKey_ReturnsCorrectData) +{ + const auto result1 = implementation->GetCyclic(1, 1, "intVal"); + const auto result2 = implementation->GetCyclic(2, 0, "intVal"); + + ASSERT_THAT(result1->size(), Eq(1)); + ASSERT_THAT(result2->size(), Eq(1)); + EXPECT_THAT(result1->at(0), Eq(CyclicRow{1, 1, "intVal", 5})); + EXPECT_THAT(result2->at(0), Eq(CyclicRow{2, 0, "intVal", 7})); +} + +TEST_F(BasicDataStore_GetCyclic_Test, GivenTimestampAndKey_ReturnsCorrectData) +{ + const auto result = implementation->GetCyclic(1, std::nullopt, "intVal"); + + ASSERT_THAT(result->size(), Eq(3)); + EXPECT_THAT(result->at(0), Eq(CyclicRow{1, 0, "intVal", 4})); + EXPECT_THAT(result->at(1), Eq(CyclicRow{1, 1, "intVal", 5})); + EXPECT_THAT(result->at(2), Eq(CyclicRow{1, 2, "intVal", 6})); +} + +TEST_F(BasicDataStore_GetCyclic_Test, GivenEntityIdAndKey_ReturnsCorrectResult) +{ + const auto result = implementation->GetCyclic(std::nullopt, 1, "intVal"); + + ASSERT_THAT(result->size(), Eq(3)); + EXPECT_THAT(result->at(0), Eq(CyclicRow{0, 1, "intVal", 2})); + EXPECT_THAT(result->at(1), Eq(CyclicRow{1, 1, "intVal", 5})); + EXPECT_THAT(result->at(2), Eq(CyclicRow{2, 1, "intVal", 8})); +} + +TEST_F(BasicDataStore_GetCyclic_Test, GivenKey_ReturnsCorrectResult) +{ + const auto result = implementation->GetCyclic(std::nullopt, std::nullopt, "intVal2"); + + ASSERT_THAT(result->size(), Eq(4)); + EXPECT_THAT(result->at(0), Eq(CyclicRow{2, 2, "intVal2", 22})); + EXPECT_THAT(result->at(1), Eq(CyclicRow{2, 2, "intVal2", 33})); + EXPECT_THAT(result->at(2), Eq(CyclicRow{2, 2, "intVal2", 44})); + EXPECT_THAT(result->at(3), Eq(CyclicRow{2, 2, "intVal2", 55})); +} + +TEST_F(BasicDataStore_GetCyclic_Test, GivenTimestampAndEntityIdAndWildcard_ReturnsCorrectResult) +{ + const auto result = implementation->GetCyclic(2, 2, "*"); + + ASSERT_THAT(result->size(), Eq(5)); + EXPECT_THAT(result->at(0), Eq(CyclicRow{2, 2, "intVal", 9})); + EXPECT_THAT(result->at(1), Eq(CyclicRow{2, 2, "intVal2", 22})); + EXPECT_THAT(result->at(2), Eq(CyclicRow{2, 2, "intVal2", 33})); + EXPECT_THAT(result->at(3), Eq(CyclicRow{2, 2, "intVal2", 44})); + EXPECT_THAT(result->at(4), Eq(CyclicRow{2, 2, "intVal2", 55})); +} + +TEST_F(BasicDataStore_GetCyclic_Test, GivenTimestampAndWildcard_ReturnsCorrectResult) +{ + const auto result = implementation->GetCyclic(2, std::nullopt, "*"); + + ASSERT_THAT(result->size(), Eq(7)); + EXPECT_THAT(result->at(0), Eq(CyclicRow{2, 0, "intVal", 7})); + EXPECT_THAT(result->at(1), Eq(CyclicRow{2, 1, "intVal", 8})); + EXPECT_THAT(result->at(2), Eq(CyclicRow{2, 2, "intVal", 9})); + EXPECT_THAT(result->at(3), Eq(CyclicRow{2, 2, "intVal2", 22})); + EXPECT_THAT(result->at(4), Eq(CyclicRow{2, 2, "intVal2", 33})); + EXPECT_THAT(result->at(5), Eq(CyclicRow{2, 2, "intVal2", 44})); + EXPECT_THAT(result->at(6), Eq(CyclicRow{2, 2, "intVal2", 55})); +} + +TEST_F(BasicDataStore_GetCyclic_Test, GivenEntityIdAndWildcard_ReturnsCorrectResult) +{ + const auto result = implementation->GetCyclic(std::nullopt, 2, "*"); + + ASSERT_THAT(result->size(), Eq(7)); + EXPECT_THAT(result->at(0), Eq(CyclicRow{0, 2, "intVal", 3})); + EXPECT_THAT(result->at(1), Eq(CyclicRow{1, 2, "intVal", 6})); + EXPECT_THAT(result->at(2), Eq(CyclicRow{2, 2, "intVal", 9})); + EXPECT_THAT(result->at(3), Eq(CyclicRow{2, 2, "intVal2", 22})); + EXPECT_THAT(result->at(4), Eq(CyclicRow{2, 2, "intVal2", 33})); + EXPECT_THAT(result->at(5), Eq(CyclicRow{2, 2, "intVal2", 44})); + EXPECT_THAT(result->at(6), Eq(CyclicRow{2, 2, "intVal2", 55})); +} + +TEST_F(BasicDataStore_GetCyclic_Test, GivenWildcard_ReturnsCorrectResult) +{ + const auto result = implementation->GetCyclic(std::nullopt, std::nullopt, "*"); + + ASSERT_THAT(result->size(), Eq(30)); + + EXPECT_THAT(result->at(0), Eq(CyclicRow{0, 0, "boolVal", true})); + EXPECT_THAT(result->at(1), Eq(CyclicRow{0, 0, "charVal", 'a'})); + EXPECT_THAT(result->at(2), Eq(CyclicRow{0, 0, "intVal", 1})); + EXPECT_THAT(result->at(3), Eq(CyclicRow{0, 0, "sizeVal", static_cast<size_t>(2)})); + EXPECT_THAT(result->at(4), Eq(CyclicRow{0, 0, "floatVal", 3.3f})); + EXPECT_THAT(result->at(5), Eq(CyclicRow{0, 0, "doubleVal", 4.4})); + EXPECT_THAT(result->at(6), Eq(CyclicRow{0, 0, "stringVal", "str"})); + + EXPECT_THAT(result->at(7), Eq(CyclicRow{0, 0, "boolVec", std::vector<bool>{true, false}})); + EXPECT_THAT(result->at(8), Eq(CyclicRow{0, 0, "charVec", std::vector<char>{'a'}})); + EXPECT_THAT(result->at(9), Eq(CyclicRow{0, 0, "intVec", std::vector<char>{1, 2}})); + EXPECT_THAT(result->at(10), Eq(CyclicRow{0, 0, "sizeVec", std::vector<size_t>{3, 4}})); + EXPECT_THAT(result->at(11), Eq(CyclicRow{0, 0, "floatVec", std::vector<float>{5.5f, 6.6f}})); + EXPECT_THAT(result->at(12), Eq(CyclicRow{0, 0, "doubleVec", std::vector<double>{7.7, 8.8}})); + EXPECT_THAT(result->at(13), Eq(CyclicRow{0, 0, "stringVec", std::vector<std::string>{"str1", "str2"}})); + + EXPECT_THAT(result->at(14), Eq(CyclicRow{0, 1, "intVal", 2})); + EXPECT_THAT(result->at(15), Eq(CyclicRow{0, 2, "intVal", 3})); + EXPECT_THAT(result->at(16), Eq(CyclicRow{1, 0, "intVal", 4})); + EXPECT_THAT(result->at(17), Eq(CyclicRow{1, 1, "intVal", 5})); + EXPECT_THAT(result->at(18), Eq(CyclicRow{1, 2, "intVal", 6})); + EXPECT_THAT(result->at(19), Eq(CyclicRow{2, 0, "intVal", 7})); + EXPECT_THAT(result->at(20), Eq(CyclicRow{2, 1, "intVal", 8})); + EXPECT_THAT(result->at(21), Eq(CyclicRow{2, 2, "intVal", 9})); + + EXPECT_THAT(result->at(22), Eq(CyclicRow{2, 2, "intVal2", 22})); + EXPECT_THAT(result->at(23), Eq(CyclicRow{2, 2, "intVal2", 33})); + EXPECT_THAT(result->at(24), Eq(CyclicRow{2, 2, "intVal2", 44})); + EXPECT_THAT(result->at(25), Eq(CyclicRow{2, 2, "intVal2", 55})); + + EXPECT_THAT(result->at(26), Eq(CyclicRow{3, 3, "intVal3", 66})); + EXPECT_THAT(result->at(27), Eq(CyclicRow{3, 3, "intVal3", 77})); + EXPECT_THAT(result->at(28), Eq(CyclicRow{3, 3, "intVal3", 88})); + EXPECT_THAT(result->at(29), Eq(CyclicRow{3, 3, "intVal3", 99})); + +} + +TEST_F(BasicDataStore_GetCyclic_Test, Result_IsIteratable) +{ + const auto result = implementation->GetCyclic(std::nullopt, std::nullopt, "intVal3"); + + ASSERT_THAT(result->size(), Eq(4)); + + int expectedValue = 66; + for (const auto& entryRef : *result) + { + const auto& entry = entryRef.get(); + EXPECT_THAT(entry, Eq(CyclicRow{3, 3, "intVal3", expectedValue})); + expectedValue += 11; + } +} + +TEST(BasicDataStore, PutAcyclicData_StoresData) +{ + FakeCallback fakeCallback; + FakeStochastics fakeStochastics; + + const Timestamp timestamp = 0; + const EntityId agentId = 1; + + const std::string name{"name"}; + const TriggeringEntities triggeringEntities{{0, 1}}; + const AffectedEntities affectedEntities{{2, 3}}; + const std::string key{"key/one/two"}; + const Parameter params{{"key", "value"}}; + const Acyclic acyclic{name, triggeringEntities, affectedEntities, params}; + const AcyclicRow expectedRow{timestamp, agentId, key, acyclic}; + + auto ds = std::make_unique<TestBasicDataStore>(&fakeRti, &fakeCallback); + + ASSERT_THAT(ds, NotNull()); + + ds->PutAcyclic(timestamp, agentId, key, acyclic); + + EXPECT_THAT(ds->GetAcyclicStore().back(), Eq(expectedRow)); +} + +TEST_F(BasicDataStore_GetAcyclic_Test, GivenKey_ReturnsCorrectResult) +{ + const auto result = implementation->GetAcyclic(std::nullopt, std::nullopt, "key1"); + + ASSERT_THAT(result->size(), Eq(3)); + + EXPECT_THAT(result->at(0), Eq(AcyclicRow{0, 0, "key1", Acyclic{"name", {{0, 1}}, {{2, 3}}, {{"param1", 1}}}})); + EXPECT_THAT(result->at(1), Eq(AcyclicRow{1, 0, "key1", Acyclic{"name", {{2, 3}}, {{4, 5}}, {{"param3", "paramVal3"}}}})); + EXPECT_THAT(result->at(2), Eq(AcyclicRow{2, 0, "key1", Acyclic{"name", {{3, 4}}, {{5, 6}}, {{"param4", std::vector<int>{0, 1, 2}}}}})); +} + +TEST_F(BasicDataStore_GetAcyclic_Test, GivenWildcard_ReturnsCorrectResult) +{ + const auto result = implementation->GetAcyclic(std::nullopt, std::nullopt, "*"); + + ASSERT_THAT(result->size(), Eq(4)); + + EXPECT_THAT(result->at(0), Eq(AcyclicRow{0, 0, "key1", Acyclic{"name", {{0, 1}}, {{2, 3}}, {{"param1", 1}}}})); + EXPECT_THAT(result->at(1), Eq(AcyclicRow{0, 1, "key2", Acyclic{"name", {{1, 2}}, {{3, 4}}, {{"param2", 2.0}}}})); + EXPECT_THAT(result->at(2), Eq(AcyclicRow{1, 0, "key1", Acyclic{"name", {{2, 3}}, {{4, 5}}, {{"param3", "paramVal3"}}}})); + EXPECT_THAT(result->at(3), Eq(AcyclicRow{2, 0, "key1", Acyclic{"name", {{3, 4}}, {{5, 6}}, {{"param4", std::vector<int>{0, 1, 2}}}}})); +} + +TEST(BasicDataStore, PutStaticData_StoresData) +{ + FakeCallback fakeCallback; + + const int value = 1; + const std::string key{"key/one/two"}; + + auto ds = std::make_unique<TestBasicDataStore>(&fakeRti, &fakeCallback); + + ASSERT_THAT(ds, NotNull()); + + ds->PutStatic(key, value); + + Value result; + ASSERT_NO_THROW(result = std::get<Value>(ds->GetStaticStore().at(key))); + EXPECT_THAT(result, Eq(Value{value})); +} + +TEST(BasicDataStore, PutStaticDataTwiceUsingSameKey_IgnoresSecondCall) +{ + FakeCallback fakeCallback; + + const int value1 = 1; + const int value2 = 2; + const std::string key{"key/one/two"}; + + auto ds = std::make_unique<TestBasicDataStore>(&fakeRti, &fakeCallback); + + ASSERT_THAT(ds, NotNull()); + + ds->PutStatic(key, value1); + ds->PutStatic(key, value2); + + Value result; + ASSERT_NO_THROW(result = std::get<Value>(ds->GetStaticStore().at(key))); + EXPECT_THAT(result, Eq(Value{value1})); +} + +TEST_F(BasicDataStore_Persistence_Test, FixtureSetup_StoresData) +{ + const auto acyclicResult = implementation->GetAcyclic(std::nullopt, std::nullopt, "acyclicKey"); + const auto cyclicResult = implementation->GetCyclic(std::nullopt, std::nullopt, "cyclicKey"); + const auto staticPersistentResult = implementation->GetStatic("persistentKey"); + const auto staticNonPersistentResult = implementation->GetStatic("nonpersistentKey"); + + ASSERT_THAT(acyclicResult->size(), Eq(1)); + ASSERT_THAT(cyclicResult->size(), Eq(1)); + ASSERT_THAT(staticPersistentResult, SizeIs(1)); + ASSERT_THAT(staticNonPersistentResult, SizeIs(1)); +} + +TEST_F(BasicDataStore_Persistence_Test, Clear_KeepsPersistentStaticData) +{ + implementation->Clear(); + + const auto staticPersistentResult = implementation->GetStatic("persistentKey"); + + ASSERT_THAT(staticPersistentResult, SizeIs(1)); + EXPECT_THAT(staticPersistentResult.at(0), Eq(Value{1})); +} + +TEST_F(BasicDataStore_Persistence_Test, Clear_DeletesNonPersisentData) +{ + implementation->Clear(); + + const auto acyclicResult = implementation->GetAcyclic(std::nullopt, std::nullopt, "acyclicKey"); + const auto cyclicResult = implementation->GetCyclic(std::nullopt, std::nullopt, "cyclicKey"); + const auto staticNonPersistentResult = implementation->GetStatic("nonpersistentKey"); + + ASSERT_THAT(acyclicResult->size(), Eq(0)); + ASSERT_THAT(cyclicResult->size(), Eq(0)); + ASSERT_THAT(staticNonPersistentResult, SizeIs(0)); +} + +TEST_F(BasicDataStore_GetStatic_Test, GivenKey_ReturnsValue) +{ + const auto boolResult = implementation->GetStatic("boolVal"); + const auto intResult = implementation->GetStatic("intVal"); + const auto doubleResult = implementation->GetStatic("doubleVal"); + + ASSERT_THAT(boolResult, SizeIs(1)); + ASSERT_THAT(intResult, SizeIs(1)); + ASSERT_THAT(doubleResult, SizeIs(1)); + + EXPECT_THAT(boolResult.at(0), Eq(Value{true})); + EXPECT_THAT(intResult.at(0), Eq(Value{1})); + EXPECT_THAT(doubleResult.at(0), Eq(Value{2.0})); +} + +TEST_F(BasicDataStore_GetStatic_Test, GivenWildcard_ReturnsEmptyResult) +{ + const auto result = implementation->GetStatic("*"); + + ASSERT_THAT(result, SizeIs(0)); +} + +TEST_F(BasicDataStore_GetKeys_Test, StaticsKey_ReturnsCorrectKeys) +{ + const auto keys1 = implementation->GetKeys("Statics"); + const auto keys2 = implementation->GetKeys("Statics/level1a"); + const auto keys3 = implementation->GetKeys("Statics/level1b"); + const auto keys4 = implementation->GetKeys("Statics/level1c/level2c"); + + EXPECT_THAT(keys1, ElementsAre("level1a", "level1b", "level1c")); + EXPECT_THAT(keys2, SizeIs(0)); + EXPECT_THAT(keys3, ElementsAre("level2a", "level2b")); + EXPECT_THAT(keys4, ElementsAre("level3a", "level3b")); +} + +TEST_F(BasicDataStore_GetKeys_Test, CyclicsKeyWithoutTimestampAndEntityId_ReturnsTimestamps) +{ + const auto keys1 = implementation->GetKeys("Cyclics"); + + EXPECT_THAT(keys1, ElementsAre("0", "1")); + +} + +TEST_F(BasicDataStore_GetKeys_Test, CyclicsKeyWithTimestampAndEntityId_ReturnsKeys) +{ + const auto keys1 = implementation->GetKeys("Cyclics/0/0"); + const auto keys2 = implementation->GetKeys("Cyclics/0/0/level1e"); + const auto keys3 = implementation->GetKeys("Cyclics/0/1"); + const auto keys4 = implementation->GetKeys("Cyclics/1/0"); + + EXPECT_THAT(keys1, ElementsAre("level1c", "level1d", "level1e")); + EXPECT_THAT(keys2, ElementsAre("level2c", "level2d")); + EXPECT_THAT(keys3, ElementsAre("level1f")); + EXPECT_THAT(keys4, ElementsAre("level1g", "level1h")); + +} + +TEST(BasicDataStore_Constants, Wildcard_IsSize1) +{ + ASSERT_THAT(WILDCARD, SizeIs(1)); +} + +TEST(BasicDataStore_Constants, Separator_IsSize1) +{ + ASSERT_THAT(SEPARATOR, SizeIs(1)); +} diff --git a/OpenPass_Test/unitTests/CoreModules/BasicDataStore/basicDataStore_Tests.pro b/OpenPass_Test/unitTests/CoreModules/BasicDataStore/basicDataStore_Tests.pro new file mode 100644 index 0000000000000000000000000000000000000000..a5d477c214b386048d5b4da5bb57fe8ed3369b66 --- /dev/null +++ b/OpenPass_Test/unitTests/CoreModules/BasicDataStore/basicDataStore_Tests.pro @@ -0,0 +1,30 @@ +# /********************************************************************* +# * Copyright (c) 2020 in-tech GmbH +# * +# * This program and the accompanying materials are made +# * available under the terms of the Eclipse Public License 2.0 +# * which is available at https://www.eclipse.org/legal/epl-2.0/ +# * +# * SPDX-License-Identifier: EPL-2.0 +# **********************************************************************/ + +CONFIG += OPENPASS_GTEST \ + OPENPASS_GTEST_DEFAULT_MAIN + +include(../../../testing.pri) + +UNIT_UNDER_TEST = $$OPEN_SRC/CoreModules/BasicDataStore + +#win32:QMAKE_CXXFLAGS += -Wa,-mbig-obj + +INCLUDEPATH += \ + $$UNIT_UNDER_TEST + +HEADERS += \ + $$OPEN_SRC/Interfaces/dataStoreInterface.h \ + $$UNIT_UNDER_TEST/basicDataStoreImplementation.h + +SOURCES += \ + $$OPEN_SRC/Common/vector2d.cpp \ + $$UNIT_UNDER_TEST/basicDataStoreImplementation.cpp \ + basicDataStore_Tests.cpp diff --git a/OpenPass_Test/unitTests/CoreModules/EventDetector/ConditionalEventDetector_Tests.cpp b/OpenPass_Test/unitTests/CoreModules/EventDetector/ConditionalEventDetector_Tests.cpp index e3212d87d0cd64cbea67308a0a85393ee0d60c31..5a78eee4014d57e64734e4c264c67e4d40768f70 100644 --- a/OpenPass_Test/unitTests/CoreModules/EventDetector/ConditionalEventDetector_Tests.cpp +++ b/OpenPass_Test/unitTests/CoreModules/EventDetector/ConditionalEventDetector_Tests.cpp @@ -71,7 +71,7 @@ TEST_P(ConditionalTimeTriggerTest, TriggerEventInsertion_AddsEventIfNecessary) INSTANTIATE_TEST_CASE_P(ConditionalTimeTrigger_AppropriatelyInsertsEventsIntoNetwork, ConditionalTimeTriggerTest, - Values( + ::testing::Values( ConditionalTimeTriggerTest_Data{800, 0}, ConditionalTimeTriggerTest_Data{1000, 0}, ConditionalTimeTriggerTest_Data{1200, 1} @@ -112,7 +112,7 @@ TEST_P(ReachPositionConditionTest, TriggerEventInsertion_AddsEventIfNecessary) { openScenario::ConditionalEventDetectorInformation testConditionalEventDetectorInformation; testConditionalEventDetectorInformation.numberOfExecutions = -1; - testConditionalEventDetectorInformation.actorInformation.triggeringAgentsAsActors.emplace(true); + testConditionalEventDetectorInformation.actorInformation.actorIsTriggeringEntity = true; const std::vector<std::string> actors {"mockAgent1", "mockAgent2"}; testConditionalEventDetectorInformation.actorInformation.actors.emplace(actors); @@ -178,7 +178,7 @@ TEST_P(ReachPositionConditionTest, TriggerEventInsertion_AddsEventIfNecessary) INSTANTIATE_TEST_CASE_P(ReachPositionCondition_AppropriatelyInsertsEventsIntoNetwork, ReachPositionConditionTest, - Values( + ::testing::Values( ReachPositionCondition_Data{20.0 , -1.0 , "fakeRoad" , true, 0, 0}, ReachPositionCondition_Data{-20.0, 10.0 , "fakeRoad" , true, 0, 0}, ReachPositionCondition_Data{20.0 , 100.0, "fakeRoad" , false, 2, 2}, @@ -212,7 +212,7 @@ TEST_P(RelativeSpeedConditionTest, TriggerEventInsertion_AddsEventIfNecessary) { openScenario::ConditionalEventDetectorInformation testConditionalEventDetectorInformation; testConditionalEventDetectorInformation.numberOfExecutions = -1; - testConditionalEventDetectorInformation.actorInformation.triggeringAgentsAsActors.emplace(true); + testConditionalEventDetectorInformation.actorInformation.actorIsTriggeringEntity = true; const std::vector<std::string> actors {}; testConditionalEventDetectorInformation.actorInformation.actors.emplace(actors); @@ -266,7 +266,7 @@ TEST_P(RelativeSpeedConditionTest, TriggerEventInsertion_AddsEventIfNecessary) INSTANTIATE_TEST_CASE_P(RelativeSpeedCondition_AppropriatelyInsertsEventsIntoNetwork, RelativeSpeedConditionTest, - Values( + ::testing::Values( RelativeSpeedCondition_Data{"notExisting" , DontCare<double>(), DontCare<openScenario::Rule>() , 20.0, 20.0, DontCare<double>(), true , 0}, RelativeSpeedCondition_Data{"referenceAgent" , -10.0 , DontCare<openScenario::Rule>() , 0.0, 0.0, 20.0 , false , 1}, RelativeSpeedCondition_Data{"referenceAgent" , 10.0 , openScenario::Rule::LessThan , 10.0, 10.0, 19.9 , false , 1}, @@ -303,7 +303,7 @@ TEST_P(RelativeLaneConditionTest, TriggerEventInsertion_AddsEventIfNecessary) { openScenario::ConditionalEventDetectorInformation testConditionalEventDetectorInformation; testConditionalEventDetectorInformation.numberOfExecutions = -1; - testConditionalEventDetectorInformation.actorInformation.triggeringAgentsAsActors.emplace(true); + testConditionalEventDetectorInformation.actorInformation.actorIsTriggeringEntity = true; const std::vector<std::string> actors {}; testConditionalEventDetectorInformation.actorInformation.actors.emplace(actors); @@ -357,7 +357,7 @@ TEST_P(RelativeLaneConditionTest, TriggerEventInsertion_AddsEventIfNecessary) INSTANTIATE_TEST_CASE_P(RelativeLaneCondition_AppropriatelyInsertsEventsIntoNetwork, RelativeLaneConditionTest, - Values( + ::testing::Values( // -----------------------| entityName | deltaLane | deltaS | tolerance | triggeringAgentLane | triggeringAgentSCoordinate | referenceAgentLane | referenceAgentSCoordinate | expectError | expectNumberOfEvents RelativeLaneCondition_Data{"notExisting" , DontCare<int>(), DontCare<double>(), DontCare<double>(), DontCare<int>() , DontCare<double>() , DontCare<int>() , DontCare<double>() , true , 0 }, RelativeLaneCondition_Data{"referenceAgentOnSameRoad", -1 , 30.0 , 10.0 , 0 , 25.0 , -1 , 0.0 , false , 0 }, @@ -388,7 +388,7 @@ TEST_P(TimeToCollisionConditionTest, TriggerEventInsertion_AddsEventIfNecessary) { openScenario::ConditionalEventDetectorInformation testConditionalEventDetectorInformation; testConditionalEventDetectorInformation.numberOfExecutions = -1; - testConditionalEventDetectorInformation.actorInformation.triggeringAgentsAsActors.emplace(true); + testConditionalEventDetectorInformation.actorInformation.actorIsTriggeringEntity = true; const std::vector<std::string> actors {}; testConditionalEventDetectorInformation.actorInformation.actors.emplace(actors); @@ -457,7 +457,7 @@ TEST_P(TimeToCollisionConditionTest, TriggerEventInsertion_AddsEventIfNecessary) INSTANTIATE_TEST_CASE_P(TimeToCollisionCondition_AppropriatelyInsertsEventsIntoNetwork, TimeToCollisionConditionTest, - Values( + ::testing::Values( // ------------------------- | entityName | targetTTC | rule | expectError | expectNumberOfEvents | TimeToCollisionCondition_Data{"notExisting" , 1.0 , openScenario::Rule::LessThan , true , 0 }, TimeToCollisionCondition_Data{"referenceAgent" , 1.0 , openScenario::Rule::GreaterThan , false , 1 }, @@ -489,7 +489,7 @@ TEST_P(TimeHeadwayConditionTest, TriggerEventInsertionFreeSpaceTrue_AddsEventIfN { openScenario::ConditionalEventDetectorInformation testConditionalEventDetectorInformation; testConditionalEventDetectorInformation.numberOfExecutions = -1; - testConditionalEventDetectorInformation.actorInformation.triggeringAgentsAsActors.emplace(true); + testConditionalEventDetectorInformation.actorInformation.actorIsTriggeringEntity = true; const std::vector<std::string> actors {}; testConditionalEventDetectorInformation.actorInformation.actors.emplace(actors); @@ -546,7 +546,7 @@ TEST_P(TimeHeadwayConditionTest, TriggerEventInsertionFreeSpaceFalse_AddsEventIf { openScenario::ConditionalEventDetectorInformation testConditionalEventDetectorInformation; testConditionalEventDetectorInformation.numberOfExecutions = -1; - testConditionalEventDetectorInformation.actorInformation.triggeringAgentsAsActors.emplace(true); + testConditionalEventDetectorInformation.actorInformation.actorIsTriggeringEntity = true; const std::vector<std::string> actors {}; testConditionalEventDetectorInformation.actorInformation.actors.emplace(actors); @@ -601,7 +601,7 @@ TEST_P(TimeHeadwayConditionTest, TriggerEventInsertionFreeSpaceFalse_AddsEventIf INSTANTIATE_TEST_CASE_P(TimeHeadwayCondition_AppropriatelyInsertsEventsIntoNetwork, TimeHeadwayConditionTest, - Values( + ::testing::Values( // --------------------- | entityName | targetTHW | rule | expectError | expectNumberOfEvents | TimeHeadwayCondition_Data{"notExisting" , 1.0 , openScenario::Rule::LessThan , true , 0 }, TimeHeadwayCondition_Data{"referenceAgent" , 1.0 , openScenario::Rule::GreaterThan , false , 1 }, diff --git a/OpenPass_Test/unitTests/CoreModules/Observation_Log/observationLog_Tests.cpp b/OpenPass_Test/unitTests/CoreModules/Observation_Log/observationLog_Tests.cpp index 96dafe025aab93c4e8fee420cdf683547c809753..6b3284167251e94aa730056fc511a4aa942f7a05 100644 --- a/OpenPass_Test/unitTests/CoreModules/Observation_Log/observationLog_Tests.cpp +++ b/OpenPass_Test/unitTests/CoreModules/Observation_Log/observationLog_Tests.cpp @@ -45,7 +45,7 @@ TEST(ObservationCyclics_Test, GetTimeSteps_ReturnsCorrectTimesteps) cyclics.Insert(100, "ParameterA", "345"); cyclics.Insert(150, "ParameterB", "456"); - std::vector<int> timesteps = *cyclics.GetTimeSteps(); + const auto& timesteps = cyclics.GetTimeSteps(); ASSERT_THAT(timesteps, ElementsAre(0, 100, 150)); } @@ -116,39 +116,6 @@ TEST(ObservationCyclics_Test, GetSamplesLineSamplesNotUntilEnd_ReturnsLineWithEm ASSERT_THAT(samplesLine, Eq(", 789, ")); } -TEST(RunStatisticCalculation_Test, CalculateTotalDistanceTraveled_SetsCorrectDistances) -{ - NiceMock<FakeWorld> fakeWorld; - - NiceMock<FakeAgent> fakeEgo; - ON_CALL(fakeEgo, GetDistanceTraveled()).WillByDefault(Return(100.0)); - ON_CALL(fakeWorld, GetEgoAgent()).WillByDefault(Return(&fakeEgo)); - - NiceMock<FakeAgent> fakeAgent1; - ON_CALL(fakeAgent1, GetDistanceTraveled()).WillByDefault(Return(50.0)); - ON_CALL(fakeAgent1, IsEgoAgent()).WillByDefault(Return(false)); - - NiceMock<FakeAgent> fakeAgent2; - ON_CALL(fakeAgent2, GetDistanceTraveled()).WillByDefault(Return(8.0)); - ON_CALL(fakeAgent2, IsEgoAgent()).WillByDefault(Return(false)); - - NiceMock<FakeAgent> fakeAgent3; - ON_CALL(fakeAgent3, GetDistanceTraveled()).WillByDefault(Return(0.3)); - ON_CALL(fakeAgent3, IsEgoAgent()).WillByDefault(Return(false)); - - std::map<int, AgentInterface*> agents{ {0, &fakeEgo}, {1, &fakeAgent1}, {2, &fakeAgent2} }; - std::list<const AgentInterface*> removedAgents{&fakeAgent3}; - ON_CALL(fakeWorld, GetAgents()).WillByDefault(ReturnRef(agents)); - ON_CALL(fakeWorld, GetRemovedAgents()).WillByDefault(ReturnRef(removedAgents)); - - RunStatistic runStatistic{0}; - - RunStatisticCalculation::CalculateTotalDistanceTraveled(runStatistic, &fakeWorld); - - ASSERT_THAT(runStatistic.EgoDistanceTraveled, DoubleEq(100.0)); - ASSERT_THAT(runStatistic.TotalDistanceTraveled, DoubleEq(158.3)); -} - TEST(RunStatisticCalculation_Test, DetermineEgoCollisionWithEgoCollision_SetsEgoCollisionTrue) { NiceMock<FakeWorld> fakeWorld; diff --git a/OpenPass_Test/unitTests/CoreModules/Observation_Log/observationLog_Tests.pro b/OpenPass_Test/unitTests/CoreModules/Observation_Log/observationLog_Tests.pro index 0db586fcbdfc04d0b659b512336ecea80ae8f091..73ae69acf067fd5782f83f101e8b2f00378fdf15 100644 --- a/OpenPass_Test/unitTests/CoreModules/Observation_Log/observationLog_Tests.pro +++ b/OpenPass_Test/unitTests/CoreModules/Observation_Log/observationLog_Tests.pro @@ -34,4 +34,5 @@ SOURCES += \ $$UNIT_UNDER_TEST/observationFileHandler.cpp \ $$UNIT_UNDER_TEST/runStatistic.cpp \ $$UNIT_UNDER_TEST/runStatisticCalculation.cpp \ + $$OPEN_SRC/Common/vector2d.cpp \ observationLog_Tests.cpp diff --git a/OpenPass_Test/unitTests/CoreModules/Observation_LogNG/observationLogNG_Tests.cpp b/OpenPass_Test/unitTests/CoreModules/Observation_LogNG/observationLogNG_Tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddbaaafeb87c9c1a7f71a6c7d67d3514ba362fb9 --- /dev/null +++ b/OpenPass_Test/unitTests/CoreModules/Observation_LogNG/observationLogNG_Tests.cpp @@ -0,0 +1,54 @@ +/******************************************************************************* +* Copyright (c) 2020 in-tech GmbH +* +* This program and the accompanying materials are made +* available under the terms of the Eclipse Public License 2.0 +* which is available at https://www.eclipse.org/legal/epl-2.0/ +* +* SPDX-License-Identifier: EPL-2.0 +*******************************************************************************/ + +#include "gtest/gtest.h" +#include "gmock/gmock.h" + +#include "fakeAgentDataPublisher.h" +#include "fakeCallback.h" +#include "fakeDataStore.h" +#include "fakeEventNetwork.h" +#include "fakeParameter.h" +#include "fakeStochastics.h" +#include "fakeWorld.h" + +#include "Common/runtimeInformation.h" + +#include "observation_logNGImplementation.h" + +using ::testing::NiceMock; +using ::testing::NotNull; +using ::testing::Return; +using ::testing::ReturnRef; + +const openpass::common::RuntimeInformation fakeRti{{openpass::common::Version{0,0,0}}, {"", "", ""}}; + +TEST(ObservationNG, Compiles) +{ + FakeCallback fakeCallback; + FakeEventNetwork fakeEventNetwork; + NiceMock<FakeParameter> fakeParameter; + FakeStochastics fakeStochastics; + FakeWorld fakeWorld; + + std::map<std::string, const std::vector<std::string>> fakeStringVectors{{"LoggingGroups", {}}}; + + ON_CALL(fakeParameter, GetRuntimeInformation()).WillByDefault(ReturnRef(fakeRti)); + ON_CALL(fakeParameter, GetParametersStringVector()).WillByDefault(ReturnRef(fakeStringVectors)); + + auto ong = std::make_unique<ObservationLogNGImplementation>( + &fakeEventNetwork, + &fakeStochastics, + &fakeWorld, + &fakeParameter, + &fakeCallback); + + ASSERT_THAT(ong, NotNull()); +} diff --git a/OpenPass_Test/unitTests/CoreModules/Observation_LogNG/observationLogNG_Tests.pro b/OpenPass_Test/unitTests/CoreModules/Observation_LogNG/observationLogNG_Tests.pro new file mode 100644 index 0000000000000000000000000000000000000000..38816134b9c364b7bcba727d0882893395c3c12a --- /dev/null +++ b/OpenPass_Test/unitTests/CoreModules/Observation_LogNG/observationLogNG_Tests.pro @@ -0,0 +1,31 @@ +# /********************************************************************* +# * Copyright (c) 2020 in-tech GmbH +# * +# * This program and the accompanying materials are made +# * available under the terms of the Eclipse Public License 2.0 +# * which is available at https://www.eclipse.org/legal/epl-2.0/ +# * +# * SPDX-License-Identifier: EPL-2.0 +# **********************************************************************/ + +CONFIG += OPENPASS_GTEST \ + OPENPASS_GTEST_DEFAULT_MAIN + +include(../../../testing.pri) + +UNIT_UNDER_TEST = $$OPEN_SRC/CoreModules/Observation_LogNG + +win32:QMAKE_CXXFLAGS += -Wa,-mbig-obj + +INCLUDEPATH += \ + . \ + $$UNIT_UNDER_TEST + +HEADERS += \ + $$OPEN_SRC/Interfaces/dataStoreInterface.h \ + $$OPEN_SRC/Interfaces/publisherInterface.h \ + $$UNIT_UNDER_TEST/observation_logNGImplementation.h + +SOURCES += \ + $$UNIT_UNDER_TEST/observation_logNGImplementation.cpp \ + observationLogNG_Tests.cpp diff --git a/OpenPass_Test/unitTests/CoreModules/SpawnPointRuntimeCommon_OSI/spawnPointRuntimeCommon_Tests.pro b/OpenPass_Test/unitTests/CoreModules/SpawnPointRuntimeCommon_OSI/spawnPointRuntimeCommon_Tests.pro index 17d7cbc2c2b6018c4cfce69cf09af00f77706f8b..a4f5b22fbbdd62cd1e4202d968a51de18c982284 100644 --- a/OpenPass_Test/unitTests/CoreModules/SpawnPointRuntimeCommon_OSI/spawnPointRuntimeCommon_Tests.pro +++ b/OpenPass_Test/unitTests/CoreModules/SpawnPointRuntimeCommon_OSI/spawnPointRuntimeCommon_Tests.pro @@ -65,6 +65,7 @@ SOURCES += \ $$relative_path($$OPEN_SRC)/Common/vector2d.cpp \ $$UNIT_UNDER_TEST/SpawnPointRuntimeCommon.cpp \ $$FRAMEWORK/agentBlueprintProvider.cpp \ + $$FRAMEWORK/agentDataPublisher.cpp \ $$FRAMEWORK/dynamicProfileSampler.cpp \ $$FRAMEWORK/dynamicParametersSampler.cpp \ $$FRAMEWORK/dynamicAgentTypeGenerator.cpp \ diff --git a/OpenPass_Test/unitTests/CoreModules/SpawnPointScenario_OSI/spawnPointScenario_Tests.cpp b/OpenPass_Test/unitTests/CoreModules/SpawnPointScenario_OSI/spawnPointScenario_Tests.cpp index dd864b78da3002718a58620c6efe55f20b905f5e..34204097582ebdc969cedf7513cffd1fe33adf09 100644 --- a/OpenPass_Test/unitTests/CoreModules/SpawnPointScenario_OSI/spawnPointScenario_Tests.cpp +++ b/OpenPass_Test/unitTests/CoreModules/SpawnPointScenario_OSI/spawnPointScenario_Tests.cpp @@ -8,48 +8,40 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ -#include "gtest/gtest.h" -#include "gmock/gmock.h" -#include "dontCare.h" - #include "SpawnPointScenario.h" #include "agentBlueprint.h" - -#include "fakeWorld.h" -#include "fakeScenario.h" +#include "dontCare.h" +#include "fakeAgent.h" #include "fakeAgentBlueprintProvider.h" #include "fakeAgentFactory.h" #include "fakeStochastics.h" -#include "fakeAgent.h" +#include "fakeScenario.h" +#include "fakeWorld.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" -using ::testing::ReturnRef; -using ::testing::Return; using ::testing::_; using ::testing::DontCare; using ::testing::Matcher; using ::testing::NiceMock; +using ::testing::Return; +using ::testing::ReturnRef; MATCHER_P(MatchesAgentBlueprint, referenceAgentBlueprint, "matches blueprint") { - if (!(arg->GetAgentProfileName() == referenceAgentBlueprint.GetAgentProfileName() - && arg->GetAgentCategory() == referenceAgentBlueprint.GetAgentCategory()) - && arg->GetObjectName() == referenceAgentBlueprint.GetObjectName()) + if (!(arg->GetAgentProfileName() == referenceAgentBlueprint.GetAgentProfileName() && arg->GetAgentCategory() == referenceAgentBlueprint.GetAgentCategory()) && arg->GetObjectName() == referenceAgentBlueprint.GetObjectName()) { return false; } const auto actualSpawnParameters = arg->GetSpawnParameter(); const auto expectedSpawnParameters = referenceAgentBlueprint.GetSpawnParameter(); - if (!(actualSpawnParameters.velocity == expectedSpawnParameters.velocity - && actualSpawnParameters.positionX == expectedSpawnParameters.positionX - && actualSpawnParameters.yawAngle == expectedSpawnParameters.yawAngle)) + if (!(actualSpawnParameters.velocity == expectedSpawnParameters.velocity && actualSpawnParameters.positionX == expectedSpawnParameters.positionX && actualSpawnParameters.yawAngle == expectedSpawnParameters.yawAngle)) { return false; } const auto actualVehicleModelParameters = arg->GetVehicleModelParameters(); const auto expectedVehicleModelParameters = referenceAgentBlueprint.GetVehicleModelParameters(); - if (!(actualVehicleModelParameters.length == expectedVehicleModelParameters.length - && actualVehicleModelParameters.width == expectedVehicleModelParameters.width - && actualVehicleModelParameters.distanceReferencePointToLeadingEdge == expectedVehicleModelParameters.distanceReferencePointToLeadingEdge)) + if (!(actualVehicleModelParameters.length == expectedVehicleModelParameters.length && actualVehicleModelParameters.width == expectedVehicleModelParameters.width && actualVehicleModelParameters.distanceReferencePointToLeadingEdge == expectedVehicleModelParameters.distanceReferencePointToLeadingEdge)) { return false; } @@ -108,17 +100,17 @@ TEST(SpawnPointScenario, Trigger_SpawnsEgoAgentAccordingToScenarioWorldPosition) expectedAgentBlueprint.SetSpawnParameter(expectedSpawnParameter); ON_CALL(fakeScenario, GetEntities()) - .WillByDefault(ReturnRef(entities)); + .WillByDefault(ReturnRef(entities)); ON_CALL(fakeAgentBlueprintProvider, SampleAgent(entity.catalogReference.entryName, _)) - .WillByDefault(Return(actualAgentBlueprint)); + .WillByDefault(Return(actualAgentBlueprint)); ON_CALL(fakeWorld, IntersectsWithAgent(_, _, _, _, _, _)) - .WillByDefault(Return(false)); + .WillByDefault(Return(false)); SimulationSlave::Agent agent(0, &fakeWorld); // if this is called and the blueprints match, we're creating our Agent correctly EXPECT_CALL(fakeAgentFactory, AddAgent(MatchesAgentBlueprint(expectedAgentBlueprint))) - .WillOnce(Return(&agent)); + .WillOnce(Return(&agent)); SpawnPointScenario spawnPointScenario{&dependencies, nullptr}; spawnPointScenario.Trigger(0); @@ -184,25 +176,25 @@ TEST(SpawnPointScenario, Trigger_SpawnsEgoAgentAccordingToScenarioLanePosition) Position position{expectedX, expectedY, expectedYaw, 0}; - ON_CALL(fakeScenario, GetEntities()) .WillByDefault(ReturnRef(entities)); + ON_CALL(fakeScenario, GetEntities()).WillByDefault(ReturnRef(entities)); ON_CALL(fakeAgentBlueprintProvider, SampleAgent(entity.catalogReference.entryName, _)) - .WillByDefault(Return(actualAgentBlueprint)); + .WillByDefault(Return(actualAgentBlueprint)); ON_CALL(fakeWorld, IsSValidOnLane(roadId, laneId, s)) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); ON_CALL(fakeWorld, IsSValidOnLane(roadId, laneId, s)) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); ON_CALL(fakeWorld, GetLaneWidth(roadId, laneId, s)) - .WillByDefault(Return(0.75)); + .WillByDefault(Return(0.75)); ON_CALL(fakeWorld, LaneCoord2WorldCoord(s, offset, roadId, laneId)) - .WillByDefault(Return(position)); + .WillByDefault(Return(position)); ON_CALL(fakeWorld, IntersectsWithAgent(_, _, _, _, _, _)) - .WillByDefault(Return(false)); + .WillByDefault(Return(false)); SimulationSlave::Agent agent(0, &fakeWorld); // if this is called and the blueprints match, we're creating our Agent correctly EXPECT_CALL(fakeAgentFactory, AddAgent(MatchesAgentBlueprint(expectedAgentBlueprint))) - .WillOnce(Return(&agent)); + .WillOnce(Return(&agent)); SpawnPointScenario spawnPointScenario{&dependencies, nullptr}; spawnPointScenario.Trigger(0); @@ -259,17 +251,17 @@ TEST(SpawnPointScenario, Trigger_SpawnsScenarioAgentAccordingToScenarioWorldPosi expectedAgentBlueprint.SetSpawnParameter(expectedSpawnParameter); ON_CALL(fakeScenario, GetEntities()) - .WillByDefault(ReturnRef(entities)); + .WillByDefault(ReturnRef(entities)); ON_CALL(fakeAgentBlueprintProvider, SampleAgent(entity.catalogReference.entryName, _)) - .WillByDefault(Return(actualAgentBlueprint)); + .WillByDefault(Return(actualAgentBlueprint)); ON_CALL(fakeWorld, IntersectsWithAgent(_, _, _, _, _, _)) - .WillByDefault(Return(false)); + .WillByDefault(Return(false)); SimulationSlave::Agent agent(0, &fakeWorld); // if this is called and the blueprints match, we're creating our Agent correctly EXPECT_CALL(fakeAgentFactory, AddAgent(MatchesAgentBlueprint(expectedAgentBlueprint))) - .WillOnce(Return(&agent)); + .WillOnce(Return(&agent)); SpawnPointScenario spawnPointScenario{&dependencies, nullptr}; spawnPointScenario.Trigger(0); @@ -336,25 +328,25 @@ TEST(SpawnPointScenario, Trigger_SpawnsScenarioAgentAccordingToScenarioLanePosit Position position{expectedX, expectedY, expectedYaw, 0}; ON_CALL(fakeScenario, GetEntities()) - .WillByDefault(ReturnRef(entities)); + .WillByDefault(ReturnRef(entities)); ON_CALL(fakeAgentBlueprintProvider, SampleAgent(entity.catalogReference.entryName, _)) - .WillByDefault(Return(actualAgentBlueprint)); + .WillByDefault(Return(actualAgentBlueprint)); ON_CALL(fakeWorld, IsSValidOnLane(roadId, laneId, s)) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); ON_CALL(fakeWorld, IsSValidOnLane(roadId, laneId, s)) - .WillByDefault(Return(true)); + .WillByDefault(Return(true)); ON_CALL(fakeWorld, GetLaneWidth(roadId, laneId, s)) - .WillByDefault(Return(0.75)); + .WillByDefault(Return(0.75)); ON_CALL(fakeWorld, LaneCoord2WorldCoord(s, offset, roadId, laneId)) - .WillByDefault(Return(position)); + .WillByDefault(Return(position)); ON_CALL(fakeWorld, IntersectsWithAgent(_, _, _, _, _, _)) - .WillByDefault(Return(false)); + .WillByDefault(Return(false)); SimulationSlave::Agent agent(0, &fakeWorld); // if this is called and the blueprints match, we're creating our Agent correctly EXPECT_CALL(fakeAgentFactory, AddAgent(MatchesAgentBlueprint(expectedAgentBlueprint))) - .WillOnce(Return(&agent)); + .WillOnce(Return(&agent)); SpawnPointScenario spawnPointScenario{&dependencies, nullptr}; spawnPointScenario.Trigger(0); diff --git a/OpenPass_Test/unitTests/CoreModules/SpawnPointScenario_OSI/spawnPointScenario_Tests.pro b/OpenPass_Test/unitTests/CoreModules/SpawnPointScenario_OSI/spawnPointScenario_Tests.pro index e9dae7a84e09ad6a26069465d009afac837e933c..37df5e100c908bef4d43b14381f9abbdb4d4fdb8 100644 --- a/OpenPass_Test/unitTests/CoreModules/SpawnPointScenario_OSI/spawnPointScenario_Tests.pro +++ b/OpenPass_Test/unitTests/CoreModules/SpawnPointScenario_OSI/spawnPointScenario_Tests.pro @@ -62,6 +62,7 @@ SOURCES += \ $$relative_path($$OPEN_SRC)/Common/vector2d.cpp \ $$UNIT_UNDER_TEST/SpawnPointScenario.cpp \ $$FRAMEWORK/agentBlueprintProvider.cpp \ + $$FRAMEWORK/agentDataPublisher.cpp \ $$FRAMEWORK/dynamicProfileSampler.cpp \ $$FRAMEWORK/dynamicParametersSampler.cpp \ $$FRAMEWORK/dynamicAgentTypeGenerator.cpp \ diff --git a/OpenPass_Test/unitTests/openPASS_UnitTests.pro b/OpenPass_Test/unitTests/openPASS_UnitTests.pro index add44f8e4282510b785ad4634c07f8e5f29defba..43007de8260afe6abb01e6063c26268b2a564b42 100644 --- a/OpenPass_Test/unitTests/openPASS_UnitTests.pro +++ b/OpenPass_Test/unitTests/openPASS_UnitTests.pro @@ -16,12 +16,14 @@ SUBDIRS = \ algorithmFmuWrapper_Tests \ algorithmLateral_Tests \ algorithmLongitudinal_Tests \ + basicDataStore_Tests \ componentController_Tests \ dynamicsCollision_Tests \ dynamicsTrajectoryFollower_Tests \ eventDetector_Tests \ limiterAccelerationVehicleComponents_Tests \ observationLog_Tests \ + \ #observationLogNG_Tests \ openPassSlave_Tests \ openScenarioActions_Tests \ scheduler_Tests \ @@ -50,6 +52,9 @@ algorithmLateral_Tests.file = \ algorithmLongitudinal_Tests.file = \ $$PWD/Components/Algorithm_Longitudinal/algorithmLongitudinal_Tests.pro +basicDataStore_Tests.file = \ + $$PWD/CoreModules/BasicDataStore/basicDataStore_Tests.pro + componentController_Tests.file = \ $$PWD/Components/ComponentController/componentController_Tests.pro diff --git a/Templates/Algorithm_Comp1/algorithm_Comp1.cpp b/Templates/Algorithm_Comp1/algorithm_Comp1.cpp index 9ca3b659081ce39d5c734372022c4b2c0f7b0949..0c80df446827571318d9d617aeedd8bd26f3afc2 100644 --- a/Templates/Algorithm_Comp1/algorithm_Comp1.cpp +++ b/Templates/Algorithm_Comp1/algorithm_Comp1.cpp @@ -1,9 +1,9 @@ -/********************************************************************* -* This Example Content is intended to demonstrate usage of -* Eclipse technology. It is provided to you under the terms -* and conditions of the Eclipse Distribution License v1.0 -* which is available at http://www.eclipse.org/org/documents/edl-v10.php -**********************************************************************/ +/********************************************************************* +* This Example Content is intended to demonstrate usage of +* Eclipse technology. It is provided to you under the terms +* and conditions of the Eclipse Distribution License v1.0 +* which is available at http://www.eclipse.org/org/documents/edl-v10.php +**********************************************************************/ //----------------------------------------------------------------------------- //! @file algorithm_Comp1.cpp @@ -34,7 +34,7 @@ extern "C" ALGORITHM_COMP1_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -55,7 +55,7 @@ extern "C" ALGORITHM_COMP1_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agent->GetAgentId())); } diff --git a/Templates/Algorithm_Comp1/algorithm_Comp1_implementation.cpp b/Templates/Algorithm_Comp1/algorithm_Comp1_implementation.cpp index 3829a097791e9b7b3df7e6a823281a1954db8d63..f6b40f512e21090b78efaaa681cc1fdf2b33b14d 100644 --- a/Templates/Algorithm_Comp1/algorithm_Comp1_implementation.cpp +++ b/Templates/Algorithm_Comp1/algorithm_Comp1_implementation.cpp @@ -1,9 +1,9 @@ -/********************************************************************* -* This Example Content is intended to demonstrate usage of -* Eclipse technology. It is provided to you under the terms -* and conditions of the Eclipse Distribution License v1.0 -* which is available at http://www.eclipse.org/org/documents/edl-v10.php -**********************************************************************/ +/********************************************************************* +* This Example Content is intended to demonstrate usage of +* Eclipse technology. It is provided to you under the terms +* and conditions of the Eclipse Distribution License v1.0 +* which is available at http://www.eclipse.org/org/documents/edl-v10.php +**********************************************************************/ /** * @defgroup module_comp1 Comp1 @@ -31,7 +31,7 @@ Algorithm_Comp1_Implementation::Algorithm_Comp1_Implementation(int componentId, int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, int agentId) : AlgorithmInterface(componentId, @@ -42,7 +42,7 @@ Algorithm_Comp1_Implementation::Algorithm_Comp1_Implementation(int componentId, cycleTime, stochastics, parameters, - observations, + publisher, callbacks, agentId) { diff --git a/Templates/Algorithm_Comp1/algorithm_Comp1_implementation.h b/Templates/Algorithm_Comp1/algorithm_Comp1_implementation.h index e1854ecda2e83975024ff5d2b0b5a388724157e5..c02131166eeedddd79359f17cc44b2b1a1d7e0a3 100644 --- a/Templates/Algorithm_Comp1/algorithm_Comp1_implementation.h +++ b/Templates/Algorithm_Comp1/algorithm_Comp1_implementation.h @@ -1,15 +1,14 @@ -/********************************************************************* -* This Example Content is intended to demonstrate usage of -* Eclipse technology. It is provided to you under the terms -* and conditions of the Eclipse Distribution License v1.0 -* which is available at http://www.eclipse.org/org/documents/edl-v10.php -**********************************************************************/ +/********************************************************************* +* This Example Content is intended to demonstrate usage of +* Eclipse technology. It is provided to you under the terms +* and conditions of the Eclipse Distribution License v1.0 +* which is available at http://www.eclipse.org/org/documents/edl-v10.php +**********************************************************************/ #ifndef ALGORITHM_COMP1_IMPLEMENTATION_H #define ALGORITHM_COMP1_IMPLEMENTATION_H #include "modelInterface.h" -#include "observationInterface.h" #include "primitiveSignals.h" #include "vectorSignals.h" #include "componentPorts.h" @@ -55,7 +54,7 @@ public: int cycleTime, StochasticsInterface *stochastics, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, int agentId); diff --git a/Templates/Dynamics_Comp2/dynamics_Comp2.cpp b/Templates/Dynamics_Comp2/dynamics_Comp2.cpp index d99d2e8834eb389fe5eab05654f0353e6a2c59a4..336156741e5d6d591305a11b4076a621fceed869 100644 --- a/Templates/Dynamics_Comp2/dynamics_Comp2.cpp +++ b/Templates/Dynamics_Comp2/dynamics_Comp2.cpp @@ -1,9 +1,9 @@ -/********************************************************************* -* This Example Content is intended to demonstrate usage of -* Eclipse technology. It is provided to you under the terms -* and conditions of the Eclipse Distribution License v1.0 -* which is available at http://www.eclipse.org/org/documents/edl-v10.php -**********************************************************************/ +/********************************************************************* +* This Example Content is intended to demonstrate usage of +* Eclipse technology. It is provided to you under the terms +* and conditions of the Eclipse Distribution License v1.0 +* which is available at http://www.eclipse.org/org/documents/edl-v10.php +**********************************************************************/ //----------------------------------------------------------------------------- //! @file dynamics_Comp2.cpp @@ -34,7 +34,7 @@ extern "C" DYNAMICS_COMP2_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, AgentInterface *agent, const CallbackInterface *callbacks) { @@ -56,7 +56,7 @@ extern "C" DYNAMICS_COMP2_SHARED_EXPORT ModelInterface *OpenPASS_CreateInstance( stochastics, world, parameters, - observations, + publisher, callbacks, agent)); } diff --git a/Templates/Dynamics_Comp2/dynamics_Comp2_implementation.cpp b/Templates/Dynamics_Comp2/dynamics_Comp2_implementation.cpp index b6f7b3a441c20e8ffc24d5c7b443012e5a9468c0..2e1f78dc3dbbf8c2a9c057695356dbdf9d9cc231 100644 --- a/Templates/Dynamics_Comp2/dynamics_Comp2_implementation.cpp +++ b/Templates/Dynamics_Comp2/dynamics_Comp2_implementation.cpp @@ -1,9 +1,9 @@ -/********************************************************************* -* This Example Content is intended to demonstrate usage of -* Eclipse technology. It is provided to you under the terms -* and conditions of the Eclipse Distribution License v1.0 -* which is available at http://www.eclipse.org/org/documents/edl-v10.php -**********************************************************************/ +/********************************************************************* +* This Example Content is intended to demonstrate usage of +* Eclipse technology. It is provided to you under the terms +* and conditions of the Eclipse Distribution License v1.0 +* which is available at http://www.eclipse.org/org/documents/edl-v10.php +**********************************************************************/ /** * @defgroup module_comp2 Comp2 @@ -32,7 +32,7 @@ Dynamics_Comp2_Implementation::Dynamics_Comp2_Implementation(int componentId, StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent) : DynamicsInterface(componentId, @@ -44,7 +44,7 @@ Dynamics_Comp2_Implementation::Dynamics_Comp2_Implementation(int componentId, stochastics, world, parameters, - observations, + publisher, callbacks, agent) { diff --git a/Templates/Dynamics_Comp2/dynamics_Comp2_implementation.h b/Templates/Dynamics_Comp2/dynamics_Comp2_implementation.h index 9731709d8b854d81fd14e7188a67ef26a82efb93..c168011cd051c9aa6dd004d555782dd98cbf7466 100644 --- a/Templates/Dynamics_Comp2/dynamics_Comp2_implementation.h +++ b/Templates/Dynamics_Comp2/dynamics_Comp2_implementation.h @@ -1,15 +1,14 @@ -/********************************************************************* -* This Example Content is intended to demonstrate usage of -* Eclipse technology. It is provided to you under the terms -* and conditions of the Eclipse Distribution License v1.0 -* which is available at http://www.eclipse.org/org/documents/edl-v10.php -**********************************************************************/ +/********************************************************************* +* This Example Content is intended to demonstrate usage of +* Eclipse technology. It is provided to you under the terms +* and conditions of the Eclipse Distribution License v1.0 +* which is available at http://www.eclipse.org/org/documents/edl-v10.php +**********************************************************************/ #ifndef DYNAMICS_COMP2_IMPLEMENTATION_H #define DYNAMICS_COMP2_IMPLEMENTATION_H #include "modelInterface.h" -#include "observationInterface.h" #include "primitiveSignals.h" #include "vectorSignals.h" #include "componentPorts.h" @@ -56,7 +55,7 @@ public: StochasticsInterface *stochastics, WorldInterface *world, const ParameterInterface *parameters, - const std::map<int, ObservationInterface *> *observations, + PublisherInterface * const publisher, const CallbackInterface *callbacks, AgentInterface *agent);