<commit_before>/**
 * @file Cognition.cpp
 *
 * @author Heinrich Mellmann
 * Implementation of the class Cognition
 */

#include "Cognition.h"

#include <PlatformInterface/Platform.h>

// tools
#include "Tools/Debug/Trace.h"

/////////////////////////////////////
// Modules
/////////////////////////////////////

// infrastructure
#include "Modules/Infrastructure/IO/Sensor.h"
#include "Modules/Infrastructure/IO/Actuator.h"
#include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h"
#include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h"
#include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h"
#include "Modules/Infrastructure/GameController/GameController.h"
#include "Modules/Infrastructure/Debug/FrameRateCheck.h"
#include "Modules/Infrastructure/Debug/DebugExecutor.h"
#include "Modules/Infrastructure/Debug/Debug.h"
#include "Modules/Infrastructure/LEDSetter/LEDSetter.h"
#include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h"

#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h"
#include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h"

#include "Modules/Infrastructure/Debug/CameraDebug.h"
#include "Modules/Infrastructure/Camera/CameraInfoSetter.h"
#include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h"
#include "Modules/Infrastructure/GameLogger/GameLogger.h"

// perception
#include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h"
#include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h"
#include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h"
#include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h"

#include "Modules/VisualCortex/HistogramProvider.h"
#include "Modules/VisualCortex/FieldColorClassifier.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridProvider.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridEdgelDetector.h"
#include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h"
#include "Modules/VisualCortex/FieldDetector/FieldDetector.h"
#include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h"
#include "Modules/VisualCortex/LineDetector/LineGraphProvider.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h"
#include "Modules/VisualCortex/BallDetector/RedBallDetector.h"
#include "Modules/VisualCortex/BallDetector/CNNBallDetector.h"
#include "Modules/VisualCortex/BallDetector/MultiPassBallDetector.h"
#include "Modules/VisualCortex/IntegralImageProvider.h"

#include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h"

#include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h"
#include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h"

#include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h"
#include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h"

#include "Modules/VisualCortex/LineDetector/RansacLineDetector.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h"
#include "Modules/VisualCortex/LineDetector/LineAugmenter.h"

#include "Modules/Modeling/CompassProvider/CompassProvider.h"

// modeling
#include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h"
#include "Modules/Modeling/FieldCompass/FieldCompass.h"
#include "Modules/Perception/UltrasonicObstacleDetector/UltraSoundObstacleDetector.h"
#include "Modules/Perception/UltrasonicObstacleDetector/UltrasonicObstacleDetector2020.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h"
#include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h"
#include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h"
#include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h"
#include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h"
#include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h"
#include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h"
#include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h"

// role decisions
#include "Modules/Modeling/RoleDecision/RolesProvider.h"
#include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h"

#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h"
// the old striker decision (dynamic)
#include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h"

#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h"
#include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h"
#include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h"

#include "Modules/Modeling/ObstacleLocator/MultiUnifiedObstacleLocator.h"

#include "Modules/Modeling/Simulation/Simulation.h"
#include "Modules/Modeling/Simulation/KickDirectionSimulator.h"
#include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h"

// behavior
#include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h"
#include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h"
#include "Modules/Behavior/PathPlanner/PathPlanner2018.h"

using namespace std;

Cognition::Cognition()
  : ModuleManagerWithDebug("")
{
}

Cognition::~Cognition()
{
}

#define REGISTER_MODULE(module) \
  std::cout << "[Cognition] Register " << #module << std::endl;\
  registerModule<module>(std::string(#module))

void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform)
{
  std::cout << "[Cognition] Cognition register start" << std::endl;

  // register input module
  ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true);
  sensor->getModuleT()->init(platformInterface, platform);

  /*
  * to register a module use
  *   REGISTER_MODULE(ModuleClassName);
  *
  * Remark: to enable the module don't forget
  *         to set the value in modules.cfg
  */

  // -- BEGIN REGISTER MODULES --

  // infrastructure
  REGISTER_MODULE(ButtonEventMonitor);
  REGISTER_MODULE(WifiModeSetter);
  REGISTER_MODULE(TeamCommReceiver);
  REGISTER_MODULE(SimpleNetworkTimeProtocol);
  REGISTER_MODULE(GameController);
  REGISTER_MODULE(BatteryAlert);
  REGISTER_MODULE(LEDSetter);
  REGISTER_MODULE(UltraSoundControl);

  REGISTER_MODULE(CameraDebug);
  REGISTER_MODULE(CameraInfoSetter);
  REGISTER_MODULE(AdaptiveAutoExposure);
  REGISTER_MODULE(WhistleDetectorV1);
  REGISTER_MODULE(WhistleDetectorV2);

  // perception
  REGISTER_MODULE(CameraMatrixFinder);
  REGISTER_MODULE(KinematicChainProvider);
  REGISTER_MODULE(ArtificialHorizonCalculator);
  REGISTER_MODULE(BodyContourProvider);

  REGISTER_MODULE(HistogramProvider);
  REGISTER_MODULE(IntegralImageProvider);
  REGISTER_MODULE(FieldColorClassifier);
  REGISTER_MODULE(IntegralFieldDetector);
  REGISTER_MODULE(ScanGridProvider);
  REGISTER_MODULE(ScanGridEdgelDetector);
  REGISTER_MODULE(ScanLineEdgelDetector);
  REGISTER_MODULE(FieldDetector);
  REGISTER_MODULE(LineGraphProvider);
  REGISTER_MODULE(GoalFeatureDetector);
  REGISTER_MODULE(GoalFeatureDetectorV2);
  REGISTER_MODULE(GoalDetector);
  REGISTER_MODULE(GoalDetectorV2);
  REGISTER_MODULE(GoalCrossBarDetector);

  REGISTER_MODULE(NoGreenObstacleDetector);

  REGISTER_MODULE(RedBallDetector);
  REGISTER_MODULE(CNNBallDetector);
  REGISTER_MODULE(MultiPassBallDetector);
  REGISTER_MODULE(FakeCameraMatrixFinder);
  REGISTER_MODULE(FakeBallDetector);

  REGISTER_MODULE(VirtualVisionProcessor);
  REGISTER_MODULE(PerceptionsVisualizer);

  REGISTER_MODULE(RansacLineDetector);
  REGISTER_MODULE(RansacLineDetectorOnGraphs);
  REGISTER_MODULE(LineAugmenter);

  REGISTER_MODULE(CompassProvider);

  // modeling
  REGISTER_MODULE(SituationPriorProvider);
  REGISTER_MODULE(BodyStateProvider);
  REGISTER_MODULE(FieldCompass);
  REGISTER_MODULE(UltraSoundObstacleDetector);
  REGISTER_MODULE(UltrasonicDetector2020);
  REGISTER_MODULE(TeamCommReceiveEmulator);
  REGISTER_MODULE(TeamMessageStatisticsModule);
  REGISTER_MODULE(TeamMessagePlayersStateModule);
  REGISTER_MODULE(SoccerStrategyProvider);
  REGISTER_MODULE(PotentialFieldProvider);
  REGISTER_MODULE(GPS_SelfLocator);
  REGISTER_MODULE(MonteCarloSelfLocator);
  REGISTER_MODULE(OdometrySelfLocator);
  REGISTER_MODULE(WholeGoalLocator);
  REGISTER_MODULE(DummyActiveGoalLocator);
  REGISTER_MODULE(MultiKalmanBallLocator);

  REGISTER_MODULE(TeamBallLocatorMedian);
  REGISTER_MODULE(TeamBallLocatorCanopyCluster);

  REGISTER_MODULE(MultiUnifiedObstacleLocator);
  /*
   * BEGIN ROLE DECISIONS
   */
  REGISTER_MODULE(RolesProvider);
  // first set the position of the roles
  REGISTER_MODULE(RoleDecisionPositionStatic);
  REGISTER_MODULE(RoleDecisionPositionForce);
  REGISTER_MODULE(RoleDecisionPositionPotentialField);
  REGISTER_MODULE(RoleDecisionPositionFormation);
  REGISTER_MODULE(RoleDecisionPositionDynamicGoalie);
  // then decide which player should have which role
  REGISTER_MODULE(RoleDecisionAssignmentStatic);
  REGISTER_MODULE(RoleDecisionAssignmentDistance);
  // finally, determine the dynamic role (striker, supporter, ...)
  REGISTER_MODULE(RoleDecisionDynamic);

  // old striker decisions
  REGISTER_MODULE(SimpleRoleDecision);
  REGISTER_MODULE(StableRoleDecision);
  REGISTER_MODULE(CleanRoleDecision);
  /*
   * END ROLE DECISIONS
   */

  REGISTER_MODULE(KickDirectionSimulator);
  REGISTER_MODULE(Simulation);
  REGISTER_MODULE(StaticDebugModelProvider);

  // behavior
  REGISTER_MODULE(BasicTestBehavior);
  REGISTER_MODULE(XABSLBehaviorControl);
  REGISTER_MODULE(PathPlanner2018);

  REGISTER_MODULE(CameraMatrixCorrectorV3);

  REGISTER_MODULE(TeamCommSender);

  // debug
  REGISTER_MODULE(GameLogger);
  REGISTER_MODULE(Debug);
  REGISTER_MODULE(FrameRateCheck);
  REGISTER_MODULE(DebugExecutor);

  // -- END REGISTER MODULES --

  // register output module
  ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true);
  actuator->getModuleT()->init(platformInterface, platform);

  // use the configuration in order to set whether a module is activated or not
  const naoth::Configuration& config = Platform::getInstance().theConfiguration;

  list<string>::const_iterator name = getExecutionList().begin();
  for(;name != getExecutionList().end(); ++name)
  {
    bool active = false;
    if(config.hasKey("modules", *name)) {
      active = config.getBool("modules", *name);
    }
    if(active) {
      std::cout << "[Cognition] activating module " << *name << std::endl;
    }
    setModuleEnabled(*name, active);
  }//end for

  // auto-generate the execution list
  //calculateExecutionList();

  std::cout << "[Cognition] register end" << std::endl;

  stopwatch.start();
}//end init

void Cognition::call()
{
  // BEGIN cognition frame rate measuring
  stopwatch.stop();
  stopwatch.start();
  PLOT("Cognition.Cycle", stopwatch.lastValue);
  // END cognition frame rate measuring

  STOPWATCH_START("Cognition.Execute");

  // execute all modules
  list<AbstractModuleCreator*>::const_iterator iter;
  for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter)
  {
    AbstractModuleCreator* module = *iter;
    if (module != NULL && module->isEnabled())
    {
      std::string name(module->getModule()->getName());
      GT_TRACE("executing " << name);
      module->execute();
    }
  }

  STOPWATCH_STOP("Cognition.Execute");

  // HACK: reset all the debug stuff before executing the modules
  STOPWATCH_START("Cognition.Debug.Init");
  getDebugDrawings().reset();
  getDebugImageDrawings().reset();
  getDebugImageDrawingsTop().reset();
  getDebugDrawings3D().reset();
  STOPWATCH_STOP("Cognition.Debug.Init");
}//end call
<commit_msg>move SituationPriorProvider close to the SelfLocators. It requires BodyState, so it should be executed after BodyStateProvider.<commit_after>/**
 * @file Cognition.cpp
 *
 * @author Heinrich Mellmann
 * Implementation of the class Cognition
 */

#include "Cognition.h"

#include <PlatformInterface/Platform.h>

// tools
#include "Tools/Debug/Trace.h"

/////////////////////////////////////
// Modules
/////////////////////////////////////

// infrastructure
#include "Modules/Infrastructure/IO/Sensor.h"
#include "Modules/Infrastructure/IO/Actuator.h"
#include "Modules/Infrastructure/ButtonEventMonitor/ButtonEventMonitor.h"
#include "Cognition/Modules/Infrastructure/WifiModeSetter/WifiModeSetter.h"
#include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h"
#include "Modules/Infrastructure/GameController/GameController.h"
#include "Modules/Infrastructure/Debug/FrameRateCheck.h"
#include "Modules/Infrastructure/Debug/DebugExecutor.h"
#include "Modules/Infrastructure/Debug/Debug.h"
#include "Modules/Infrastructure/LEDSetter/LEDSetter.h"
#include "Modules/Infrastructure/UltraSoundControl/UltraSoundControl.h"

#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h"
#include "Modules/Infrastructure/TeamCommunicator/SimpleNetworkTimeProtocol.h"

#include "Modules/Infrastructure/Debug/CameraDebug.h"
#include "Modules/Infrastructure/Camera/CameraInfoSetter.h"
#include "Modules/Infrastructure/Camera/AdaptiveAutoExposure.h"
#include "Modules/Infrastructure/GameLogger/GameLogger.h"

// perception
#include "Modules/SelfAwareness/CameraMatrixFinder/CameraMatrixFinder.h"
#include "Modules/SelfAwareness/KinematicChainProvider/KinematicChainProvider.h"
#include "Modules/SelfAwareness/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h"
#include "Modules/SelfAwareness/BodyContourProvider/BodyContourProvider.h"
#include "Modules/SelfAwareness/CameraMatrixCorrectorV3/CameraMatrixCorrectorV3.h"

#include "Modules/VisualCortex/HistogramProvider.h"
#include "Modules/VisualCortex/FieldColorClassifier.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridProvider.h"
#include "Modules/VisualCortex/ScanGrid/ScanGridEdgelDetector.h"
#include "Modules/VisualCortex/ScanLineEdgelDetector/ScanLineEdgelDetector.h"
#include "Modules/VisualCortex/FieldDetector/FieldDetector.h"
#include "Modules/VisualCortex/FieldDetector/IntegralFieldDetector.h"
#include "Modules/VisualCortex/LineDetector/LineGraphProvider.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalFeatureDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetector.h"
#include "Modules/VisualCortex/GoalDetector/GoalDetectorV2.h"
#include "Modules/VisualCortex/GoalDetector/GoalCrossBarDetector.h"
#include "Modules/VisualCortex/BallDetector/RedBallDetector.h"
#include "Modules/VisualCortex/BallDetector/CNNBallDetector.h"
#include "Modules/VisualCortex/BallDetector/MultiPassBallDetector.h"
#include "Modules/VisualCortex/IntegralImageProvider.h"

#include "Modules/VisualCortex/ObstacleDetector/NoGreenObstacleDetector.h"

#include "Modules/SelfAwareness/FakeCameraMatrixFinder/FakeCameraMatrixFinder.h"
#include "Modules/VisualCortex/FakeBallDetector/FakeBallDetector.h"

#include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h"
#include "Modules/Perception/PerceptionsVisualizer/PerceptionsVisualizer.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV1.h"
#include "Modules/Perception/WhistleDetector/WhistleDetectorV2.h"

#include "Modules/VisualCortex/LineDetector/RansacLineDetector.h"
#include "Modules/VisualCortex/LineDetector/RansacLineDetectorOnGraphs.h"
#include "Modules/VisualCortex/LineDetector/LineAugmenter.h"

#include "Modules/Modeling/CompassProvider/CompassProvider.h"

// modeling
#include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h"
#include "Modules/Modeling/FieldCompass/FieldCompass.h"
#include "Modules/Perception/UltrasonicObstacleDetector/UltraSoundObstacleDetector.h"
#include "Modules/Perception/UltrasonicObstacleDetector/UltrasonicObstacleDetector2020.h"
#include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessageStatisticsModule.h"
#include "Modules/Modeling/TeamMessageStatistics/TeamMessagePlayersStateModule.h"
#include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h"
#include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h"
#include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h"
#include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h"
#include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h"
#include "Modules/Modeling/GoalModel/DummyActiveGoalLocator/DummyActiveGoalLocator.h"
#include "Modules/Modeling/GoalModel/WholeGoalLocator/WholeGoalLocator.h"

// role decisions
#include "Modules/Modeling/RoleDecision/RolesProvider.h"
#include "Modules/Modeling/RoleDecision/Dynamic/RoleDecisionDynamic.h"

#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionStatic.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionForce.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionPotentialField.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionFormation.h"
#include "Modules/Modeling/RoleDecision/Position/RoleDecisionPositionDynamicGoalie.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentStatic.h"
#include "Modules/Modeling/RoleDecision/Assignment/RoleDecisionAssignmentDistance.h"
// the old striker decision (dynamic)
#include "Modules/Modeling/RoleDecision/Dynamic/SimpleRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/StableRoleDecision.h"
#include "Modules/Modeling/RoleDecision/Dynamic/CleanRoleDecision.h"

#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorMedian.h"
#include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocatorCanopyCluster.h"
#include "Modules/Modeling/BallLocator/MultiKalmanBallLocator/MultiKalmanBallLocator.h"
#include "Modules/Modeling/StaticDebugModelProvider/StaticDebugModelProvider.h"

#include "Modules/Modeling/ObstacleLocator/MultiUnifiedObstacleLocator.h"

#include "Modules/Modeling/Simulation/Simulation.h"
#include "Modules/Modeling/Simulation/KickDirectionSimulator.h"
#include "Modules/Modeling/SelfLocator/SituationPriorProvider/SituationPriorProvider.h"

// behavior
#include "Modules/Behavior/BasicTestBehavior/BasicTestBehavior.h"
#include "Modules/Behavior/XABSLBehaviorControl/XABSLBehaviorControl.h"
#include "Modules/Behavior/PathPlanner/PathPlanner2018.h"

using namespace std;

Cognition::Cognition()
  : ModuleManagerWithDebug("")
{
}

Cognition::~Cognition()
{
}

#define REGISTER_MODULE(module) \
  std::cout << "[Cognition] Register " << #module << std::endl;\
  registerModule<module>(std::string(#module))

void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform)
{
  std::cout << "[Cognition] Cognition register start" << std::endl;

  // register input module
  ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true);
  sensor->getModuleT()->init(platformInterface, platform);

  /*
  * to register a module use
  *   REGISTER_MODULE(ModuleClassName);
  *
  * Remark: to enable the module don't forget
  *         to set the value in modules.cfg
  */

  // -- BEGIN REGISTER MODULES --

  // infrastructure
  REGISTER_MODULE(ButtonEventMonitor);
  REGISTER_MODULE(WifiModeSetter);
  REGISTER_MODULE(TeamCommReceiver);
  REGISTER_MODULE(SimpleNetworkTimeProtocol);
  REGISTER_MODULE(GameController);
  REGISTER_MODULE(BatteryAlert);
  REGISTER_MODULE(LEDSetter);
  REGISTER_MODULE(UltraSoundControl);

  REGISTER_MODULE(CameraDebug);
  REGISTER_MODULE(CameraInfoSetter);
  REGISTER_MODULE(AdaptiveAutoExposure);
  REGISTER_MODULE(WhistleDetectorV1);
  REGISTER_MODULE(WhistleDetectorV2);

  // perception
  REGISTER_MODULE(CameraMatrixFinder);
  REGISTER_MODULE(KinematicChainProvider);
  REGISTER_MODULE(ArtificialHorizonCalculator);
  REGISTER_MODULE(BodyContourProvider);

  REGISTER_MODULE(HistogramProvider);
  REGISTER_MODULE(IntegralImageProvider);
  REGISTER_MODULE(FieldColorClassifier);
  REGISTER_MODULE(IntegralFieldDetector);
  REGISTER_MODULE(ScanGridProvider);
  REGISTER_MODULE(ScanGridEdgelDetector);
  REGISTER_MODULE(ScanLineEdgelDetector);
  REGISTER_MODULE(FieldDetector);
  REGISTER_MODULE(LineGraphProvider);
  REGISTER_MODULE(GoalFeatureDetector);
  REGISTER_MODULE(GoalFeatureDetectorV2);
  REGISTER_MODULE(GoalDetector);
  REGISTER_MODULE(GoalDetectorV2);
  REGISTER_MODULE(GoalCrossBarDetector);

  REGISTER_MODULE(NoGreenObstacleDetector);

  REGISTER_MODULE(RedBallDetector);
  REGISTER_MODULE(CNNBallDetector);
  REGISTER_MODULE(MultiPassBallDetector);
  REGISTER_MODULE(FakeCameraMatrixFinder);
  REGISTER_MODULE(FakeBallDetector);

  REGISTER_MODULE(VirtualVisionProcessor);
  REGISTER_MODULE(PerceptionsVisualizer);

  REGISTER_MODULE(RansacLineDetector);
  REGISTER_MODULE(RansacLineDetectorOnGraphs);
  REGISTER_MODULE(LineAugmenter);

  REGISTER_MODULE(CompassProvider);

  // modeling
  REGISTER_MODULE(BodyStateProvider);
  REGISTER_MODULE(FieldCompass);
  REGISTER_MODULE(UltraSoundObstacleDetector);
  REGISTER_MODULE(UltrasonicDetector2020);
  REGISTER_MODULE(TeamCommReceiveEmulator);
  REGISTER_MODULE(TeamMessageStatisticsModule);
  REGISTER_MODULE(TeamMessagePlayersStateModule);
  REGISTER_MODULE(SoccerStrategyProvider);
  REGISTER_MODULE(PotentialFieldProvider);
  REGISTER_MODULE(SituationPriorProvider);

  REGISTER_MODULE(GPS_SelfLocator);
  REGISTER_MODULE(MonteCarloSelfLocator);
  REGISTER_MODULE(OdometrySelfLocator);

  REGISTER_MODULE(WholeGoalLocator);
  REGISTER_MODULE(DummyActiveGoalLocator);
  REGISTER_MODULE(MultiKalmanBallLocator);

  REGISTER_MODULE(TeamBallLocatorMedian);
  REGISTER_MODULE(TeamBallLocatorCanopyCluster);

  REGISTER_MODULE(MultiUnifiedObstacleLocator);
  /*
   * BEGIN ROLE DECISIONS
   */
  REGISTER_MODULE(RolesProvider);
  // first set the position of the roles
  REGISTER_MODULE(RoleDecisionPositionStatic);
  REGISTER_MODULE(RoleDecisionPositionForce);
  REGISTER_MODULE(RoleDecisionPositionPotentialField);
  REGISTER_MODULE(RoleDecisionPositionFormation);
  REGISTER_MODULE(RoleDecisionPositionDynamicGoalie);
  // then decide which player should have which role
  REGISTER_MODULE(RoleDecisionAssignmentStatic);
  REGISTER_MODULE(RoleDecisionAssignmentDistance);
  // finally, determine the dynamic role (striker, supporter, ...)
  REGISTER_MODULE(RoleDecisionDynamic);

  // old striker decisions
  REGISTER_MODULE(SimpleRoleDecision);
  REGISTER_MODULE(StableRoleDecision);
  REGISTER_MODULE(CleanRoleDecision);
  /*
   * END ROLE DECISIONS
   */

  REGISTER_MODULE(KickDirectionSimulator);
  REGISTER_MODULE(Simulation);
  REGISTER_MODULE(StaticDebugModelProvider);

  // behavior
  REGISTER_MODULE(BasicTestBehavior);
  REGISTER_MODULE(XABSLBehaviorControl);
  REGISTER_MODULE(PathPlanner2018);

  REGISTER_MODULE(CameraMatrixCorrectorV3);

  REGISTER_MODULE(TeamCommSender);

  // debug
  REGISTER_MODULE(GameLogger);
  REGISTER_MODULE(Debug);
  REGISTER_MODULE(FrameRateCheck);
  REGISTER_MODULE(DebugExecutor);

  // -- END REGISTER MODULES --

  // register output module
  ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true);
  actuator->getModuleT()->init(platformInterface, platform);

  // use the configuration in order to set whether a module is activated or not
  const naoth::Configuration& config = Platform::getInstance().theConfiguration;

  list<string>::const_iterator name = getExecutionList().begin();
  for(;name != getExecutionList().end(); ++name)
  {
    bool active = false;
    if(config.hasKey("modules", *name)) {
      active = config.getBool("modules", *name);
    }
    if(active) {
      std::cout << "[Cognition] activating module " << *name << std::endl;
    }
    setModuleEnabled(*name, active);
  }//end for

  // auto-generate the execution list
  //calculateExecutionList();

  std::cout << "[Cognition] register end" << std::endl;

  stopwatch.start();
}//end init

void Cognition::call()
{
  // BEGIN cognition frame rate measuring
  stopwatch.stop();
  stopwatch.start();
  PLOT("Cognition.Cycle", stopwatch.lastValue);
  // END cognition frame rate measuring

  STOPWATCH_START("Cognition.Execute");

  // execute all modules
  list<AbstractModuleCreator*>::const_iterator iter;
  for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter)
  {
    AbstractModuleCreator* module = *iter;
    if (module != NULL && module->isEnabled())
    {
      std::string name(module->getModule()->getName());
      GT_TRACE("executing " << name);
      module->execute();
    }
  }

  STOPWATCH_STOP("Cognition.Execute");

  // HACK: reset all the debug stuff before executing the modules
  STOPWATCH_START("Cognition.Debug.Init");
  getDebugDrawings().reset();
  getDebugImageDrawings().reset();
  getDebugImageDrawingsTop().reset();
  getDebugDrawings3D().reset();
  STOPWATCH_STOP("Cognition.Debug.Init");
}//end call
<|endoftext|>


<commit_before>#include "pch.h"
#include "rdo_resources.h"
#include <rdortp.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace rdoMBuilder
{

// --------------------------------------------------------------------
// ----------
// --------------------------------------------------------------------
RDOResType::RDOResType( const RDOResType& obj )
{
	operator=( obj );
}

RDOResType::Param::Param( const RDOResType::Param& obj )
{
	operator=( obj );
}

RDOResource::RDOResource( const RDOResource& obj )
{
	operator=( obj );
}

void RDOResType::operator= (const RDOResType& obj )
{
	m_name   = obj.m_name;
	m_exist  = obj.m_exist;
	m_type   = obj.m_type;
	m_id     = obj.m_id;
	m_params = obj.m_params;
}

void RDOResType::Param::operator= (const RDOResType::Param& obj )
{
	m_name    = obj.m_name;
	m_exist   = obj.m_exist;
	m_type    = obj.m_type;
	m_id      = obj.m_id;
	m_min     = obj.m_min;
	m_max     = obj.m_max;
	m_default = obj.m_default;
}

void RDOResource::operator= (const RDOResource& obj )
{
	m_name   = obj.m_name;
	m_exist  = obj.m_exist;
	m_rtp    = obj.m_rtp;
	m_id     = obj.m_id;
	m_params.clear();
	Params::const_iterator it = obj.m_params.begin();
	while ( it != obj.m_params.end() )
	{
		m_params[ it->first ] = it->second;
		it++;
	}
}

// --------------------------------------------------------------------
// ---------- RDOResType
// --------------------------------------------------------------------
// ----
// ----
// --------------------------------------------------------------------
RDOResType::RDOResType( const rdoParse::RDORTPResType& rtp ):
	m_name( rtp.name() ),
	m_type( rtp.isPermanent() ? rt_permanent : rt_temporary ),
	m_exist( true ),
	m_id( rtp.getNumber() )
{
	std::vector< const rdoParse::RDORTPParam* >::const_iterator param_it = rtp.getParams().begin();
	while ( param_it != rtp.getParams().end() )
	{
		Param param( **param_it );
		param.m_id = m_params.size();
		m_params.append( param );
		param_it++;
	}
}

RDOResType::Param::Param( const rdoParse::RDORTPParam& param ):
	m_name( param.name() ),
	m_type( &param.getType()->type().type() ),
	m_exist( true ),
	m_id( -1 )
{
	switch ( typeID() )
	{
		case rdoRuntime::RDOType::t_int:
		{
			const rdoParse::RDORTPIntParamType* param_type = static_cast<const rdoParse::RDORTPIntParamType*>(param.getType());
			if ( param_type->getDiap().isExist() ) {
				m_min = param_type->getDiap().getMin();
				m_max = param_type->getDiap().getMax();
			}
			break;
		}
		case rdoRuntime::RDOType::t_real:
		{
			const rdoParse::RDORTPRealParamType* param_type = static_cast<const rdoParse::RDORTPRealParamType*>(param.getType());
			if ( param_type->getDiap().isExist() ) {
				m_min = param_type->getDiap().getMin();
				m_max = param_type->getDiap().getMax();
			}
			break;
		}
	}
	if ( param.getType()->getDV().isExist() )
	{
		m_default = param.getType()->getDefaultValue( param.getType()->getDV().value() );
	}
}

// --------------------------------------------------------------------
// ----  **
// --------------------------------------------------------------------
RDOResType::RDOResType( const std::string& name, Type type ):
	m_name( name ),
	m_type( type ),
	m_exist( false ),
	m_id( -1 )
{

}

bool RDOResType::ParamList::append( Param& param )
{
	if ( std::find_if(begin(), end(), rdoParse::compareNameRef<Param>(param.name())) == end() )
	{
		m_list.push_back( param );
		return true;
	}
	else
	{
		return false;
	}
}

RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOType* type, const rdoRuntime::RDOValue& def ):
	m_name( name ),
	m_type( type ),
	m_default( def ),
	m_exist( true ),
	m_id( -1 )
{
	if (type->id() == rdoRuntime::RDOType::t_enum && def.typeID() == rdoRuntime::RDOType::t_string)
	{
		m_default = rdoRuntime::RDOValue(getEnum(), def.getAsString());
	}
}

RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOValue& def ):
	m_name( name ),
	m_type( &def.type() ),
	m_default( def ),
	m_exist( true ),
	m_id( -1 )
{
}

RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOValue& min, const rdoRuntime::RDOValue& max, const rdoRuntime::RDOValue& def ):
	m_name( name ),
	m_type( &rdoRuntime::RDOType::getTypeByID(min.typeID()) ),
	m_min( min ),
	m_max( max ),
	m_default( def ),
	m_exist( true ),
	m_id( -1 )
{
}

void RDOResType::Param::setDiap( const rdoRuntime::RDOValue& min, const rdoRuntime::RDOValue& max )
{
	m_min = min;
	m_max = max;
}

void RDOResType::Param::setDefault( const rdoRuntime::RDOValue& def )
{
	m_default = def;
}

bool RDOResType::Param::operator== (const Param& param ) const
{
	return true;
}

// --------------------------------------------------------------------
// ---------- RDOResTypeList
// --------------------------------------------------------------------
// ----    ,
// --------------------------------------------------------------------
RDOResTypeList::RDOResTypeList( rdoParse::RDOParser* parser ):
	RDOList<RDOResType>( parser )
{
	std::vector< rdoParse::RDORTPResType* >::const_iterator rtp_it = m_parser->getRTPResTypes().begin();
	while ( rtp_it != m_parser->getRTPResTypes().end() ) {
		RDOResType rtp( **rtp_it );
		m_list.push_back( rtp );
		rtp_it++;
	}
}

// --------------------------------------------------------------------
// ----  **
// --------------------------------------------------------------------
bool RDOResTypeList::append( RDOResType& rtp )
{
	if ( std::find_if(begin(), end(), rdoParse::compareNameRef<RDOResType>(rtp.name())) == end() )
	{
		rdoParse::RDORTPResType* pRTP = new rdoParse::RDORTPResType( m_parser, rtp.name(), rtp.isPermanent() );
		RDOResType::ParamList::List::const_iterator param = rtp.m_params.begin();
		while ( param != rtp.m_params.end() )
		{
			rdoParse::RDORTPParamType* pParamType = NULL;
			switch ( param->typeID() )
			{
				case rdoRuntime::RDOType::t_int:
				{
					rdoParse::RDORTPIntDiap* pDiap;
					if ( param->hasDiap() )
					{
						pDiap = new rdoParse::RDORTPIntDiap( m_parser, param->getMin().getInt(), param->getMax().getInt() );
					}
					else
					{
						pDiap = new rdoParse::RDORTPIntDiap( m_parser );
					}
					rdoParse::RDORTPDefVal* pDef;
					if ( param->hasDefault() )
					{
						pDef = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() );
					}
					else
					{
						pDef = new rdoParse::RDORTPDefVal( m_parser );
					}
					pParamType = new rdoParse::RDORTPIntParamType( m_parser, pDiap, pDef );
					break;
				}
				case rdoRuntime::RDOType::t_real:
				{
					rdoParse::RDORTPRealDiap* pDiap;
					if ( param->hasDiap() )
					{
						pDiap = new rdoParse::RDORTPRealDiap( m_parser, param->getMin().getDouble(), param->getMax().getDouble() );
					}
					else
					{
						pDiap = new rdoParse::RDORTPRealDiap( m_parser );
					}
					rdoParse::RDORTPDefVal* pDef;
					if ( param->hasDefault() )
					{
						pDef = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() );
					}
					else
					{
						pDef = new rdoParse::RDORTPDefVal( m_parser );
					}
					pParamType = new rdoParse::RDORTPRealParamType( m_parser, pDiap, pDef );
					break;
				}
				case rdoRuntime::RDOType::t_enum:
				{
					rdoParse::RDORTPEnum* pEnum = NULL;
					rdoRuntime::RDOEnumType::CIterator enum_it = param->getEnum().begin();
					while ( enum_it != param->getEnum().end() )
					{
						if ( !pEnum )
						{
							pEnum = new rdoParse::RDORTPEnum( pRTP, rdoParse::RDOValue::getIdentificator(*enum_it) );
						}
						else
						{
							pEnum->add( rdoParse::RDOValue::getIdentificator(*enum_it) );
						}
						enum_it++;
					}
					rdoParse::RDORTPDefVal* pEnumDefValue;
					if ( param->hasDefault() )
					{
						pEnumDefValue = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() );
					}
					else
					{
						pEnumDefValue = new rdoParse::RDORTPDefVal( m_parser );
					}
					pParamType = new rdoParse::RDORTPEnumParamType( pRTP, pEnum, pEnumDefValue, rtp.name() );
					break;
				}
				default:
				{
					delete pRTP;
					return false;
				}
			}
			pRTP->addParam( new rdoParse::RDORTPParam( pRTP, param->name(), pParamType ) );
			param++;
		}
		rtp.m_exist = true;
		rtp.m_id    = pRTP->getNumber();
		m_list.push_back( rtp );
		return true;
	}
	else
	{
		return false;
	}
}

// --------------------------------------------------------------------
// ---------- RDOResource
// --------------------------------------------------------------------
// ----
// ----
// --------------------------------------------------------------------
RDOResource::RDOResource( const rdoParse::RDORSSResource& rss )
	: m_name (rss.name()    )
	, m_rtp  (*rss.getType())
	, m_exist(true          )
	, m_id   (rss.getID()   )
{
	if ( m_rtp.m_params.size() == rss.params().size() )
	{
		unsigned int index = 0;
		RDOResType::ParamList::List::const_iterator param_it = m_rtp.m_params.begin();
		while ( param_it != m_rtp.m_params.end() )
		{
//			const rdoRuntime::RDOValue& value = rss.params()[index];
//			m_params[param_it->name()] = rdoParse::RDOValue(value, rdoParse::RDOType(value.type()));
			m_params[param_it->name()] = rss.params()[index];
			index++;
			param_it++;
		}
	}
}

RDOResource::Params::const_iterator RDOResource::operator[] ( const std::string& param ) const
{
	return m_params.find(param);
}

RDOResource::Params::mapped_type& RDOResource::operator[] ( const std::string& param )
{
	RDOResource::Params::iterator param_it = m_params.find(param);
	if ( param_it != m_params.end() )
	{
		return param_it->second;
	}
	else
	{
		static Params::mapped_type tmpValue;
		return tmpValue;
	}
}

bool RDOResource::fillParserResourceParams(rdoParse::RDORSSResource* pRSS) const
{
	RDOResType::ParamList::List::const_iterator param_it = getType().m_params.begin();
	while ( param_it != getType().m_params.end() )
	{
		RDOResource::Params::const_iterator value_it = operator[](param_it->name());
		if ( value_it == end() )
		{
			return false;
		}
		pRSS->addParam( value_it->second );
		param_it++;
	}
	return true;
}

// --------------------------------------------------------------------
// ----  **
// --------------------------------------------------------------------
RDOResource::RDOResource( const RDOResType& rtp, const std::string& name )
	: m_name (name                                  )
	, m_rtp  (rtp                                   )
	, m_exist(false                                 )
	, m_id   (rdoParse::RDORSSResource::UNDEFINED_ID)
{
	RDOResType::ParamList::List::const_iterator param_it = m_rtp.m_params.begin();
	while ( param_it != m_rtp.m_params.end() )
	{
		rdoRuntime::RDOValue value( *param_it->type() );
		if ( param_it->hasDefault() )
		{
			value = param_it->getDefault();
		}
		else if ( param_it->hasDiap() )
		{
			value = param_it->getMin();
		}
		m_params[param_it->name()] = value;
		param_it++;
	}
}

// --------------------------------------------------------------------
// ---------- RDOResourceList
// --------------------------------------------------------------------
// ----   ,
// --------------------------------------------------------------------
RDOResourceList::RDOResourceList( rdoParse::RDOParser* parser ):
	RDOList<RDOResource>( parser )
{
	std::vector< rdoParse::RDORSSResource* >::const_iterator rss_it = m_parser->getRSSResources().begin();
	while ( rss_it != m_parser->getRSSResources().end() ) {
		RDOResource rss( **rss_it );
		m_list.push_back( rss );
		rss_it++;
	}
}

} // rdoMBuilder
<commit_msg>* откат к старой и неправильной логике работы mbuilder'а с enum-данными, чтобы можно было отлаживать RDOProcess<commit_after>#include "pch.h"
#include "rdo_resources.h"
#include <rdortp.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace rdoMBuilder
{

// --------------------------------------------------------------------
// ----------
// --------------------------------------------------------------------
RDOResType::RDOResType( const RDOResType& obj )
{
	operator=( obj );
}

RDOResType::Param::Param( const RDOResType::Param& obj )
{
	operator=( obj );
}

RDOResource::RDOResource( const RDOResource& obj )
{
	operator=( obj );
}

void RDOResType::operator= (const RDOResType& obj )
{
	m_name   = obj.m_name;
	m_exist  = obj.m_exist;
	m_type   = obj.m_type;
	m_id     = obj.m_id;
	m_params = obj.m_params;
}

void RDOResType::Param::operator= (const RDOResType::Param& obj )
{
	m_name    = obj.m_name;
	m_exist   = obj.m_exist;
	m_type    = obj.m_type;
	m_id      = obj.m_id;
	m_min     = obj.m_min;
	m_max     = obj.m_max;
	m_default = obj.m_default;
}

void RDOResource::operator= (const RDOResource& obj )
{
	m_name   = obj.m_name;
	m_exist  = obj.m_exist;
	m_rtp    = obj.m_rtp;
	m_id     = obj.m_id;
	m_params.clear();
	Params::const_iterator it = obj.m_params.begin();
	while ( it != obj.m_params.end() )
	{
		m_params[ it->first ] = it->second;
		it++;
	}
}

// --------------------------------------------------------------------
// ---------- RDOResType
// --------------------------------------------------------------------
// ----
// ----
// --------------------------------------------------------------------
RDOResType::RDOResType( const rdoParse::RDORTPResType& rtp ):
	m_name( rtp.name() ),
	m_type( rtp.isPermanent() ? rt_permanent : rt_temporary ),
	m_exist( true ),
	m_id( rtp.getNumber() )
{
	std::vector< const rdoParse::RDORTPParam* >::const_iterator param_it = rtp.getParams().begin();
	while ( param_it != rtp.getParams().end() )
	{
		Param param( **param_it );
		param.m_id = m_params.size();
		m_params.append( param );
		param_it++;
	}
}

RDOResType::Param::Param( const rdoParse::RDORTPParam& param ):
	m_name( param.name() ),
	m_type( &param.getType()->type().type() ),
	m_exist( true ),
	m_id( -1 )
{
	switch ( typeID() )
	{
		case rdoRuntime::RDOType::t_int:
		{
			const rdoParse::RDORTPIntParamType* param_type = static_cast<const rdoParse::RDORTPIntParamType*>(param.getType());
			if ( param_type->getDiap().isExist() ) {
				m_min = param_type->getDiap().getMin();
				m_max = param_type->getDiap().getMax();
			}
			break;
		}
		case rdoRuntime::RDOType::t_real:
		{
			const rdoParse::RDORTPRealParamType* param_type = static_cast<const rdoParse::RDORTPRealParamType*>(param.getType());
			if ( param_type->getDiap().isExist() ) {
				m_min = param_type->getDiap().getMin();
				m_max = param_type->getDiap().getMax();
			}
			break;
		}
	}
	if ( param.getType()->getDV().isExist() )
	{
		m_default = param.getType()->getDefaultValue( param.getType()->getDV().value() );
	}
}

// --------------------------------------------------------------------
// ----  **
// --------------------------------------------------------------------
RDOResType::RDOResType( const std::string& name, Type type ):
	m_name( name ),
	m_type( type ),
	m_exist( false ),
	m_id( -1 )
{

}

bool RDOResType::ParamList::append( Param& param )
{
	if ( std::find_if(begin(), end(), rdoParse::compareNameRef<Param>(param.name())) == end() )
	{
		m_list.push_back( param );
		return true;
	}
	else
	{
		return false;
	}
}

RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOType* type, const rdoRuntime::RDOValue& def ):
	m_name( name ),
	m_type( type ),
	m_default( def ),
	m_exist( true ),
	m_id( -1 )
{
	if (type->id() == rdoRuntime::RDOType::t_enum && def.typeID() == rdoRuntime::RDOType::t_string)
	{
//		m_default = rdoRuntime::RDOValue(getEnum(), def.getAsString());
	}
}

RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOValue& def ):
	m_name( name ),
	m_type( &def.type() ),
	m_default( def ),
	m_exist( true ),
	m_id( -1 )
{
}

RDOResType::Param::Param( const std::string& name, const rdoRuntime::RDOValue& min, const rdoRuntime::RDOValue& max, const rdoRuntime::RDOValue& def ):
	m_name( name ),
	m_type( &rdoRuntime::RDOType::getTypeByID(min.typeID()) ),
	m_min( min ),
	m_max( max ),
	m_default( def ),
	m_exist( true ),
	m_id( -1 )
{
}

void RDOResType::Param::setDiap( const rdoRuntime::RDOValue& min, const rdoRuntime::RDOValue& max )
{
	m_min = min;
	m_max = max;
}

void RDOResType::Param::setDefault( const rdoRuntime::RDOValue& def )
{
	m_default = def;
}

bool RDOResType::Param::operator== (const Param& param ) const
{
	return true;
}

// --------------------------------------------------------------------
// ---------- RDOResTypeList
// --------------------------------------------------------------------
// ----    ,
// --------------------------------------------------------------------
RDOResTypeList::RDOResTypeList( rdoParse::RDOParser* parser ):
	RDOList<RDOResType>( parser )
{
	std::vector< rdoParse::RDORTPResType* >::const_iterator rtp_it = m_parser->getRTPResTypes().begin();
	while ( rtp_it != m_parser->getRTPResTypes().end() ) {
		RDOResType rtp( **rtp_it );
		m_list.push_back( rtp );
		rtp_it++;
	}
}

// --------------------------------------------------------------------
// ----  **
// --------------------------------------------------------------------
bool RDOResTypeList::append( RDOResType& rtp )
{
	if ( std::find_if(begin(), end(), rdoParse::compareNameRef<RDOResType>(rtp.name())) == end() )
	{
		rdoParse::RDORTPResType* pRTP = new rdoParse::RDORTPResType( m_parser, rtp.name(), rtp.isPermanent() );
		RDOResType::ParamList::List::const_iterator param = rtp.m_params.begin();
		while ( param != rtp.m_params.end() )
		{
			rdoParse::RDORTPParamType* pParamType = NULL;
			switch ( param->typeID() )
			{
				case rdoRuntime::RDOType::t_int:
				{
					rdoParse::RDORTPIntDiap* pDiap;
					if ( param->hasDiap() )
					{
						pDiap = new rdoParse::RDORTPIntDiap( m_parser, param->getMin().getInt(), param->getMax().getInt() );
					}
					else
					{
						pDiap = new rdoParse::RDORTPIntDiap( m_parser );
					}
					rdoParse::RDORTPDefVal* pDef;
					if ( param->hasDefault() )
					{
						pDef = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() );
					}
					else
					{
						pDef = new rdoParse::RDORTPDefVal( m_parser );
					}
					pParamType = new rdoParse::RDORTPIntParamType( m_parser, pDiap, pDef );
					break;
				}
				case rdoRuntime::RDOType::t_real:
				{
					rdoParse::RDORTPRealDiap* pDiap;
					if ( param->hasDiap() )
					{
						pDiap = new rdoParse::RDORTPRealDiap( m_parser, param->getMin().getDouble(), param->getMax().getDouble() );
					}
					else
					{
						pDiap = new rdoParse::RDORTPRealDiap( m_parser );
					}
					rdoParse::RDORTPDefVal* pDef;
					if ( param->hasDefault() )
					{
						pDef = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() );
					}
					else
					{
						pDef = new rdoParse::RDORTPDefVal( m_parser );
					}
					pParamType = new rdoParse::RDORTPRealParamType( m_parser, pDiap, pDef );
					break;
				}
				case rdoRuntime::RDOType::t_enum:
				{
					rdoParse::RDORTPEnum* pEnum = NULL;
					rdoRuntime::RDOEnumType::CIterator enum_it = param->getEnum().begin();
					while ( enum_it != param->getEnum().end() )
					{
						if ( !pEnum )
						{
							pEnum = new rdoParse::RDORTPEnum( pRTP, rdoParse::RDOValue::getIdentificator(*enum_it) );
						}
						else
						{
							pEnum->add( rdoParse::RDOValue::getIdentificator(*enum_it) );
						}
						enum_it++;
					}
					rdoParse::RDORTPDefVal* pEnumDefValue;
					if ( param->hasDefault() )
					{
						pEnumDefValue = new rdoParse::RDORTPDefVal( m_parser, param->getDefault() );
					}
					else
					{
						pEnumDefValue = new rdoParse::RDORTPDefVal( m_parser );
					}
					pParamType = new rdoParse::RDORTPEnumParamType( pRTP, pEnum, pEnumDefValue, rtp.name() );
					break;
				}
				default:
				{
					delete pRTP;
					return false;
				}
			}
			pRTP->addParam( new rdoParse::RDORTPParam( pRTP, param->name(), pParamType ) );
			param++;
		}
		rtp.m_exist = true;
		rtp.m_id    = pRTP->getNumber();
		m_list.push_back( rtp );
		return true;
	}
	else
	{
		return false;
	}
}

// --------------------------------------------------------------------
// ---------- RDOResource
// --------------------------------------------------------------------
// ----
// ----
// --------------------------------------------------------------------
RDOResource::RDOResource( const rdoParse::RDORSSResource& rss )
	: m_name (rss.name()    )
	, m_rtp  (*rss.getType())
	, m_exist(true          )
	, m_id   (rss.getID()   )
{
	if ( m_rtp.m_params.size() == rss.params().size() )
	{
		unsigned int index = 0;
		RDOResType::ParamList::List::const_iterator param_it = m_rtp.m_params.begin();
		while ( param_it != m_rtp.m_params.end() )
		{
//			const rdoRuntime::RDOValue& value = rss.params()[index];
//			m_params[param_it->name()] = rdoParse::RDOValue(value, rdoParse::RDOType(value.type()));
			m_params[param_it->name()] = rss.params()[index];
			index++;
			param_it++;
		}
	}
}

RDOResource::Params::const_iterator RDOResource::operator[] ( const std::string& param ) const
{
	return m_params.find(param);
}

RDOResource::Params::mapped_type& RDOResource::operator[] ( const std::string& param )
{
	RDOResource::Params::iterator param_it = m_params.find(param);
	if ( param_it != m_params.end() )
	{
		return param_it->second;
	}
	else
	{
		static Params::mapped_type tmpValue;
		return tmpValue;
	}
}

bool RDOResource::fillParserResourceParams(rdoParse::RDORSSResource* pRSS) const
{
	RDOResType::ParamList::List::const_iterator param_it = getType().m_params.begin();
	while ( param_it != getType().m_params.end() )
	{
		RDOResource::Params::const_iterator value_it = operator[](param_it->name());
		if ( value_it == end() )
		{
			return false;
		}
		pRSS->addParam( value_it->second );
		param_it++;
	}
	return true;
}

// --------------------------------------------------------------------
// ----  **
// --------------------------------------------------------------------
RDOResource::RDOResource( const RDOResType& rtp, const std::string& name )
	: m_name (name                                  )
	, m_rtp  (rtp                                   )
	, m_exist(false                                 )
	, m_id   (rdoParse::RDORSSResource::UNDEFINED_ID)
{
	RDOResType::ParamList::List::const_iterator param_it = m_rtp.m_params.begin();
	while ( param_it != m_rtp.m_params.end() )
	{
		rdoRuntime::RDOValue value( *param_it->type() );
		if ( param_it->hasDefault() )
		{
			value = param_it->getDefault();
		}
		else if ( param_it->hasDiap() )
		{
			value = param_it->getMin();
		}
		m_params[param_it->name()] = value;
		param_it++;
	}
}

// --------------------------------------------------------------------
// ---------- RDOResourceList
// --------------------------------------------------------------------
// ----   ,
// --------------------------------------------------------------------
RDOResourceList::RDOResourceList( rdoParse::RDOParser* parser ):
	RDOList<RDOResource>( parser )
{
	std::vector< rdoParse::RDORSSResource* >::const_iterator rss_it = m_parser->getRSSResources().begin();
	while ( rss_it != m_parser->getRSSResources().end() ) {
		RDOResource rss( **rss_it );
		m_list.push_back( rss );
		rss_it++;
	}
}

} // rdoMBuilder
<|endoftext|>


<commit_before>//Copyright (c) 2013 Christopher Johnstone(meson800)
//The MIT License - See ../../../LICENSE for more info

#include "MacroExpander.h"

void MacroExpander::expandString(std::string& string)
{
	//loop while we still have macros (defined by angle brackets)
	while (string.find(">") != std::string::npos)
	{
		int firstPos, secondPos, length;
		firstPos = string.find_first_of("<");
		secondPos = string.find_first_of(">");
		length = secondPos - firstPos;

		//check that we found them
		if (firstPos != -1 && secondPos != -1)
		{
			string.replace(firstPos, length, macroToText(string.substr(firstPos, length)));
		}
	}
}

std::string MacroExpander::macroToText(std::string macro)
{
	VESSEL * focusVessel = oapiGetFocusInterface();
	//format is <name option i decimalPlaces>
	double value;

	//get macro name, id, and possibly int
	char name[256];
	int option;
	int decimalPlaces;

	int numArguments = sscanf("<%255s %i i %i", name, &option, &decimalPlaces);
	std::string type_name = name;

	//switch different macros
	if (type_name.compare("fuel_percent") == 0)
	{
		PROPELLANT_HANDLE fuel_handle = focusVessel->GetPropellantHandleByIndex(option);
		value = oapiGetPropellantMass(fuel_handle) / oapiGetPropellantMaxMass(fuel_handle);
	}
	else if (type_name.compare("fuel_mass") == 0)
	{
		if (option == -1)
		{
			value = focusVessel->GetTotalPropellantMass();
		}
		else
		{
			PROPELLANT_HANDLE fuel_handle = focusVessel->GetPropellantHandleByIndex(option);
			value = oapiGetPropellantMass(fuel_handle);
		}

	}

	std::ostringstream toStringConverter;
	if (numArguments >= 3)
	{
		//convert value to integer
		toStringConverter << doubleToDecimalInt(value, decimalPlaces);
	}
	else
	{
		//just return the double
		toStringConverter << value;
	}
	return toStringConverter.str();
}

int MacroExpander::doubleToDecimalInt(double value, int decimalPlaces)
{
	return (int)(value * (10 * decimalPlaces));
}<commit_msg>Fixed bug where MacroExpander would not correctly expand<commit_after>//Copyright (c) 2013 Christopher Johnstone(meson800)
//The MIT License - See ../../../LICENSE for more info

#include "MacroExpander.h"

void MacroExpander::expandString(std::string& string)
{
	//loop while we still have macros (defined by angle brackets)
	while (string.find(">") != std::string::npos)
	{
		int firstPos, secondPos, length;
		firstPos = string.find_first_of("<");
		secondPos = string.find_first_of(">");
		length = secondPos - firstPos + 1;

		//check that we found them
		if (firstPos != -1 && secondPos != -1)
		{
			string.replace(firstPos, length, macroToText(string.substr(firstPos, length)));
		}
	}
}

std::string MacroExpander::macroToText(std::string macro)
{
	VESSEL * focusVessel = oapiGetFocusInterface();
	//format is <name option i decimalPlaces>
	double value;

	//get macro name, id, and possibly int
	char name[256];
	int option;
	int decimalPlaces;

	int numArguments = sscanf(macro.c_str(),"<%255s %i i %i>", name, &option, &decimalPlaces);
	std::string type_name = name;

	//switch different macros
	if (type_name.compare("fuel_percent") == 0)
	{
		PROPELLANT_HANDLE fuel_handle = focusVessel->GetPropellantHandleByIndex(option);
		value = oapiGetPropellantMass(fuel_handle) / oapiGetPropellantMaxMass(fuel_handle);
	}
	else if (type_name.compare("fuel_mass") == 0)
	{
		if (option == -1)
		{
			value = focusVessel->GetTotalPropellantMass();
		}
		else
		{
			PROPELLANT_HANDLE fuel_handle = focusVessel->GetPropellantHandleByIndex(option);
			value = oapiGetPropellantMass(fuel_handle);
		}

	}

	std::ostringstream toStringConverter;
	if (numArguments >= 3)
	{
		//convert value to integer
		toStringConverter << doubleToDecimalInt(value, decimalPlaces);
	}
	else
	{
		//just return the double
		toStringConverter << value;
	}
	return toStringConverter.str();
}

int MacroExpander::doubleToDecimalInt(double value, int decimalPlaces)
{
	return (int)(value * pow((double)10,(double)decimalPlaces));
}<|endoftext|>


<commit_before>//
// Class AliRsnCutPrimaryVertex
//
// This cut implementation checks the quality of event primary vertex.
// It currently works only with ESD events (not AOD).
//
// authors: Martin Vala (martin.vala@cern.ch)
//          Alberto Pulvirenti (alberto.pulvirenti@ct.infn.it)
//

#include "AliRsnCutPrimaryVertex.h"

ClassImp(AliRsnCutPrimaryVertex)

//_________________________________________________________________________________________________
AliRsnCutPrimaryVertex::AliRsnCutPrimaryVertex() :
  AliRsnCut(AliRsnCut::kEvent),
  fAcceptTPC(kFALSE)
{
//
// Default constructor.
//
}

//_________________________________________________________________________________________________
AliRsnCutPrimaryVertex::AliRsnCutPrimaryVertex
(const char *name, Double_t maxVz, Int_t nContributors, Bool_t acceptTPC) :
  AliRsnCut(name, AliRsnCut::kEvent, 0, nContributors - 1),
  fAcceptTPC(acceptTPC)
{
//
// Main constructor.
// Defines the cut range between 0 and
// the minimum required number of contributors.
// The cut will be passed when if the event has a
// primary vertex with number of contributors outside this interval.
// ---
// If the 'acceptTPC' argument is true, events with TPC
// primary vertex will be checked, otherwise they will be
// rejected by default.
// ---
// Since the range check uses the '>=' and '<=', the high edge
// must be decreased by 1 to get the right behaviour, since this is integer.
//

  fMinD = 0.0;
  fMaxD = maxVz + 1E-6;
}

//_________________________________________________________________________________________________
Bool_t AliRsnCutPrimaryVertex::IsSelected(TObject *obj1, TObject* /*obj2*/)
{
//
// Cut checker
//

  static Int_t evNum = 0;
  evNum++;

  // retrieve ESD event
  AliRsnEvent *rsn = dynamic_cast<AliRsnEvent*>(obj1);
  if (!rsn) return kFALSE;
  AliESDEvent *esd = dynamic_cast<AliESDEvent*>(rsn->GetRef());
  AliAODEvent *aod = dynamic_cast<AliAODEvent*>(rsn->GetRef());

  if (esd)
  {
    // get the best primary vertex:
    // first try the one with tracks
    const AliESDVertex *vTrk  = esd->GetPrimaryVertexTracks();
    const AliESDVertex *vSPD  = esd->GetPrimaryVertexSPD();
    const AliESDVertex *vTPC  = esd->GetPrimaryVertexTPC();
    Int_t               ncTrk = -1;
    Int_t               ncSPD = -1;
    Int_t               ncTPC = -1;
    Double_t            vzTrk = 2.0 * fMaxD;
    Double_t            vzSPD = 2.0 * fMaxD;
    Double_t            vzTPC = 2.0 * fMaxD;
    if (vTrk) vzTrk = TMath::Abs(vTrk->GetZv());
    if (vSPD) vzSPD = TMath::Abs(vSPD->GetZv());
    if (vTPC) vzTPC = TMath::Abs(vTPC->GetZv());
    if (vTrk) ncTrk = (Int_t)vTrk->GetNContributors();
    if (vSPD) ncSPD = (Int_t)vSPD->GetNContributors();
    if (vTPC) ncTPC = (Int_t)vTPC->GetNContributors();
    if(vTrk && ncTrk > 0)
    {
      fCutValueI = ncTrk;
      fCutValueD = vzTrk;
    }
    else if (vSPD && ncSPD > 0)
    {
      fCutValueI = ncSPD;
      fCutValueD = vzSPD;
    }
    else if (vTPC && fAcceptTPC && ncTPC > 0)
    {
      fCutValueI = ncTPC;
      fCutValueD = vzTPC;
    }
    else
    {
      fCutValueI = -1;
      fCutValueD = 2.0 * fMaxD;
    }
  }
  else if (aod)
  {
    // lines suggested by Andrea to reject TPC-only events
    if(!aod->GetPrimaryVertexSPD()) return kFALSE;
    //PH    if(!aod->GetPrimaryVertexSPD()->Status()) return kFALSE;

    AliAODVertex *prim = (AliAODVertex*)aod->GetPrimaryVertex();
    fCutValueI = prim->GetNContributors();
    //PH    fCutValueD = prim->Zv();
    fCutValueD = prim->GetZ();
  }
  else
    return kFALSE;

  // output
  Bool_t result = ((!OkRangeI()) && OkRangeD());
  return result;
}

<commit_msg>Compilation error corrected<commit_after>//
// Class AliRsnCutPrimaryVertex
//
// This cut implementation checks the quality of event primary vertex.
// It currently works only with ESD events (not AOD).
//
// authors: Martin Vala (martin.vala@cern.ch)
//          Alberto Pulvirenti (alberto.pulvirenti@ct.infn.it)
//

#include "AliRsnCutPrimaryVertex.h"

ClassImp(AliRsnCutPrimaryVertex)

//_________________________________________________________________________________________________
AliRsnCutPrimaryVertex::AliRsnCutPrimaryVertex() :
  AliRsnCut(AliRsnCut::kEvent),
  fAcceptTPC(kFALSE)
{
//
// Default constructor.
//
}

//_________________________________________________________________________________________________
AliRsnCutPrimaryVertex::AliRsnCutPrimaryVertex
(const char *name, Double_t maxVz, Int_t nContributors, Bool_t acceptTPC) :
  AliRsnCut(name, AliRsnCut::kEvent, 0, nContributors - 1),
  fAcceptTPC(acceptTPC)
{
//
// Main constructor.
// Defines the cut range between 0 and
// the minimum required number of contributors.
// The cut will be passed when if the event has a
// primary vertex with number of contributors outside this interval.
// ---
// If the 'acceptTPC' argument is true, events with TPC
// primary vertex will be checked, otherwise they will be
// rejected by default.
// ---
// Since the range check uses the '>=' and '<=', the high edge
// must be decreased by 1 to get the right behaviour, since this is integer.
//

  fMinD = 0.0;
  fMaxD = maxVz + 1E-6;
}

//_________________________________________________________________________________________________
Bool_t AliRsnCutPrimaryVertex::IsSelected(TObject *obj1, TObject* /*obj2*/)
{
//
// Cut checker
//

  static Int_t evNum = 0;
  evNum++;

  // retrieve ESD event
  AliRsnEvent *rsn = dynamic_cast<AliRsnEvent*>(obj1);
  if (!rsn) return kFALSE;
  AliESDEvent *esd = dynamic_cast<AliESDEvent*>(rsn->GetRef());
  AliAODEvent *aod = dynamic_cast<AliAODEvent*>(rsn->GetRef());

  if (esd)
  {
    // get the best primary vertex:
    // first try the one with tracks
    const AliESDVertex *vTrk  = esd->GetPrimaryVertexTracks();
    const AliESDVertex *vSPD  = esd->GetPrimaryVertexSPD();
    const AliESDVertex *vTPC  = esd->GetPrimaryVertexTPC();
    Int_t               ncTrk = -1;
    Int_t               ncSPD = -1;
    Int_t               ncTPC = -1;
    Double_t            vzTrk = 2.0 * fMaxD;
    Double_t            vzSPD = 2.0 * fMaxD;
    Double_t            vzTPC = 2.0 * fMaxD;
    if (vTrk) vzTrk = TMath::Abs(vTrk->GetZv());
    if (vSPD) vzSPD = TMath::Abs(vSPD->GetZv());
    if (vTPC) vzTPC = TMath::Abs(vTPC->GetZv());
    if (vTrk) ncTrk = (Int_t)vTrk->GetNContributors();
    if (vSPD) ncSPD = (Int_t)vSPD->GetNContributors();
    if (vTPC) ncTPC = (Int_t)vTPC->GetNContributors();
    if(vTrk && ncTrk > 0)
    {
      fCutValueI = ncTrk;
      fCutValueD = vzTrk;
    }
    else if (vSPD && ncSPD > 0)
    {
      fCutValueI = ncSPD;
      fCutValueD = vzSPD;
    }
    else if (vTPC && fAcceptTPC && ncTPC > 0)
    {
      fCutValueI = ncTPC;
      fCutValueD = vzTPC;
    }
    else
    {
      fCutValueI = -1;
      fCutValueD = 2.0 * fMaxD;
    }
  }
  else if (aod)
  {
    // lines suggested by Andrea to reject TPC-only events
    if(!aod->GetPrimaryVertexSPD()) return kFALSE;
    if(aod->GetPrimaryVertexSPD()->GetNContributors() < 1) return kFALSE;

    AliAODVertex *prim = (AliAODVertex*)aod->GetPrimaryVertex();
    fCutValueI = prim->GetNContributors();
    fCutValueD = prim->GetZ();
  }
  else
    return kFALSE;

  // output
  Bool_t result = ((!OkRangeI()) && OkRangeD());
  return result;
}

<|endoftext|>


<commit_before>#include "ExecutionEngine.h"

#include <chrono>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"

#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>

#pragma GCC diagnostic pop

#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
#include "Compiler.h"
#include "Cache.h"

namespace dev
{
namespace eth
{
namespace jit
{

ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)
{
	std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
	/*if (auto cachedExec = Cache::findExec(key))
	{
		return run(*cachedExec, _data, _env);
	}*/

	auto module = Compiler({}).compile(_code);
	//module->dump();
	return run(std::move(module), _data, _env, _code);
}

ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)
{
	llvm::sys::PrintStackTraceOnErrorSignal();
	static const auto program = "EVM JIT";
	llvm::PrettyStackTraceProgram X(1, &program);

	llvm::InitializeNativeTargetAsmPrinter();

	llvm::EngineBuilder builder(_module.get());
	builder.setEngineKind(llvm::EngineKind::JIT);
	builder.setUseMCJIT(true);
	builder.setOptLevel(llvm::CodeGenOpt::None);

	auto triple = llvm::Triple(llvm::sys::getProcessTriple());
	if (triple.getOS() == llvm::Triple::OSType::Win32)
		triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF);  // MCJIT does not support COFF format
	_module->setTargetTriple(triple.str());

	ExecBundle exec;
	exec.engine.reset(builder.create());
	if (!exec.engine)
		return ReturnCode::LLVMConfigError;
	_module.release();        // Successfully created llvm::ExecutionEngine takes ownership of the module

	exec.engine->setObjectCache(Cache::getObjectCache());

	// TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used
	//auto finalizationStartTime = std::chrono::high_resolution_clock::now();
	//exec.engine->finalizeObject();
	//auto finalizationEndTime = std::chrono::high_resolution_clock::now();
	//clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();

	auto executionStartTime = std::chrono::high_resolution_clock::now();

	std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
	//auto& cachedExec = Cache::registerExec(key, std::move(exec));
	auto returnCode = run(exec, _data, _env);

	auto executionEndTime = std::chrono::high_resolution_clock::now();
	clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms ";
	//clog(JIT) << "Max stack size: " << Stack::maxStackSize;

	clog(JIT) << "\n";

	return returnCode;
}

namespace
{
ReturnCode runEntryFunc(ExecBundle const& _exec, Runtime* _runtime)
{
	// That function uses long jumps to handle "execeptions".
	// Do not create any non-POD objects here

	// TODO:
	// Getting pointer to function seems to be cachable,
	// but it looks like getPointerToFunction() method does something special
	// to allow function to be executed.
	// That might be related to memory manager. Can we share one?
	typedef ReturnCode(*EntryFuncPtr)(Runtime*);
	auto entryFuncPtr = (EntryFuncPtr)_exec.engine->getFunctionAddress("main");

	ReturnCode returnCode{};
	auto sj = setjmp(_runtime->getJmpBuf());
	if (sj == 0)
		returnCode = entryFuncPtr(_runtime);
	else
		returnCode = static_cast<ReturnCode>(sj);

	return returnCode;
}
}

ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env)
{
	Runtime runtime(_data, _env);
	auto returnCode = runEntryFunc(_exec, &runtime);
	if (returnCode == ReturnCode::Return)
		this->returnData = runtime.getReturnData();
	return returnCode;
}

}
}
}
<commit_msg>Execution Engine cleanups (reverted from commit bd85efa299e661228a1ac6283b5fad14e09f88d9)<commit_after>#include "ExecutionEngine.h"

#include <chrono>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"

#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/ADT/Triple.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/Signals.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/Host.h>

#pragma GCC diagnostic pop

#include "Runtime.h"
#include "Memory.h"
#include "Stack.h"
#include "Type.h"
#include "Compiler.h"
#include "Cache.h"

namespace dev
{
namespace eth
{
namespace jit
{

ReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)
{
	std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
	/*if (auto cachedExec = Cache::findExec(key))
	{
		return run(*cachedExec, _data, _env);
	}*/

	auto module = Compiler({}).compile(_code);
	//module->dump();
	return run(std::move(module), _data, _env, _code);
}

ReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)
{
	llvm::sys::PrintStackTraceOnErrorSignal();
	static const auto program = "EVM JIT";
	llvm::PrettyStackTraceProgram X(1, &program);

	llvm::InitializeNativeTarget();
	llvm::InitializeNativeTargetAsmPrinter();

	llvm::EngineBuilder builder(_module.get());
	builder.setEngineKind(llvm::EngineKind::JIT);
	builder.setUseMCJIT(true);
	std::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager);
	builder.setMCJITMemoryManager(memoryManager.get());
	builder.setOptLevel(llvm::CodeGenOpt::None);

	auto triple = llvm::Triple(llvm::sys::getProcessTriple());
	if (triple.getOS() == llvm::Triple::OSType::Win32)
		triple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF);  // MCJIT does not support COFF format
	_module->setTargetTriple(triple.str());

	ExecBundle exec;
	exec.engine.reset(builder.create());
	if (!exec.engine)
		return ReturnCode::LLVMConfigError;
	_module.release();        // Successfully created llvm::ExecutionEngine takes ownership of the module
	memoryManager.release();  // and memory manager

	exec.engine->setObjectCache(Cache::getObjectCache());

	// TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used
	//auto finalizationStartTime = std::chrono::high_resolution_clock::now();
	//exec.engine->finalizeObject();
	//auto finalizationEndTime = std::chrono::high_resolution_clock::now();
	//clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();

	auto executionStartTime = std::chrono::high_resolution_clock::now();

	std::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};
	//auto& cachedExec = Cache::registerExec(key, std::move(exec));
	auto returnCode = run(exec, _data, _env);

	auto executionEndTime = std::chrono::high_resolution_clock::now();
	clog(JIT) << " + " << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << " ms ";
	//clog(JIT) << "Max stack size: " << Stack::maxStackSize;

	clog(JIT) << "\n";

	return returnCode;
}

namespace
{
ReturnCode runEntryFunc(ExecBundle const& _exec, Runtime* _runtime)
{
	// That function uses long jumps to handle "execeptions".
	// Do not create any non-POD objects here

	// TODO:
	// Getting pointer to function seems to be cachable,
	// but it looks like getPointerToFunction() method does something special
	// to allow function to be executed.
	// That might be related to memory manager. Can we share one?
	typedef ReturnCode(*EntryFuncPtr)(Runtime*);
	auto entryFuncPtr = (EntryFuncPtr)_exec.engine->getFunctionAddress("main");

	ReturnCode returnCode{};
	auto sj = setjmp(_runtime->getJmpBuf());
	if (sj == 0)
		returnCode = entryFuncPtr(_runtime);
	else
		returnCode = static_cast<ReturnCode>(sj);

	return returnCode;
}
}

ReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env)
{
	Runtime runtime(_data, _env);
	auto returnCode = runEntryFunc(_exec, &runtime);
	if (returnCode == ReturnCode::Return)
		this->returnData = runtime.getReturnData();
	return returnCode;
}

}
}
}
<|endoftext|>


<commit_before>AliAnalysisTask* AddTaskQAHighPtDeDx(Bool_t AnalysisMC = kFALSE,
			                         Int_t typerun =1, // 0 for pp and 1 for Pb-Pb or pPb
			                         TString  type ="ESD",
			                         UInt_t kTriggerInt = AliVEvent::kINT7, //for pPb kINT7, for pp or PbPb kMB
			                         Float_t minCent = 0.,
                                     Float_t maxCent = 80.,
			                         char *centralityEstimator = "V0A",//for pPb V0A for PbPb V0M
			                         Bool_t ispileuprej = kFALSE
                                    )
{
  // Creates a pid task and adds it to the analysis manager

  // Get the pointer to the existing analysis manager via the static
  //access method
  //=========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskHighPtDeDx", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the
  // analysis manager The availability of MC handler can also be
  // checked here.
  // =========================================================================
  if (!mgr->GetInputEventHandler()) {
    Error("AddTaskHighPtDeDx", "This task requires an input event handler");
    return NULL;
  }

  AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter");
  AliESDtrackCuts* esdTrackCutsGolden = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kTRUE,1);
  trackFilterGolden->AddCuts(esdTrackCutsGolden);

  AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC");
  AliESDtrackCuts* esdTrackCutsTPC =
    AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
  trackFilterTPC->AddCuts(esdTrackCutsTPC);

  AliAnalysisTaskQAHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskQAHighPtDeDx("taskHighPtDeDxpp");
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  taskHighPtDeDx->SetAnalysisType(type);
  taskHighPtDeDx->SetAnalysisMC(AnalysisMC);
  if(typerun==1){
    taskHighPtDeDx->SetAnalysisPbPb(kTRUE);
    taskHighPtDeDx->SetMinCent(minCent);
    taskHighPtDeDx->SetMaxCent(maxCent);
    taskHighPtDeDx->SetCentralityEstimator(centralityEstimator);
  }
  else
    taskHighPtDeDx->SetAnalysisPbPb(kFALSE);
  taskHighPtDeDx->SetDebugLevel(0);
  taskHighPtDeDx->SetEtaCut(0.8);
  taskHighPtDeDx->SetVtxCut(10.0);
  taskHighPtDeDx->SetTrigger(kTriggerInt);
  taskHighPtDeDx->SetPileUpRej(ispileuprej);
  //Set Filtesr
  taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden);
  taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC);
  taskHighPtDeDx->SetStoreMcIn(analysisMC);     // def: kFALSE

  mgr->AddTask(taskHighPtDeDx);

  // Create ONLY the output containers for the data produced by the
  // task.  Get and connect other common input/output containers via
  // the manager as below
  //=======================================================================

  AliAnalysisDataContainer *cout_histdedx;

  cout_histdedx=0;
  cout_histdedx = mgr->CreateContainer("outputdedx", TList::Class(), AliAnalysisManager::kOutputContainer, "QAHighPtDeDx.root");
  mgr->ConnectInput (taskHighPtDeDx, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskHighPtDeDx, 1, cout_histdedx);

  // Return task pointer at the end
  return taskHighPtDeDx;

}
<commit_msg>Further update of PWGLF QA macro<commit_after>AliAnalysisTask* AddTaskQAHighPtDeDx(Bool_t AnalysisMC = kFALSE,
			                         Int_t typerun =1, // 0 for pp and 1 for Pb-Pb or pPb
			                         TString  type ="ESD",
			                         UInt_t kTriggerInt = AliVEvent::kINT7, //for pPb kINT7, for pp or PbPb kMB
			                         Float_t minCent = 0.,
                                     Float_t maxCent = 80.,
			                         char *centralityEstimator = "V0A",//for pPb V0A for PbPb V0M
			                         Bool_t ispileuprej = kFALSE
                                    )
{
  // Creates a pid task and adds it to the analysis manager

  // Get the pointer to the existing analysis manager via the static
  //access method
  //=========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskHighPtDeDx", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the
  // analysis manager The availability of MC handler can also be
  // checked here.
  // =========================================================================
  if (!mgr->GetInputEventHandler()) {
    Error("AddTaskHighPtDeDx", "This task requires an input event handler");
    return NULL;
  }

  AliAnalysisFilter* trackFilterGolden = new AliAnalysisFilter("trackFilter");
  AliESDtrackCuts* esdTrackCutsGolden = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kTRUE,1);
  trackFilterGolden->AddCuts(esdTrackCutsGolden);

  AliAnalysisFilter* trackFilterTPC = new AliAnalysisFilter("trackFilterTPC");
  AliESDtrackCuts* esdTrackCutsTPC =
    AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
  trackFilterTPC->AddCuts(esdTrackCutsTPC);

  AliAnalysisTaskQAHighPtDeDx* taskHighPtDeDx = new AliAnalysisTaskQAHighPtDeDx("taskHighPtDeDxpp");
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  taskHighPtDeDx->SetAnalysisType(type);
  taskHighPtDeDx->SetAnalysisMC(AnalysisMC);
  if(typerun==1){
    taskHighPtDeDx->SetAnalysisPbPb(kTRUE);
    taskHighPtDeDx->SetMinCent(minCent);
    taskHighPtDeDx->SetMaxCent(maxCent);
    taskHighPtDeDx->SetCentralityEstimator(centralityEstimator);
  }
  else
    taskHighPtDeDx->SetAnalysisPbPb(kFALSE);
  taskHighPtDeDx->SetDebugLevel(0);
  taskHighPtDeDx->SetEtaCut(0.8);
  taskHighPtDeDx->SetVtxCut(10.0);
  taskHighPtDeDx->SetTrigger(kTriggerInt);
  taskHighPtDeDx->SetPileUpRej(ispileuprej);
  //Set Filtesr
  taskHighPtDeDx->SetTrackFilterGolden(trackFilterGolden);
  taskHighPtDeDx->SetTrackFilterTPC(trackFilterTPC);
  taskHighPtDeDx->SetStoreMcIn(AnalysisMC);     // def: kFALSE

  mgr->AddTask(taskHighPtDeDx);

  // Create ONLY the output containers for the data produced by the
  // task.  Get and connect other common input/output containers via
  // the manager as below
  //=======================================================================

  AliAnalysisDataContainer *cout_histdedx;

  cout_histdedx=0;
  cout_histdedx = mgr->CreateContainer("outputdedx", TList::Class(), AliAnalysisManager::kOutputContainer, "QAHighPtDeDx.root");
  mgr->ConnectInput (taskHighPtDeDx, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskHighPtDeDx, 1, cout_histdedx);

  // Return task pointer at the end
  return taskHighPtDeDx;

}
<|endoftext|>


<commit_before>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef ShaderNode_INCLUDE_ONCE
#define ShaderNode_INCLUDE_ONCE

#include <vlGraphics/Shader.hpp>
#include <vlCore/vlnamespace.hpp>
#include <vector>
#include <map>

namespace vl
{
  /**
   * The ShaderNode class is used to conveniently manage complex hierarchies of Shader[s].
   */
  class ShaderNode: public Object
  {
  private:
    class EnableInfo
    {
    public:
      EnableInfo(EEnable en=EN_UnknownEnable, bool on=false, EInheritance inheritance=IN_Propagate): mEnable(en), mOn(on), mInheritance(inheritance) {}
      EEnable mEnable;
      bool mOn;
      EInheritance mInheritance;
    };
    class RenderStateInfo
    {
    public:
      RenderStateInfo(RenderState* rs=NULL, EInheritance inheritance=IN_Propagate): mRenderState(rs), mInheritance(inheritance) {}
      ref<RenderState> mRenderState;
      EInheritance mInheritance;
    };
    class UniformInfo
    {
    public:
      UniformInfo(Uniform* unif=NULL, EInheritance inheritance=IN_Propagate): mUniform(unif), mInheritance(inheritance) {}
      ref<Uniform> mUniform;
      EInheritance mInheritance;
    };

  public:
    virtual const char* className() { return "vl::ShaderNode"; }

    ShaderNode(): mParent(NULL) {}

    // tree-related functions

    void addChild(ShaderNode* node)
    {
      VL_CHECK(node->parent() == NULL);
      mNodes.push_back(node);
      node->mParent = this;
    }

    void eraseChild(ShaderNode* node)
    {
      VL_CHECK(node->parent() == this);
      for(unsigned i=0; i<childrenCount(); ++i)
        if (child(i) == node)
        {
          mNodes.erase(mNodes.begin()+i);
          node->mParent = NULL;
          return;
        }
    }

    void eraseChild(unsigned index)
    {
      VL_CHECK(index<childrenCount())
      mNodes[index]->mParent = NULL;
      mNodes.erase(mNodes.begin()+index);
    }

    void eraseChildren(unsigned start, unsigned count)
    {
      VL_CHECK(start < childrenCount())
      VL_CHECK(start+count-1 < childrenCount())
      for(unsigned i=start; i<start+count; ++i)
        mNodes[i]->mParent = NULL;
      mNodes.erase(mNodes.begin()+start, mNodes.begin()+start+count);
    }

    int findChild(const ShaderNode* node) const
    {
      for(unsigned i=0; i<childrenCount(); ++i)
        if(child(i) == node)
          return i;
      return -1;
    }

    size_t childrenCount() const { return mNodes.size(); }

    ShaderNode* child(unsigned i) { return mNodes[i].get(); }
    const ShaderNode* child(unsigned i) const { return mNodes[i].get(); }

    ShaderNode* parent() { return mParent; }
    const ShaderNode* parent() const { return mParent; }

    // shader-related functions

    void inherit(ShaderNode* parent)
    {
      // init
      mRenderStates_Final.clear();
      mEnables_Final.clear();
      mUniforms_Final.clear();

      // propagate
      for(std::map< ERenderState, RenderStateInfo >::const_iterator rs_it = mRenderStates.begin(); rs_it != mRenderStates.end(); ++rs_it)
          mRenderStates_Final[rs_it->first] = rs_it->second;

      for(std::map< EEnable, EnableInfo>::const_iterator en_it = mEnables.begin(); en_it != mEnables.end(); ++en_it)
        if(en_it->second.mOn)
          mEnables_Final[en_it->first] = en_it->second;

      for(std::map< std::string, UniformInfo >::const_iterator unif_it = mUniforms.begin(); unif_it != mUniforms.end(); ++unif_it)
          mUniforms_Final[unif_it->first] = unif_it->second;

      // iterate parent final values

      if (parent)
      {

        /* ALGORITHM:
         *
         * 1 - iterate over parent's values
         * 2 - if it doesn't propagate -> end
         * 3 - find current values
         *   3a - if there is not -> insert parent's -> end
         *   3b - if there is
         *      3ba - if parent's do not overrides -> end
         *      3bb - if child's do not overridden -> end
         *      3bc - else -> use parent's
         */

        // render states
        for(std::map< ERenderState, RenderStateInfo >::const_iterator par_it = parent->mRenderStates_Final.begin(); par_it != parent->mRenderStates_Final.end(); ++par_it)
        {
          if (!(par_it->second.mInheritance & IN_Propagate))
            continue;
          std::map< ERenderState, RenderStateInfo >::const_iterator cur_it = mRenderStates_Final.find(par_it->first);
          if (cur_it == mRenderStates_Final.end())
            mRenderStates_Final[par_it->first] = par_it->second;
          else
          if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky))
            continue;
          else
            mRenderStates_Final[par_it->first] = par_it->second;
        }

        // enables
        for(std::map< EEnable, EnableInfo >::const_iterator par_it = parent->mEnables_Final.begin(); par_it != parent->mEnables_Final.end(); ++par_it)
        {
          if (!par_it->second.mOn)
            continue;
          if (!(par_it->second.mInheritance & IN_Propagate))
            continue;
          std::map< EEnable, EnableInfo >::const_iterator cur_it = mEnables_Final.find(par_it->first);
          if (cur_it == mEnables_Final.end())
            mEnables_Final[par_it->first] = par_it->second;
          else
          if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky))
            continue;
          else
            mEnables_Final[par_it->first] = par_it->second;
        }

        // uniforms
        for(std::map< std::string, UniformInfo >::const_iterator par_it = parent->mUniforms_Final.begin(); par_it != parent->mUniforms_Final.end(); ++par_it)
        {
          if (!(par_it->second.mInheritance & IN_Propagate))
            continue;
          std::map< std::string, UniformInfo >::const_iterator cur_it = mUniforms_Final.find(par_it->first);
          if (cur_it == mUniforms_Final.end())
            mUniforms_Final[par_it->first] = par_it->second;
          else
          if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky))
            continue;
          else
            mUniforms_Final[par_it->first] = par_it->second;
        }
      }

      // apply it to the Shader

      if (mShader)
      {
        mShader->eraseAllRenderStates();
        mShader->eraseAllUniforms();
        mShader->disableAll();

        // we can speed this up even more by removing the duplication check

        for(std::map< ERenderState, RenderStateInfo >::const_iterator rs_it = mRenderStates_Final.begin(); rs_it != mRenderStates_Final.end(); ++rs_it)
          mShader->setRenderState(rs_it->second.mRenderState.get());
        for(std::map< EEnable, EnableInfo >::const_iterator en_it = mEnables_Final.begin(); en_it != mEnables_Final.end(); ++en_it)
          mShader->enable(en_it->second.mEnable);
        for(std::map< std::string, UniformInfo >::const_iterator rs_it = mUniforms_Final.begin(); rs_it != mUniforms_Final.end(); ++rs_it)
          mShader->setUniform(rs_it->second.mUniform.get());
      }
    }

    void setRenderState(RenderState* rs, EInheritance inheritance=IN_Propagate)
    {
      RenderStateInfo info(rs, inheritance);
      mRenderStates[rs->type()] = info;
    }

    void eraseRenderState(RenderState* rs)
    {
      mRenderStates.erase(rs->type());
    }

    void setEnable(EEnable en, bool on, EInheritance inheritance=IN_Propagate)
    {
      EnableInfo info(en,on,inheritance);
      mEnables[en] = info;
    }

    void eraseEnable(EEnable en)
    {
      mEnables.erase(en);
    }

    void setUniform(Uniform* unif, EInheritance inheritance=IN_Propagate)
    {
      UniformInfo info(unif, inheritance);
      mUniforms[unif->name()] = info;
    }

    void eraseUniform(Uniform* unif)
    {
      mUniforms.erase(unif->name());
    }

    void setShader(Shader* shader) { mShader = shader; }
    const Shader* shader() const { return mShader.get(); }
    Shader* shader() { return mShader.get(); }

    void updateHierarchy()
    {
      inherit(parent());
      for(unsigned i=0;i <childrenCount(); ++i)
        child(i)->updateHierarchy();
    }

  protected:
    std::vector< ref< ShaderNode > > mNodes;
    ShaderNode* mParent;

    std::map< ERenderState, RenderStateInfo > mRenderStates;
    std::map< EEnable, EnableInfo> mEnables;
    std::map< std::string, UniformInfo > mUniforms;

    std::map< ERenderState, RenderStateInfo > mRenderStates_Final;
    std::map< EEnable, EnableInfo> mEnables_Final;
    std::map< std::string, UniformInfo > mUniforms_Final;

    ref<Shader> mShader;
  };
}

#endif
<commit_msg>ShaderNode getter functions.<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef ShaderNode_INCLUDE_ONCE
#define ShaderNode_INCLUDE_ONCE

#include <vlGraphics/Shader.hpp>
#include <vlCore/vlnamespace.hpp>
#include <vector>
#include <map>

namespace vl
{
  /**
   * The ShaderNode class is used to conveniently manage complex hierarchies of Shader[s].
   */
  class ShaderNode: public Object
  {
  public:
    // --- --- ---
    struct EnableInfo
    {
      EnableInfo(EEnable en=EN_UnknownEnable, bool on=false, EInheritance inheritance=IN_Propagate): mEnable(en), mOn(on), mInheritance(inheritance) {}

      EEnable mEnable;
      bool mOn;
      EInheritance mInheritance;
    };
    // --- --- ---
    struct RenderStateInfo
    {
      RenderStateInfo(RenderState* rs=NULL, EInheritance inheritance=IN_Propagate): mRenderState(rs), mInheritance(inheritance) {}

      ref<RenderState> mRenderState;
      EInheritance mInheritance;
    };
    // --- --- ---
    struct UniformInfo
    {
      UniformInfo(Uniform* unif=NULL, EInheritance inheritance=IN_Propagate): mUniform(unif), mInheritance(inheritance) {}

      ref<Uniform> mUniform;
      EInheritance mInheritance;
    };
    // --- --- ---
    typedef std::map< ERenderState, RenderStateInfo > RenderStatesMap;
    typedef std::map< EEnable, EnableInfo > EnablesMap;
    typedef std::map< std::string, UniformInfo > UniformsMap;

  public:
    virtual const char* className() { return "vl::ShaderNode"; }

    ShaderNode(): mParent(NULL) {}

    // shader-related functions

    void setShader(Shader* shader) { mShader = shader; }

    const Shader* shader() const { return mShader.get(); }

    Shader* shader() { return mShader.get(); }

    // tree-related functions

    void addChild(ShaderNode* node)
    {
      VL_CHECK(node->parent() == NULL);
      mNodes.push_back(node);
      node->mParent = this;
    }

    void eraseChild(ShaderNode* node)
    {
      VL_CHECK(node->parent() == this);
      for(unsigned i=0; i<childrenCount(); ++i)
        if (child(i) == node)
        {
          mNodes.erase(mNodes.begin()+i);
          node->mParent = NULL;
          return;
        }
    }

    void eraseChild(unsigned index)
    {
      VL_CHECK(index<childrenCount())
      mNodes[index]->mParent = NULL;
      mNodes.erase(mNodes.begin()+index);
    }

    void eraseChildren(unsigned start, unsigned count)
    {
      VL_CHECK(start < childrenCount())
      VL_CHECK(start+count-1 < childrenCount())
      for(unsigned i=start; i<start+count; ++i)
        mNodes[i]->mParent = NULL;
      mNodes.erase(mNodes.begin()+start, mNodes.begin()+start+count);
    }

    int findChild(const ShaderNode* node) const
    {
      for(unsigned i=0; i<childrenCount(); ++i)
        if(child(i) == node)
          return i;
      return -1;
    }

    size_t childrenCount() const { return mNodes.size(); }

    ShaderNode* child(unsigned i) { return mNodes[i].get(); }

    const ShaderNode* child(unsigned i) const { return mNodes[i].get(); }

    ShaderNode* parent() { return mParent; }

    const ShaderNode* parent() const { return mParent; }

    // inheritance-related functions

    void updateHierarchy()
    {
      inherit(parent());
      for(unsigned i=0;i <childrenCount(); ++i)
        child(i)->updateHierarchy();
    }

    void inherit(ShaderNode* parent)
    {
      // init
      mRenderStates_Final.clear();
      mEnables_Final.clear();
      mUniforms_Final.clear();

      // propagate
      for(RenderStatesMap::const_iterator rs_it = mRenderStates.begin(); rs_it != mRenderStates.end(); ++rs_it)
          mRenderStates_Final[rs_it->first] = rs_it->second;

      for(std::map< EEnable, EnableInfo>::const_iterator en_it = mEnables.begin(); en_it != mEnables.end(); ++en_it)
        if(en_it->second.mOn)
          mEnables_Final[en_it->first] = en_it->second;

      for(UniformsMap::const_iterator unif_it = mUniforms.begin(); unif_it != mUniforms.end(); ++unif_it)
          mUniforms_Final[unif_it->first] = unif_it->second;

      // iterate parent final values

      if (parent)
      {

        /* ALGORITHM:
         *
         * 1 - iterate over parent's values
         * 2 - if it doesn't propagate -> end
         * 3 - find current values
         *   3a - if there is not -> insert parent's -> end
         *   3b - if there is
         *      3ba - if parent's do not overrides -> end
         *      3bb - if child's do not overridden -> end
         *      3bc - else -> use parent's
         */

        // render states
        for(RenderStatesMap::const_iterator par_it = parent->mRenderStates_Final.begin(); par_it != parent->mRenderStates_Final.end(); ++par_it)
        {
          if (!(par_it->second.mInheritance & IN_Propagate))
            continue;
          RenderStatesMap::const_iterator cur_it = mRenderStates_Final.find(par_it->first);
          if (cur_it == mRenderStates_Final.end())
            mRenderStates_Final[par_it->first] = par_it->second;
          else
          if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky))
            continue;
          else
            mRenderStates_Final[par_it->first] = par_it->second;
        }

        // enables
        for(EnablesMap::const_iterator par_it = parent->mEnables_Final.begin(); par_it != parent->mEnables_Final.end(); ++par_it)
        {
          if (!par_it->second.mOn)
            continue;
          if (!(par_it->second.mInheritance & IN_Propagate))
            continue;
          EnablesMap::const_iterator cur_it = mEnables_Final.find(par_it->first);
          if (cur_it == mEnables_Final.end())
            mEnables_Final[par_it->first] = par_it->second;
          else
          if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky))
            continue;
          else
            mEnables_Final[par_it->first] = par_it->second;
        }

        // uniforms
        for(UniformsMap::const_iterator par_it = parent->mUniforms_Final.begin(); par_it != parent->mUniforms_Final.end(); ++par_it)
        {
          if (!(par_it->second.mInheritance & IN_Propagate))
            continue;
          UniformsMap::const_iterator cur_it = mUniforms_Final.find(par_it->first);
          if (cur_it == mUniforms_Final.end())
            mUniforms_Final[par_it->first] = par_it->second;
          else
          if (!(par_it->second.mInheritance & 0x02/*IN_Overrides*/) || (cur_it->second.mInheritance & IN_Sticky))
            continue;
          else
            mUniforms_Final[par_it->first] = par_it->second;
        }
      }

      // apply it to the Shader

      if (mShader)
      {
        mShader->eraseAllRenderStates();
        mShader->eraseAllUniforms();
        mShader->disableAll();

        // we can speed this up even more by removing the duplication check

        for(RenderStatesMap::const_iterator rs_it = mRenderStates_Final.begin(); rs_it != mRenderStates_Final.end(); ++rs_it)
          mShader->setRenderState(rs_it->second.mRenderState.get());
        for(EnablesMap::const_iterator en_it = mEnables_Final.begin(); en_it != mEnables_Final.end(); ++en_it)
          mShader->enable(en_it->second.mEnable);
        for(UniformsMap::const_iterator rs_it = mUniforms_Final.begin(); rs_it != mUniforms_Final.end(); ++rs_it)
          mShader->setUniform(rs_it->second.mUniform.get());
      }
    }

    // states setters

    void setRenderState(RenderState* rs, EInheritance inheritance=IN_Propagate)
    {
      RenderStateInfo info(rs, inheritance);
      mRenderStates[rs->type()] = info;
    }

    void eraseRenderState(RenderState* rs)
    {
      mRenderStates.erase(rs->type());
    }

    void setEnable(EEnable en, bool on, EInheritance inheritance=IN_Propagate)
    {
      EnableInfo info(en,on,inheritance);
      mEnables[en] = info;
    }

    void eraseEnable(EEnable en)
    {
      mEnables.erase(en);
    }

    void setUniform(Uniform* unif, EInheritance inheritance=IN_Propagate)
    {
      UniformInfo info(unif, inheritance);
      mUniforms[unif->name()] = info;
    }

    void eraseUniform(Uniform* unif)
    {
      mUniforms.erase(unif->name());
    }

    // states getters

    const RenderStatesMap& renderStates() const { return mRenderStates; }

    RenderStatesMap& renderStates() { return mRenderStates; }

    const EnablesMap& enables() const { return mEnables; }

    EnablesMap& enables() { return mEnables; }

    const UniformsMap& uniforms() const { return mUniforms; }

    UniformsMap& uniforms() { return mUniforms; }

  protected:
    std::vector< ref< ShaderNode > > mNodes;
    ShaderNode* mParent;

    RenderStatesMap mRenderStates;
    EnablesMap mEnables;
    UniformsMap mUniforms;

    RenderStatesMap mRenderStates_Final;
    EnablesMap mEnables_Final;
    UniformsMap mUniforms_Final;

    ref<Shader> mShader;
  };
}

#endif
<|endoftext|>