<commit_before>#ifndef ANN_ENGINE
#define ANN_ENGINE

#include "systemMacro.h"

//Graphic rendering system for the rift
#include "OgreOculusRender.hpp"

//C++ STD & STL
#include <vector>
#include <sstream>
#include <cassert>

//Ogre 3D
#include <Ogre.h>
#include <OIS.h>

//Bullet
#include <btBulletCollisionCommon.h>
#include <BulletCollision/CollisionDispatch/btGhostObject.h>
#include <btBulletDynamicsCommon.h>

//btOgre
#include "BtOgrePG.h"
#include "BtOgreGP.h"
#include "BtOgreExtras.h"

//Annwvyn
#include "AnnPlayer.hpp"
#include "AnnEventManager.hpp"
#include "AnnGameObject.hpp"
#include "AnnTriggerObject.hpp"
#include "AnnTypes.h"
#include "AnnTools.h"
#include "AnnAudioEngine.hpp"

#ifdef __gnu_linux__
#include <unistd.h> //for some unix functions
#endif

namespace Annwvyn
{
    class DLL AnnEngine
    {
        public:
            ///Class constructor. take the name of the window
            AnnEngine(const char title[] = "Annwvyn Game Engine");

            ///Class destructor. Do clean up stuff.
            ~AnnEngine();

			///Return pointer to the engine itself
			AnnEngine* getAddress() {return this;}

			///Get the event manager
			AnnEventManager* getEventManager();

			///Get the player
			AnnPlayer* getPlayer();

            ///Give a zipped archive resource location to the Ogre Resource Group Manager
            void loadZip(const char path[], const char ressourceGroupName[] = "ANNWVYN_DEFAULT");
			///Give a directory resouce location to the Ogre Resource Group Manager
            void loadDir(const char path[], const char resourceGroupNmame[] = "ANNWVYN_DEFAULT");

			///Load a standard Ogre resource.cfg file
            void loadResFile(const char path[]); //resource

            ///Init All ressources groups
            void initResources(); //resource

			///Deprecated: spelling problem here. I'm French
			void initRessources(){initResources();} //resource

			///Init a resource group
			void initAResourceGroup(std::string resourceGroup); //resource

            ///Init OgreOculus stuff
            void oculusInit(bool fullscreen = true); //oculus

			///Init the physics model
            void initPlayerPhysics(); //physics on player

			///Update player location/orientation from the bullet body
            void updatePlayerFromPhysics(); //physics on player

            ///Translate the player (DONT DETECT COLLISIONS HERE !!!)
            void translatePhysicBody(Ogre::Vector3 translation); //physics on player

            ///Set player linear speed from a 3D vector
            void setPhysicBodyLinearSpeed(Ogre::Vector3 V); //physics on player

            ///Create a game object form the name of an entity.
            AnnGameObject* createGameObject(const char entityName[], AnnGameObject* object = new AnnGameObject); //object factory

            bool destroyGameObject(AnnGameObject* object); //object factory

            ///Set the ambiant light
            void setAmbiantLight(Ogre::ColourValue v); //scene parameter

            ///Add a light to the scene. return a pointer to the new light
            AnnLightObject* addLight(); //object factory

            ///Calculate one frame of the game
            void renderOneFrame(); //graphics

            ///Display bullet debuging drawing
            void setDebugPhysicState(bool state); //engine debug

            ///Run objects physics
            void runPhysics(); //physics engine call

            ///Return true if the game want to terminate the program
            bool requestStop(); //engine

            ///Log something to the console. If flag = true (by default), will print "Annwvyn - " in front of the message
            static void log(std::string message, bool flag = true); //engine

            ///Update camera position/orientation from rift and virtual body
            void updateCamera(); //graphics

			///Apply yaw transform with mouse relative X displacement
			void applyMouseYaw(); //player engine call

			///Get camera position and ask OOR to do the render
			void doRender(); //graphics engine call

			///Sync all audo objects
			void updateAudioSystemState(); //audio

			///Run the base gameplay loop content (WASD + jump + mouse for yaw)
			void runBasicGameplay(); //gameplay on user

            ///Refresh all for you
            void refresh(); //engine main loop

            ///Return a vector depending on WASD keys pressed
            bool processWASD(Ogre::Vector3* translate); //event on user

            ///Caputre event form keyboard and mouse
            void captureEvents(); //events

            ///Update program time. retur the delay between the last call of this method
            float getTime();//engine

            ///Get elapsed time from engine startup
            float getTimeFromStartUp();//engine

            ///Step Objects animation
            void playObjectsAnnimation(); //object engine call

            ///Set the ground object
            void setGround(AnnGameObject* Ground); //scene

            ///Return the Annwvyn OpenAL simplified audio engine
            AnnAudioEngine* getAudioEngine(); //audio

            ///LowLevel OIS Mouse
            OIS::Mouse* getOISMouse(); //event

            ///LowLevel OIS Keyboard
            OIS::Keyboard* getOISKeyboard(); //event

            ///LowLevel OIS Joystick
            OIS::JoyStick* getOISJoyStick(); //event

            ///Is key 'key' pressed ? (see OIS headers for KeyCode, generaly 'OIS::KC_X' where X is the key you want.
            bool isKeyDown(OIS::KeyCode key); //event

            ///Return true if you touch the ground
            bool collisionWithGround(); //physics

            ///Process collision test form bullet manifold and objects collision mask
            void processCollisionTesting(); //physics on object engine call

            ///Get the dynamicsWorld
            btDiscreteDynamicsWorld* getDynamicsWorld(); //physics

            ///Create a trigger object
            AnnTriggerObject* createTriggerObject(AnnTriggerObject* trigger = new AnnTriggerObject); //object factory

            ///Process contact test with triggers
            void processTriggersContacts(); //gameplay engine call

            ///Get ogre scene manager
            Ogre::SceneManager* getSceneManager(); //scene or graphics

            ///Set the ogre material for the skydime with params
            void setSkyDomeMaterial(bool activate, const char materialName[], float curvature = 2.0f, float tiling = 1.0f); //scene

            ///Get the AnnObject the player is looking at
            Annwvyn::AnnGameObject* playerLookingAt(); //physics

            ///Get the AnnGameObject form the given Ogre node
            Annwvyn::AnnGameObject* getFromNode(Ogre::SceneNode* node); //engine

            ///DEPRECATED Get bodyParams
            Annwvyn::bodyParams* getBodyParams();

            ///Get ogre camera scene node
            Ogre::SceneNode* getCamera(); //...

            ///Get offset between viewport and distortion centre
            float getCentreOffset(); //...

			///Reference orientation. Usefull if you are inside a vehicule for example
            void setReferenceQuaternion(Ogre::Quaternion q); //engine...

			///Retrive the said reference quaternion
            Ogre::Quaternion getReferenceQuaternion(); //engine

			///Attach a 3D mesh to the camera to act as player's body.
            void attachVisualBody(const std::string entityName,
                    float z_offset = -0.0644f,
                    bool flip = false,
                    bool animated = false,
                    Ogre::Vector3 scale = Ogre::Vector3::UNIT_SCALE); //I seriously have something to do about that...

			///Reset the Rift Orientation
            void resetOculusOrientation();///Gameplay... but engine related function.

			///Get a pose information object
			OgrePose getPoseFromOOR()
			{
				if(oor)
					return oor->returnPose;
				OgrePose p; return p;
			}

			///Set the distance of the near clipping  plane
			void setNearClippingDistance(Ogre::Real setNearClippingDistance); //graphics

        private:

			///Set up graphics
            void setUpOgre(const char title[]);

			///Set up physics
            void setUpBullet();

			///Set up inputs
            void setUpOIS();

			///Set up timing
            void setUpTime();

			///Set up 3D audio system
            void setUpAudio();

			///Set up GUI/HUD rendering
            void setUpGUI();

			///Create the bullet shape of the player's body
            void createVirtualBodyShape();

			///Create a physical object from the calculated shape
            void createPlayerPhysicalVirtualBody();

			///Add the players body to the Physics simulation
            void addPlayerPhysicalBodyToDynamicsWorld();

			///Returns internal timing
            float updateTime();

            ///Unable to continue, we have to cleanly cut the program before creating an error
            void emergency(void);

        private:

			AnnPlayer* player;
			AnnEventManager* eventManager;

            //Ogre::Root* m_Root;
            Ogre::RenderWindow* m_Window;
            Ogre::SceneManager* m_SceneManager;
            Ogre::SceneNode* m_Camera;
            Ogre::SceneNode* VisualBodyAnchor;
			Ogre::Quaternion refVisualBody;
            Ogre::Entity* VisualBody;
            Ogre::AnimationState* VisualBodyAnimation;
			float visualBody_Zoffset;
            bool readyForLoadingRessources;

            Ogre::Entity* m_ent; //only used for creating nodes into the smgr

            //Oculus oculus;
            OgreOculusRender* oor;

            ///Dynamic container for games objects
            AnnGameObjectVect objects;
            AnnTriggerObjectVect triggers;

            ///Events processing :
            OIS::InputManager *m_InputManager;
            OIS::Keyboard *m_Keyboard;
            OIS::Mouse *m_Mouse;
            OIS::JoyStick *m_Joystick;
            OIS::ParamList pl;

            size_t windowHnd;
            std::ostringstream windowHndStr;

            bool activateWASD;
            bool activateJump;
            float jumpForce;

            ///Time
            unsigned long last,now; //Milisec

            ///Elapsed time
            float deltaT; //Sec

            //bullet
            btBroadphaseInterface* m_Broadphase;
            btDefaultCollisionConfiguration* m_CollisionConfiguration;
            btCollisionDispatcher* m_Dispatcher;
            btSequentialImpulseConstraintSolver* m_Solver;
            btGhostPairCallback* m_ghostPairCallback;

            ///Bullet Dynamics World
            btDiscreteDynamicsWorld* m_DynamicsWorld;

            bool debugPhysics;
            BtOgre::DebugDrawer* m_debugDrawer;

            btQuaternion fixedBodyOrient;

            Ogre::Quaternion QuatReference;

            AnnGameObject* m_Ground;

            ///Audio engine
            AnnAudioEngine* AudioEngine;

    };
}
#endif ///ANN_ENGINE
<commit_msg>continue messing up with comments<commit_after>#ifndef ANN_ENGINE
#define ANN_ENGINE

#include "systemMacro.h"

//Graphic rendering system for the rift
#include "OgreOculusRender.hpp"

//C++ STD & STL
#include <vector>
#include <sstream>
#include <cassert>

//Ogre 3D
#include <Ogre.h>
#include <OIS.h>

//Bullet
#include <btBulletCollisionCommon.h>
#include <BulletCollision/CollisionDispatch/btGhostObject.h>
#include <btBulletDynamicsCommon.h>

//btOgre
#include "BtOgrePG.h"
#include "BtOgreGP.h"
#include "BtOgreExtras.h"

//Annwvyn
#include "AnnPlayer.hpp"
#include "AnnEventManager.hpp"
#include "AnnGameObject.hpp"
#include "AnnTriggerObject.hpp"
#include "AnnTypes.h"
#include "AnnTools.h"
#include "AnnAudioEngine.hpp"

#ifdef __gnu_linux__
#include <unistd.h> //for some unix functions
#endif

namespace Annwvyn
{
    class DLL AnnEngine
    {
        public:
            ///Class constructor. take the name of the window
            AnnEngine(const char title[] = "Annwvyn Game Engine");

            ///Class destructor. Do clean up stuff.
            ~AnnEngine();

			///Return pointer to the engine itself
			AnnEngine* getAddress() {return this;}

			///Get the event manager
			AnnEventManager* getEventManager();

			///Get the player
			AnnPlayer* getPlayer();

            ///Give a zipped archive resource location to the Ogre Resource Group Manager
            void loadZip(const char path[], const char ressourceGroupName[] = "ANNWVYN_DEFAULT");

			///Give a directory resouce location to the Ogre Resource Group Manager
            void loadDir(const char path[], const char resourceGroupNmame[] = "ANNWVYN_DEFAULT");

			///Load a standard Ogre resource.cfg file
            void loadResFile(const char path[]); //resource

            ///Init All ressources groups
            void initResources(); //resource

			///Deprecated: spelling problem here. I'm French
			void initRessources(){initResources();} //resource

			///Init a resource group
			void initAResourceGroup(std::string resourceGroup); //resource

            ///Init OgreOculus stuff
            void oculusInit(bool fullscreen = true); //oculus

			///Init the physics model
            void initPlayerPhysics(); //physics on player

			///Update player location/orientation from the bullet body
            void updatePlayerFromPhysics(); //physics on player

            ///Translate the player (DONT DETECT COLLISIONS HERE !!!)
            void translatePhysicBody(Ogre::Vector3 translation); //physics on player

            ///Set player linear speed from a 3D vector
            void setPhysicBodyLinearSpeed(Ogre::Vector3 V); //physics on player

            ///Create a game object form the name of an entity.
            AnnGameObject* createGameObject(const char entityName[], AnnGameObject* object = new AnnGameObject); //object factory

            bool destroyGameObject(AnnGameObject* object); //object factory

            ///Set the ambiant light
            void setAmbiantLight(Ogre::ColourValue v); //scene parameter

            ///Add a light to the scene. return a pointer to the new light
            AnnLightObject* addLight(); //object factory

            ///Calculate one frame of the game
            void renderOneFrame(); //graphics

            ///Display bullet debuging drawing
            void setDebugPhysicState(bool state); //engine debug

            ///Run objects physics
            void runPhysics(); //physics engine call

            ///Return true if the game want to terminate the program
            bool requestStop(); //engine

            ///Log something to the console. If flag = true (by default), will print "Annwvyn - " in front of the message
            static void log(std::string message, bool flag = true); //engine

            ///Update camera position/orientation from rift and virtual body
            void updateCamera(); //graphics

			///Apply yaw transform with mouse relative X displacement
			void applyMouseYaw(); //player engine call

			///Get camera position and ask OOR to do the render
			void doRender(); //graphics engine call

			///Sync all audo objects
			void updateAudioSystemState(); //audio

			///Run the base gameplay loop content (WASD + jump + mouse for yaw)
			void runBasicGameplay(); //gameplay on user

            ///Refresh all for you
            void refresh(); //engine main loop

            ///Return a vector depending on WASD keys pressed
            bool processWASD(Ogre::Vector3* translate); //event on user

            ///Caputre event form keyboard and mouse
            void captureEvents(); //events

            ///Update program time. retur the delay between the last call of this method
            float getTime();//engine

            ///Get elapsed time from engine startup
            float getTimeFromStartUp();//engine

            ///Step Objects animation
            void playObjectsAnnimation(); //object engine call

            ///Set the ground object
            void setGround(AnnGameObject* Ground); //scene

            ///Return the Annwvyn OpenAL simplified audio engine
            AnnAudioEngine* getAudioEngine(); //audio

            ///LowLevel OIS Mouse
            OIS::Mouse* getOISMouse(); //event

            ///LowLevel OIS Keyboard
            OIS::Keyboard* getOISKeyboard(); //event

            ///LowLevel OIS Joystick
            OIS::JoyStick* getOISJoyStick(); //event

            ///Is key 'key' pressed ? (see OIS headers for KeyCode, generaly 'OIS::KC_X' where X is the key you want.
            bool isKeyDown(OIS::KeyCode key); //event

            ///Return true if you touch the ground
            bool collisionWithGround(); //physics

            ///Process collision test form bullet manifold and objects collision mask
            void processCollisionTesting(); //physics on object engine call

            ///Get the dynamicsWorld
            btDiscreteDynamicsWorld* getDynamicsWorld(); //physics

            ///Create a trigger object
            AnnTriggerObject* createTriggerObject(AnnTriggerObject* trigger = new AnnTriggerObject); //object factory

            ///Process contact test with triggers
            void processTriggersContacts(); //gameplay engine call

            ///Get ogre scene manager
            Ogre::SceneManager* getSceneManager(); //scene or graphics

            ///Set the ogre material for the skydime with params
            void setSkyDomeMaterial(bool activate, const char materialName[], float curvature = 2.0f, float tiling = 1.0f); //scene

            ///Get the AnnObject the player is looking at
            Annwvyn::AnnGameObject* playerLookingAt(); //physics

            ///Get the AnnGameObject form the given Ogre node
            Annwvyn::AnnGameObject* getFromNode(Ogre::SceneNode* node); //engine

            ///DEPRECATED Get bodyParams
            Annwvyn::bodyParams* getBodyParams();

            ///Get ogre camera scene node
            Ogre::SceneNode* getCamera(); //...

            ///Get offset between viewport and distortion centre
            float getCentreOffset(); //...

			///Reference orientation. Usefull if you are inside a vehicule for example
            void setReferenceQuaternion(Ogre::Quaternion q); //engine...

			///Retrive the said reference quaternion
            Ogre::Quaternion getReferenceQuaternion(); //engine

			///Attach a 3D mesh to the camera to act as player's body.
            void attachVisualBody(const std::string entityName,
                    float z_offset = -0.0644f,
                    bool flip = false,
                    bool animated = false,
                    Ogre::Vector3 scale = Ogre::Vector3::UNIT_SCALE); //I seriously have something to do about that...

			///Reset the Rift Orientation
            void resetOculusOrientation();///Gameplay... but engine related function.

			///Get a pose information object
			OgrePose getPoseFromOOR()
			{
				if(oor)
					return oor->returnPose;
				OgrePose p; return p;
			}

			///Set the distance of the near clipping  plane
			void setNearClippingDistance(Ogre::Real setNearClippingDistance); //graphics

        private:

			///Set up graphics
            void setUpOgre(const char title[]);

			///Set up physics
            void setUpBullet();

			///Set up inputs
            void setUpOIS();

			///Set up timing
            void setUpTime();

			///Set up 3D audio system
            void setUpAudio();

			///Set up GUI/HUD rendering
            void setUpGUI();

			///Create the bullet shape of the player's body
            void createVirtualBodyShape();

			///Create a physical object from the calculated shape
            void createPlayerPhysicalVirtualBody();

			///Add the players body to the Physics simulation
            void addPlayerPhysicalBodyToDynamicsWorld();

			///Returns internal timing
            float updateTime();

            ///Unable to continue, we have to cleanly cut the program before creating an error
            void emergency(void);

        private:

			//Audio engine
            AnnAudioEngine* AudioEngine;
			//Player
			AnnPlayer* player;
			//Event manager
			AnnEventManager* eventManager;

            //Ogre::Root* m_Root;
            Ogre::RenderWindow* m_Window;
            Ogre::SceneManager* m_SceneManager;
            Ogre::SceneNode* m_Camera;
            Ogre::SceneNode* VisualBodyAnchor;
			Ogre::Quaternion refVisualBody;
            Ogre::Entity* VisualBody;
            Ogre::AnimationState* VisualBodyAnimation;
			float visualBody_Zoffset;
            bool readyForLoadingRessources;

            Ogre::Entity* m_ent; //only used for creating nodes into the smgr

            //Oculus oculus;
            OgreOculusRender* oor;

            ///Dynamic container for games objects
            AnnGameObjectVect objects;
            AnnTriggerObjectVect triggers;

            //Events processing :
            OIS::InputManager *m_InputManager;
            OIS::Keyboard *m_Keyboard;
            OIS::Mouse *m_Mouse;
            OIS::JoyStick *m_Joystick;
            OIS::ParamList pl;

            size_t windowHnd;
            std::ostringstream windowHndStr;

            bool activateWASD;
            bool activateJump;
            float jumpForce;

            //Time
            unsigned long last,now; //Milisec

            //Elapsed time
            float deltaT; //Sec

            //bullet
            btBroadphaseInterface* m_Broadphase;
            btDefaultCollisionConfiguration* m_CollisionConfiguration;
            btCollisionDispatcher* m_Dispatcher;
            btSequentialImpulseConstraintSolver* m_Solver;
            btGhostPairCallback* m_ghostPairCallback;

            //Bullet Dynamics World
            btDiscreteDynamicsWorld* m_DynamicsWorld;

            bool debugPhysics;
            BtOgre::DebugDrawer* m_debugDrawer;

            btQuaternion fixedBodyOrient;

            Ogre::Quaternion QuatReference;

            AnnGameObject* m_Ground;

    };
}
#endif ///ANN_ENGINE
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2021-present ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "mutation_fragment.hh"

enum class mutation_fragment_stream_validation_level {
    partition_region, // fragment kind
    token,
    partition_key,
    clustering_key,
};

/// Low level fragment stream validator.
///
/// Tracks and validates the monotonicity of the passed in fragment kinds,
/// position in partition, token or partition keys. Any subset of these
/// can be used, but what is used have to be consistent across the entire
/// stream.
class mutation_fragment_stream_validator {
    const schema& _schema;
    mutation_fragment::kind _prev_kind;
    position_in_partition _prev_pos;
    dht::decorated_key _prev_partition_key;
public:
    explicit mutation_fragment_stream_validator(const schema& s);

    const ::schema& schema() const { return _schema; }

    /// Validate the monotonicity of the fragment kind.
    ///
    /// Should be used when the full, more heavy-weight position-in-partition
    /// monotonicity validation provided by
    /// `operator()(const mutation_fragment&)` is not desired.
    /// Using both overloads for the same stream is not supported.
    /// Advances the previous fragment kind, but only if the validation passes.
    ///
    /// \returns true if the fragment kind is valid.
    bool operator()(mutation_fragment::kind kind);

    /// Validates the monotonicity of the mutation fragment kind and position.
    ///
    /// Validates the mutation fragment kind monotonicity and
    /// position-in-partition.
    /// A more complete version of `operator()(mutation_fragment::kind)`.
    /// Using both overloads for the same stream is not supported.
    /// Advances the previous fragment kind and position-in-partition, but only
    /// if the validation passes.
    ///
    /// \returns true if the mutation fragment kind is valid.
    bool operator()(mutation_fragment::kind kind, position_in_partition_view pos);

    /// Validates the monotonicity of the mutation fragment.
    ///
    /// Equivalent to calling `operator()(mf.kind(), mf.position())`.
    /// See said overload for more details.
    ///
    /// \returns true if the mutation fragment kind is valid.
    bool operator()(const mutation_fragment& mf);

    /// Validates the monotonicity of the token.
    ///
    /// Does not check fragment level monotonicity.
    /// Advances the previous token, but only if the validation passes.
    /// Cannot be used in parallel with the `dht::decorated_key`
    /// overload.
    ///
    /// \returns true if the token is valid.
    bool operator()(dht::token t);

    /// Validates the monotonicity of the partition.
    ///
    /// Does not check fragment level monotonicity.
    /// Advances the previous partition-key, but only if the validation passes.
    /// Cannot be used in parallel with the `dht::token`
    /// overload.
    ///
    /// \returns true if the partition key is valid.
    bool operator()(const dht::decorated_key& dk);

    /// Reset the state of the validator to the given partition
    ///
    /// Reset the state of the validator as if it has just validated a valid
    /// partition start with the provided key. This can be used t force a reset
    /// to a given partition that is normally invalid and hence wouldn't advance
    /// the internal state. This can be used by users that can correct such
    /// invalid streams and wish to continue validating it.
    void reset(dht::decorated_key dk);

    /// Reset the state of the validator to the given fragment
    ///
    /// Reset the state of the validator as if it has just validated a valid
    /// fragment. This can be used t force a reset to a given fragment that is
    /// normally invalid and hence wouldn't advance the internal state. This
    /// can be used by users that can correct such invalid streams and wish to
    /// continue validating it.
    void reset(const mutation_fragment&);

    /// Validate that the stream was properly closed.
    ///
    /// \returns false if the last partition wasn't closed, i.e. the last
    /// fragment wasn't a `partition_end` fragment.
    bool on_end_of_stream();

    /// The previous valid fragment kind.
    mutation_fragment::kind previous_mutation_fragment_kind() const {
        return _prev_kind;
    }
    /// The previous valid position.
    ///
    /// Not meaningful, when operator()(position_in_partition_view) is not used.
    const position_in_partition& previous_position() const {
        return _prev_pos;
    }
    /// The previous valid partition key.
    ///
    /// Only valid if `operator()(const dht::decorated_key&)` or
    /// `operator()(dht::token)` was used.
    dht::token previous_token() const {
        return _prev_partition_key.token();
    }
    /// The previous valid partition key.
    ///
    /// Only valid if `operator()(const dht::decorated_key&)` was used.
    const dht::decorated_key& previous_partition_key() const {
        return _prev_partition_key;
    }
};

struct invalid_mutation_fragment_stream : public std::runtime_error {
    explicit invalid_mutation_fragment_stream(std::runtime_error e);
};

/// Track position_in_partition transitions and validate monotonicity.
///
/// Will throw `invalid_mutation_fragment_stream` if any violation is found.
/// If the `abort_on_internal_error` configuration option is set, it will
/// abort instead.
/// Implements the FlattenedConsumerFilter concept.
class mutation_fragment_stream_validating_filter {
    mutation_fragment_stream_validator _validator;
    sstring _name;
    mutation_fragment_stream_validation_level _validation_level;

public:
    /// Constructor.
    ///
    /// \arg name is used in log messages to identify the validator, the
    ///     schema identity is added automatically
    /// \arg compare_keys enable validating clustering key monotonicity
    mutation_fragment_stream_validating_filter(sstring_view name, const schema& s, mutation_fragment_stream_validation_level level);

    bool operator()(const dht::decorated_key& dk);
    bool operator()(mutation_fragment::kind kind, position_in_partition_view pos);
    /// Equivalent to `operator()(mf.kind(), mf.position())`
    bool operator()(const mutation_fragment& mv);
    /// Equivalent to `operator()(partition_end{})`
    bool on_end_of_partition();
    void on_end_of_stream();
};
<commit_msg>mutation_fragment_stream_validator: disambiguate schema member definition<commit_after>/*
 * Copyright (C) 2021-present ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "mutation_fragment.hh"

enum class mutation_fragment_stream_validation_level {
    partition_region, // fragment kind
    token,
    partition_key,
    clustering_key,
};

/// Low level fragment stream validator.
///
/// Tracks and validates the monotonicity of the passed in fragment kinds,
/// position in partition, token or partition keys. Any subset of these
/// can be used, but what is used have to be consistent across the entire
/// stream.
class mutation_fragment_stream_validator {
    const ::schema& _schema;
    mutation_fragment::kind _prev_kind;
    position_in_partition _prev_pos;
    dht::decorated_key _prev_partition_key;
public:
    explicit mutation_fragment_stream_validator(const schema& s);

    const ::schema& schema() const { return _schema; }

    /// Validate the monotonicity of the fragment kind.
    ///
    /// Should be used when the full, more heavy-weight position-in-partition
    /// monotonicity validation provided by
    /// `operator()(const mutation_fragment&)` is not desired.
    /// Using both overloads for the same stream is not supported.
    /// Advances the previous fragment kind, but only if the validation passes.
    ///
    /// \returns true if the fragment kind is valid.
    bool operator()(mutation_fragment::kind kind);

    /// Validates the monotonicity of the mutation fragment kind and position.
    ///
    /// Validates the mutation fragment kind monotonicity and
    /// position-in-partition.
    /// A more complete version of `operator()(mutation_fragment::kind)`.
    /// Using both overloads for the same stream is not supported.
    /// Advances the previous fragment kind and position-in-partition, but only
    /// if the validation passes.
    ///
    /// \returns true if the mutation fragment kind is valid.
    bool operator()(mutation_fragment::kind kind, position_in_partition_view pos);

    /// Validates the monotonicity of the mutation fragment.
    ///
    /// Equivalent to calling `operator()(mf.kind(), mf.position())`.
    /// See said overload for more details.
    ///
    /// \returns true if the mutation fragment kind is valid.
    bool operator()(const mutation_fragment& mf);

    /// Validates the monotonicity of the token.
    ///
    /// Does not check fragment level monotonicity.
    /// Advances the previous token, but only if the validation passes.
    /// Cannot be used in parallel with the `dht::decorated_key`
    /// overload.
    ///
    /// \returns true if the token is valid.
    bool operator()(dht::token t);

    /// Validates the monotonicity of the partition.
    ///
    /// Does not check fragment level monotonicity.
    /// Advances the previous partition-key, but only if the validation passes.
    /// Cannot be used in parallel with the `dht::token`
    /// overload.
    ///
    /// \returns true if the partition key is valid.
    bool operator()(const dht::decorated_key& dk);

    /// Reset the state of the validator to the given partition
    ///
    /// Reset the state of the validator as if it has just validated a valid
    /// partition start with the provided key. This can be used t force a reset
    /// to a given partition that is normally invalid and hence wouldn't advance
    /// the internal state. This can be used by users that can correct such
    /// invalid streams and wish to continue validating it.
    void reset(dht::decorated_key dk);

    /// Reset the state of the validator to the given fragment
    ///
    /// Reset the state of the validator as if it has just validated a valid
    /// fragment. This can be used t force a reset to a given fragment that is
    /// normally invalid and hence wouldn't advance the internal state. This
    /// can be used by users that can correct such invalid streams and wish to
    /// continue validating it.
    void reset(const mutation_fragment&);

    /// Validate that the stream was properly closed.
    ///
    /// \returns false if the last partition wasn't closed, i.e. the last
    /// fragment wasn't a `partition_end` fragment.
    bool on_end_of_stream();

    /// The previous valid fragment kind.
    mutation_fragment::kind previous_mutation_fragment_kind() const {
        return _prev_kind;
    }
    /// The previous valid position.
    ///
    /// Not meaningful, when operator()(position_in_partition_view) is not used.
    const position_in_partition& previous_position() const {
        return _prev_pos;
    }
    /// The previous valid partition key.
    ///
    /// Only valid if `operator()(const dht::decorated_key&)` or
    /// `operator()(dht::token)` was used.
    dht::token previous_token() const {
        return _prev_partition_key.token();
    }
    /// The previous valid partition key.
    ///
    /// Only valid if `operator()(const dht::decorated_key&)` was used.
    const dht::decorated_key& previous_partition_key() const {
        return _prev_partition_key;
    }
};

struct invalid_mutation_fragment_stream : public std::runtime_error {
    explicit invalid_mutation_fragment_stream(std::runtime_error e);
};

/// Track position_in_partition transitions and validate monotonicity.
///
/// Will throw `invalid_mutation_fragment_stream` if any violation is found.
/// If the `abort_on_internal_error` configuration option is set, it will
/// abort instead.
/// Implements the FlattenedConsumerFilter concept.
class mutation_fragment_stream_validating_filter {
    mutation_fragment_stream_validator _validator;
    sstring _name;
    mutation_fragment_stream_validation_level _validation_level;

public:
    /// Constructor.
    ///
    /// \arg name is used in log messages to identify the validator, the
    ///     schema identity is added automatically
    /// \arg compare_keys enable validating clustering key monotonicity
    mutation_fragment_stream_validating_filter(sstring_view name, const schema& s, mutation_fragment_stream_validation_level level);

    bool operator()(const dht::decorated_key& dk);
    bool operator()(mutation_fragment::kind kind, position_in_partition_view pos);
    /// Equivalent to `operator()(mf.kind(), mf.position())`
    bool operator()(const mutation_fragment& mv);
    /// Equivalent to `operator()(partition_end{})`
    bool on_end_of_partition();
    void on_end_of_stream();
};
<|endoftext|>


<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

struct Options
{
    // Debug mode
    bool debug = false;
    // Print messages to standard output
    bool print = false;
    // Use subband dedispersion
    bool subbandDedispersion = false;
    // Avoid merging batches of dispersed data into contiguous memory
    bool splitBatchesDedispersion = false;
    // Compact the triggered events in time and DM dimensions
    bool compactResults = false;
    // Threshold for triggering
    float threshold = 0.0f;
    // SNR mode
    SNRMode snrMode;
    // Step size for median of medians (MOMAD mode)
    unsigned int stepSize = 5;
};

struct DeviceOptions
{
    // OpenCL synchronized operations
    bool synchronized = false;
    // OpenCL platform ID
    unsigned int platformID = 0;
    // OpenCL device ID
    unsigned int deviceID = 0;
    // OpenCL device name
    std::string deviceName{};
    // Padding of OpenCL devices
    AstroData::paddingConf padding{};
};

struct DataOptions
{
    // Use LOFAR file as input
    bool dataLOFAR = false;
    // Use SIGPROC file as input
    bool dataSIGPROC = false;
    // Use PSRDADA buffer as input
    bool dataPSRDADA = false;
    // SIGPROC streaming mode
    bool streamingMode = false;
    // Size (in bytes) of the SIGPROC file header
    unsigned int headerSizeSIGPROC = 0;
    // Name of the input file
    std::string dataFile{};
    // Basename for the output files
    std::string outputFile{};
    // Name of the file containing the zapped channels
    std::string channelsFile{};
    // Name of the file containing the integration steps
    std::string integrationFile{};
#ifdef HAVE_HDF5
    // Limit the number of batches processed from a LOFAR file
    bool limit = false;
    // Name of the LOFAR header file
    std::string headerFile{};
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    // PSRDADA buffer key
    key_t dadaKey = 0;
#endif // HAVE_PSRDADA
};

struct GeneratorOptions
{
    // Use random numbers in generated data
    bool random = false;
    // Width of random generated pulse
    unsigned int width = 0;
    // DM of random generated pulse
    float DM = 0.0f;
};

struct HostMemory
{
    // Input data when reading a whole input file
    std::vector<std::vector<std::vector<inputDataType> *> *> input;
    // Input data when in streaming mode
    std::vector<std::vector<inputDataType> *> inputStream;
    // Zapped channels
    std::vector<unsigned int> zappedChannels;
    // Integration steps
    std::set<unsigned int> integrationSteps;
    // Map to create synthesized beams
    std::vector<unsigned int> beamMapping;
    // Dispersed data
    std::vector<inputDataType> dispersedData;
    // Subbanded data
    std::vector<outputDataType> subbandedData;
    // Dedispersed data
    std::vector<outputDataType> dedispersedData;
    // Integrated data
    std::vector<outputDataType> integratedData;
    // SNR data (SNR mode)
    std::vector<float> snrData;
    // Index of the sample with highest SNR value (SNR mode)
    std::vector<unsigned int> snrSamples;
    // Value of max sample (MOMAD mode)
    std::vector<outputDataType> maxValues;
    // Index of max sample (MOMAD MODE)
    std::vector<unsigned int> maxIndices;
    // Medians of medians (MOMAD mode)
    std::vector<outputDataType> mediansOfMedians;
    // Medians of medians absolute deviation (MOMAD mode)
    std::vector<outputDataType> medianOfMediansAbsoluteDeviation;
    // Shifts single step dedispersion
    std::vector<float> *shiftsSingleStep = nullptr;
    // Shifts step one subbanding dedispersion
    std::vector<float> *shiftsStepOne = nullptr;
    // Shifts step two subbanding dedispersion
    std::vector<float> *shiftsStepTwo = nullptr;
#ifdef HAVE_PSRDADA
    // PSRDADA ring buffer
    dada_hdu_t *ringBuffer = nullptr;
#endif // HAVE_PSRDADA
};

struct DeviceMemory
{
    // Shifts single step dedispersion
    cl::Buffer shiftsSingleStep;
    // Shifts step one subbanding dedispersion
    cl::Buffer shiftsStepOne;
    // Shifts step two subbanding dedispersion
    cl::Buffer shiftsStepTwo;
    // Zapped channels
    cl::Buffer zappedChannels;
    // Map to create synthesized beams
    cl::Buffer beamMapping;
    // Dispersed dada
    cl::Buffer dispersedData;
    // Subbanded data
    cl::Buffer subbandedData;
    // Dedispersed data
    cl::Buffer dedispersedData;
    // Integrated data
    cl::Buffer integratedData;
    // SNR data (SNR mode)
    cl::Buffer snrData;
    // Index of the sample with highest SNR value (SNR mode)
    cl::Buffer snrSamples;
    // Value of max sample (MOMAD mode)
    cl::Buffer maxValues;
    // Index of max sample (MOMAD mode)
    cl::Buffer maxIndices;
    // Median of medians first step (MOMAD mode)
    cl::Buffer medianOfMediansStepOne;
    // Median of medians second step (MOMAD mode)
    cl::Buffer medianOfMediansStepTwo;
};

struct KernelConfigurations
{
    // Configuration of single step dedispersion kernel
    Dedispersion::tunedDedispersionConf dedispersionSingleStepParameters;
    // Configuration of subband dedispersion kernel, step one
    Dedispersion::tunedDedispersionConf dedispersionStepOneParameters;
    // Configuration of subband dedispersion kernel, step two
    Dedispersion::tunedDedispersionConf dedispersionStepTwoParameters;
    // Configuration of integration kernel
    Integration::tunedIntegrationConf integrationParameters;
    // Configuration of SNR kernel (SNR mode)
    SNR::tunedSNRConf snrParameters;
    // Configuration of max kernel (MOMAD mode)
    SNR::tunedSNRConf maxParameters;
    // Configuration of median of medians first step (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansStepOneParameters;
    // Configuration of median of medians second step (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansStepTwoParameters;
    // Configuration of median of medians absolute deviation (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansAbsoluteDeviationParameters;
};

struct Kernels
{
    // Single step dedispersion kernel
    cl::Kernel *dedispersionSingleStep = nullptr;
    // Step one subbanding dedispersion kernel
    cl::Kernel *dedispersionStepOne = nullptr;
    // Step two subbanding dedispersion kernel
    cl::Kernel *dedispersionStepTwo = nullptr;
    // Integration kernels, one for each integration step
    std::vector<cl::Kernel *> integration;
    // SNR kernels, one for the original data and one for each integration step
    std::vector<cl::Kernel *> snr;
};

struct KernelRunTimeConfigurations
{
    // Global NDrange for single step dedispersion
    cl::NDRange dedispersionSingleStepGlobal;
    // Local NDRange for single step dedispersion
    cl::NDRange dedispersionSingleStepLocal;
    // Global NDRange for subbanding dedispersion step one
    cl::NDRange dedispersionStepOneGlobal;
    // Local NDRange for subbanding dedispersion step one
    cl::NDRange dedispersionStepOneLocal;
    // Global NDRange for subbanding dedispersion step two
    cl::NDRange dedispersionStepTwoGlobal;
    // Local NDRange for subbanding dedispersion step two
    cl::NDRange dedispersionStepTwoLocal;
    // Global NDRange for integration
    std::vector<cl::NDRange> integrationGlobal;
    // Local NDRange for integration
    std::vector<cl::NDRange> integrationLocal;
    // Global NDRange for SNR
    std::vector<cl::NDRange> snrGlobal;
    // Local NDRange for SNR
    std::vector<cl::NDRange> snrLocal;
};

struct Timers
{
    isa::utils::Timer inputLoad;
    isa::utils::Timer search;
    isa::utils::Timer inputHandling;
    isa::utils::Timer inputCopy;
    isa::utils::Timer dedispersionSingleStep;
    isa::utils::Timer dedispersionStepOne;
    isa::utils::Timer dedispersionStepTwo;
    isa::utils::Timer integration;
    isa::utils::Timer snr;
    isa::utils::Timer outputCopy;
    isa::utils::Timer trigger;
};

struct TriggeredEvent
{
    unsigned int beam = 0;
    unsigned int sample = 0;
    unsigned int integration = 0;
    float DM = 0.0f;
    float SNR = 0.0f;
};

struct CompactedEvent : TriggeredEvent
{
    unsigned int compactedIntegration = 1;
    unsigned int compactedDMs = 1;
};

using TriggeredEvents = std::vector<std::map<unsigned int, std::vector<TriggeredEvent>>>;
using CompactedEvents = std::vector<std::vector<CompactedEvent>>;

struct OpenCLRunTime
{
    cl::Context *context = nullptr;
    std::vector<cl::Platform> *platforms = nullptr;
    std::vector<cl::Device> *devices = nullptr;
    std::vector<std::vector<cl::CommandQueue>> *queues = nullptr;
};

enum SNRMode
{
    Standard,
    Momad
};
<commit_msg>Added ther kernels.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

struct Options
{
    // Debug mode
    bool debug = false;
    // Print messages to standard output
    bool print = false;
    // Use subband dedispersion
    bool subbandDedispersion = false;
    // Avoid merging batches of dispersed data into contiguous memory
    bool splitBatchesDedispersion = false;
    // Compact the triggered events in time and DM dimensions
    bool compactResults = false;
    // Threshold for triggering
    float threshold = 0.0f;
    // SNR mode
    SNRMode snrMode;
    // Step size for median of medians (MOMAD mode)
    unsigned int medianStepSize = 5;
};

struct DeviceOptions
{
    // OpenCL synchronized operations
    bool synchronized = false;
    // OpenCL platform ID
    unsigned int platformID = 0;
    // OpenCL device ID
    unsigned int deviceID = 0;
    // OpenCL device name
    std::string deviceName{};
    // Padding of OpenCL devices
    AstroData::paddingConf padding{};
};

struct DataOptions
{
    // Use LOFAR file as input
    bool dataLOFAR = false;
    // Use SIGPROC file as input
    bool dataSIGPROC = false;
    // Use PSRDADA buffer as input
    bool dataPSRDADA = false;
    // SIGPROC streaming mode
    bool streamingMode = false;
    // Size (in bytes) of the SIGPROC file header
    unsigned int headerSizeSIGPROC = 0;
    // Name of the input file
    std::string dataFile{};
    // Basename for the output files
    std::string outputFile{};
    // Name of the file containing the zapped channels
    std::string channelsFile{};
    // Name of the file containing the integration steps
    std::string integrationFile{};
#ifdef HAVE_HDF5
    // Limit the number of batches processed from a LOFAR file
    bool limit = false;
    // Name of the LOFAR header file
    std::string headerFile{};
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    // PSRDADA buffer key
    key_t dadaKey = 0;
#endif // HAVE_PSRDADA
};

struct GeneratorOptions
{
    // Use random numbers in generated data
    bool random = false;
    // Width of random generated pulse
    unsigned int width = 0;
    // DM of random generated pulse
    float DM = 0.0f;
};

struct HostMemory
{
    // Input data when reading a whole input file
    std::vector<std::vector<std::vector<inputDataType> *> *> input;
    // Input data when in streaming mode
    std::vector<std::vector<inputDataType> *> inputStream;
    // Zapped channels
    std::vector<unsigned int> zappedChannels;
    // Integration steps
    std::set<unsigned int> integrationSteps;
    // Map to create synthesized beams
    std::vector<unsigned int> beamMapping;
    // Dispersed data
    std::vector<inputDataType> dispersedData;
    // Subbanded data
    std::vector<outputDataType> subbandedData;
    // Dedispersed data
    std::vector<outputDataType> dedispersedData;
    // Integrated data
    std::vector<outputDataType> integratedData;
    // SNR data (SNR mode)
    std::vector<float> snrData;
    // Index of the sample with highest SNR value (SNR mode)
    std::vector<unsigned int> snrSamples;
    // Value of max sample (MOMAD mode)
    std::vector<outputDataType> maxValues;
    // Index of max sample (MOMAD MODE)
    std::vector<unsigned int> maxIndices;
    // Medians of medians (MOMAD mode)
    std::vector<outputDataType> mediansOfMedians;
    // Medians of medians absolute deviation (MOMAD mode)
    std::vector<outputDataType> medianOfMediansAbsoluteDeviation;
    // Shifts single step dedispersion
    std::vector<float> *shiftsSingleStep = nullptr;
    // Shifts step one subbanding dedispersion
    std::vector<float> *shiftsStepOne = nullptr;
    // Shifts step two subbanding dedispersion
    std::vector<float> *shiftsStepTwo = nullptr;
#ifdef HAVE_PSRDADA
    // PSRDADA ring buffer
    dada_hdu_t *ringBuffer = nullptr;
#endif // HAVE_PSRDADA
};

struct DeviceMemory
{
    // Shifts single step dedispersion
    cl::Buffer shiftsSingleStep;
    // Shifts step one subbanding dedispersion
    cl::Buffer shiftsStepOne;
    // Shifts step two subbanding dedispersion
    cl::Buffer shiftsStepTwo;
    // Zapped channels
    cl::Buffer zappedChannels;
    // Map to create synthesized beams
    cl::Buffer beamMapping;
    // Dispersed dada
    cl::Buffer dispersedData;
    // Subbanded data
    cl::Buffer subbandedData;
    // Dedispersed data
    cl::Buffer dedispersedData;
    // Integrated data
    cl::Buffer integratedData;
    // SNR data (SNR mode)
    cl::Buffer snrData;
    // Index of the sample with highest SNR value (SNR mode)
    cl::Buffer snrSamples;
    // Value of max sample (MOMAD mode)
    cl::Buffer maxValues;
    // Index of max sample (MOMAD mode)
    cl::Buffer maxIndices;
    // Median of medians first step (MOMAD mode)
    cl::Buffer medianOfMediansStepOne;
    // Median of medians second step (MOMAD mode)
    cl::Buffer medianOfMediansStepTwo;
};

struct KernelConfigurations
{
    // Configuration of single step dedispersion kernel
    Dedispersion::tunedDedispersionConf dedispersionSingleStepParameters;
    // Configuration of subband dedispersion kernel, step one
    Dedispersion::tunedDedispersionConf dedispersionStepOneParameters;
    // Configuration of subband dedispersion kernel, step two
    Dedispersion::tunedDedispersionConf dedispersionStepTwoParameters;
    // Configuration of integration kernel
    Integration::tunedIntegrationConf integrationParameters;
    // Configuration of SNR kernel (SNR mode)
    SNR::tunedSNRConf snrParameters;
    // Configuration of max kernel (MOMAD mode)
    SNR::tunedSNRConf maxParameters;
    // Configuration of median of medians first step (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansStepOneParameters;
    // Configuration of median of medians second step (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansStepTwoParameters;
    // Configuration of median of medians absolute deviation (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansAbsoluteDeviationParameters;
};

struct Kernels
{
    // Single step dedispersion kernel
    cl::Kernel *dedispersionSingleStep = nullptr;
    // Step one subbanding dedispersion kernel
    cl::Kernel *dedispersionStepOne = nullptr;
    // Step two subbanding dedispersion kernel
    cl::Kernel *dedispersionStepTwo = nullptr;
    // Integration kernels, one for each integration step
    std::vector<cl::Kernel *> integration;
    // SNR kernels, one for the original data and one for each integration step (SNR mode)
    std::vector<cl::Kernel *> snr;
    // Max kernels, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> max;
    // Median of medians first step, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> medianOfMediansStepOne;
    // Median of medians second step, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> medianOfMediansStepTwo;
    // Median of medians absolute deviation, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> medianOfMediansAbsoluteDeviation;
};

struct KernelRunTimeConfigurations
{
    // Global NDrange for single step dedispersion
    cl::NDRange dedispersionSingleStepGlobal;
    // Local NDRange for single step dedispersion
    cl::NDRange dedispersionSingleStepLocal;
    // Global NDRange for subbanding dedispersion step one
    cl::NDRange dedispersionStepOneGlobal;
    // Local NDRange for subbanding dedispersion step one
    cl::NDRange dedispersionStepOneLocal;
    // Global NDRange for subbanding dedispersion step two
    cl::NDRange dedispersionStepTwoGlobal;
    // Local NDRange for subbanding dedispersion step two
    cl::NDRange dedispersionStepTwoLocal;
    // Global NDRange for integration
    std::vector<cl::NDRange> integrationGlobal;
    // Local NDRange for integration
    std::vector<cl::NDRange> integrationLocal;
    // Global NDRange for SNR
    std::vector<cl::NDRange> snrGlobal;
    // Local NDRange for SNR
    std::vector<cl::NDRange> snrLocal;
};

struct Timers
{
    isa::utils::Timer inputLoad;
    isa::utils::Timer search;
    isa::utils::Timer inputHandling;
    isa::utils::Timer inputCopy;
    isa::utils::Timer dedispersionSingleStep;
    isa::utils::Timer dedispersionStepOne;
    isa::utils::Timer dedispersionStepTwo;
    isa::utils::Timer integration;
    isa::utils::Timer snr;
    isa::utils::Timer outputCopy;
    isa::utils::Timer trigger;
};

struct TriggeredEvent
{
    unsigned int beam = 0;
    unsigned int sample = 0;
    unsigned int integration = 0;
    float DM = 0.0f;
    float SNR = 0.0f;
};

struct CompactedEvent : TriggeredEvent
{
    unsigned int compactedIntegration = 1;
    unsigned int compactedDMs = 1;
};

using TriggeredEvents = std::vector<std::map<unsigned int, std::vector<TriggeredEvent>>>;
using CompactedEvents = std::vector<std::vector<CompactedEvent>>;

struct OpenCLRunTime
{
    cl::Context *context = nullptr;
    std::vector<cl::Platform> *platforms = nullptr;
    std::vector<cl::Device> *devices = nullptr;
    std::vector<std::vector<cl::CommandQueue>> *queues = nullptr;
};

enum SNRMode
{
    Standard,
    Momad
};
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS ka004 (1.5.38); FILE MERGED 2005/10/26 07:11:19 ka 1.5.38.2: RESYNC: (1.5-1.6); FILE MERGED 2005/10/12 14:50:21 ka 1.5.38.1: #i42827#: added svg and xlink namespace to svg element<commit_after><|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * Learning Material from "Programming: Principles and Practices Using C++"
 *
 * hello_word.cpp
 *
 * An early C++ program teaching #include and simple i/o
 */

#include "../lib/std_lib_facilities.h"

/*
 * Note that the early exercises (Ch 1-5) can be completed
 * using an equivalent directive:
 *
 * #include<iostream>
 * #include<string>
 * #include<vector>
 * #include<algorithm>
 * #include<cmath>
 * using namespace std;
 * inline voide keep_window_open() { char ch; cin>>ch; }
 *
 */

int main() {
    cout << "Hello, World!\n";	// Outputs string to standard output device
    keep_window_open();			// Your guess is as good as mine
    return 0;					// Standard successful return value
}<commit_msg>Formatting corrections<commit_after>/*
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * Learning Material from "Programming: Principles and Practices Using C++"
 *
 * hello_word.cpp
 *
 * An early C++ program teaching #include and simple i/o
 */

#include "../lib/std_lib_facilities.h"

/*
 * Note that the early exercises (Ch 1-5) can also be completed
 * by replacing the source line above with the equivalent:
 *
 * #include<iostream>
 * #include<string>
 * #include<vector>
 * #include<algorithm>
 * #include<cmath>
 * using namespace std;
 * inline voide keep_window_open() { char ch; cin>>ch; }
 *
 */

int main() {
    cout << "Hello, World!\n";	// Outputs string to standard output device
    keep_window_open();		// Your guess is as good as mine
    return 0;			// Standard successful return value
}<|endoftext|>


<commit_before><commit_msg>Account for erased vertices in TriangleTopology::internal_add_vertex<commit_after><|endoftext|>


<commit_before>#pragma once
#include <sys/types.h>
#include <memory>
#include <array>
#include <list>
#include <vector>
#include <string>
#include <fstream>

enum Mode { r, w, rw };

enum EntryType { file, dir };

class ToyFS {
  class Inode {
    public:

    uint size;
    uint block_size;
    std::array<uint, 50>d_blocks;
    std::unique_ptr < std::array < std::array<uint, 50>, 50 >> i_blocks;
  };

  class DirEntry {
    public:

    EntryType type;
    std::string name;
    std::weak_ptr<DirEntry>parent;
    std::shared_ptr<Inode>inode;
    std::list < std::shared_ptr < DirEntry >> subdirs;
    DirEntry(const std::string              name,
             const std::weak_ptr<DirEntry>& parent);
    DirEntry(const std::string              name,
             const std::weak_ptr<DirEntry>& parent,
             const std::shared_ptr<Inode> & inode);

    // move creation out to toyfs
  };

  class FreeNode {
    public:

    uint num_blocks;
    uint pos;
    FreeNode(uint num_blocks, uint pos)
      : num_blocks(num_blocks),
      pos(pos) {}
  };

  const std::string filename;
  std::fstream disk_file;
  const uint fs_size;
  const uint block_size;
  const uint num_blocks;
  DirEntry root;
  std::list<FreeNode>free_nodes;

  void init_disk(const std::string& filename);

  public:

  ToyFS(const std::string& filename, const uint fs_size, const uint block_size);
  ~ToyFS();
};
<commit_msg>commented out root so we can compile and run<commit_after>#pragma once
#include <sys/types.h>
#include <memory>
#include <array>
#include <list>
#include <vector>
#include <string>
#include <fstream>

enum Mode { r, w, rw };

enum EntryType { file, dir };

class ToyFS {
  class Inode {
    public:

    uint size;
    uint block_size;
    std::array<uint, 50>d_blocks;
    std::unique_ptr < std::array < std::array<uint, 50>, 50 >> i_blocks;
  };

  class DirEntry {
    public:

    EntryType type;
    std::string name;
    std::weak_ptr<DirEntry>parent;
    std::shared_ptr<Inode>inode;
    std::list < std::shared_ptr < DirEntry >> subdirs;
    DirEntry(const std::string              name,
             const std::weak_ptr<DirEntry>& parent);
    DirEntry(const std::string              name,
             const std::weak_ptr<DirEntry>& parent,
             const std::shared_ptr<Inode> & inode);

    // move creation out to toyfs
  };

  class FreeNode {
    public:

    uint num_blocks;
    uint pos;
    FreeNode(uint num_blocks, uint pos)
      : num_blocks(num_blocks),
      pos(pos) {}
  };

  const std::string filename;
  std::fstream disk_file;
  const uint fs_size;
  const uint block_size;
  const uint num_blocks;

  // DirEntry root;
  std::list<FreeNode>free_nodes;

  void init_disk(const std::string& filename);

  public:

  ToyFS(const std::string& filename, const uint fs_size, const uint block_size);
  ~ToyFS();
};
<|endoftext|>


<commit_before>/* test-c.c
 *
 * A sample C++ program to test Dr.MinGW.
 *
 * Jose Fonseca
 */

#include <stdio.h>

typedef char * cp;

static void YetAnotherFunction( int i, double j, const char * pszString )
{
    int k;

#if 0
    /* Other ways to cause a GPF */
    *(int *)i = 5;
    __asm ("int $3");
    (*((void (*)(void)) 0x12345678))();
#endif

    sscanf("12345", "%i", (int *) (k=i));
}

static void MyWonderfulFunction( int i, float j )
{
    YetAnotherFunction( i * 2, j, "Hello" );
}

int main()
{
    MyWonderfulFunction( 4, float(5.6) );

    return 0;
}
<commit_msg>Silence warning in 64bit build of test case.<commit_after>/* test-c.c
 *
 * A sample C++ program to test Dr.MinGW.
 *
 * Jose Fonseca
 */

#include <stdio.h>
#include <stdlib.h>

typedef char * cp;

static void YetAnotherFunction( int i, double j, const char * pszString )
{
    int k;

#if 0
    /* Other ways to cause a GPF */
    *(int *)i = 5;
    __asm ("int $3");
    (*((void (*)(void)) 0x12345678))();
#endif

    sscanf("12345", "%i", (int *) (size_t) (k=i));
}

static void MyWonderfulFunction( int i, float j )
{
    YetAnotherFunction( i * 2, j, "Hello" );
}

int main()
{
    MyWonderfulFunction( 4, float(5.6) );

    return 0;
}
<|endoftext|>


<commit_before>//=====================================================
// File   :  btl.hh
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//=====================================================
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//
#ifndef BTL_HH
#define BTL_HH

#include "bench_parameter.hh"
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include "utilities.h"

#if (defined __GNUC__)
#define BTL_ALWAYS_INLINE __attribute__((always_inline)) inline
#else
#define BTL_ALWAYS_INLINE inline
#endif

#if (defined __GNUC__)
#define BTL_DONT_INLINE __attribute__((noinline))
#else
#define BTL_DONT_INLINE
#endif

#if (defined __GNUC__)
#define BTL_ASM_COMMENT(X)  asm("#"X)
#else
#define BTL_ASM_COMMENT(X)
#endif

#if (defined __GNUC__) && (!defined __INTEL_COMPILER)
#define BTL_DISABLE_SSE_EXCEPTIONS()  { \
  int aux; \
  asm( \
  "stmxcsr   %[aux]           \n\t" \
  "orl       $32832, %[aux]   \n\t" \
  "ldmxcsr   %[aux]           \n\t" \
  : : [aux] "m" (aux)); \
}
#else
#define BTL_DISABLE_SSE_EXCEPTIONS()
#endif

/** Enhanced std::string
*/
class BtlString : public std::string
{
public:
    BtlString() : std::string() {}
    BtlString(const BtlString& str) : std::string(static_cast<const std::string&>(str)) {}
    BtlString(const std::string& str) : std::string(str) {}
    BtlString(const char* str) : std::string(str) {}

    operator const char* () const { return c_str(); }

    void trim( bool left = true, bool right = true )
    {
        int lspaces, rspaces, len = length(), i;
        lspaces = rspaces = 0;

        if ( left )
            for (i=0; i<len && (at(i)==' '||at(i)=='\t'||at(i)=='\r'||at(i)=='\n'); ++lspaces,++i);

        if ( right && lspaces < len )
            for(i=len-1; i>=0 && (at(i)==' '||at(i)=='\t'||at(i)=='\r'||at(i)=='\n'); rspaces++,i--);

        *this = substr(lspaces, len-lspaces-rspaces);
    }

    std::vector<BtlString> split( const BtlString& delims = "\t\n ") const
    {
        std::vector<BtlString> ret;
        unsigned int numSplits = 0;
        size_t start, pos;
        start = 0;
        do
        {
            pos = find_first_of(delims, start);
            if (pos == start)
            {
                ret.push_back("");
                start = pos + 1;
            }
            else if (pos == npos)
                ret.push_back( substr(start) );
            else
            {
                ret.push_back( substr(start, pos - start) );
                start = pos + 1;
            }
            //start = find_first_not_of(delims, start);
            ++numSplits;
        } while (pos != npos);
        return ret;
    }

    bool endsWith(const BtlString& str) const
    {
        if(str.size()>this->size())
            return false;
        return this->substr(this->size()-str.size(),str.size()) == str;
    }
    bool contains(const BtlString& str) const
    {
        return this->find(str)<this->size();
    }
    bool beginsWith(const BtlString& str) const
    {
        if(str.size()>this->size())
            return false;
        return this->substr(0,str.size()) == str;
    }

    BtlString toLowerCase( void )
    {
        std::transform(begin(), end(), begin(), static_cast<int(*)(int)>(::tolower) );
        return *this;
    }
    BtlString toUpperCase( void )
    {
        std::transform(begin(), end(), begin(), static_cast<int(*)(int)>(::toupper) );
        return *this;
    }

    /** Case insensitive comparison.
    */
    bool isEquiv(const BtlString& str) const
    {
        BtlString str0 = *this;
        str0.toLowerCase();
        BtlString str1 = str;
        str1.toLowerCase();
        return str0 == str1;
    }

    /** Decompose the current string as a path and a file.
        For instance: "dir1/dir2/file.ext" leads to path="dir1/dir2/" and filename="file.ext"
    */
    void decomposePathAndFile(BtlString& path, BtlString& filename) const
    {
        std::vector<BtlString> elements = this->split("/\\");
        path = "";
        filename = elements.back();
        elements.pop_back();
        if (this->at(0)=='/')
            path = "/";
        for (unsigned int i=0 ; i<elements.size() ; ++i)
            path += elements[i] + "/";
    }
};

class BtlConfig
{
public:
  BtlConfig()
    : overwriteResults(false), checkResults(true), realclock(false), tries(DEFAULT_NB_TRIES)
  {
    char * _config;
    _config = getenv ("BTL_CONFIG");
    if (_config!=NULL)
    {
      std::vector<BtlString> config = BtlString(_config).split(" \t\n");
      for (int i = 0; i<config.size(); i++)
      {
        if (config[i].beginsWith("-a"))
        {
          if (i+1==config.size())
          {
            std::cerr << "error processing option: " << config[i] << "\n";
            exit(2);
          }
          Instance.m_selectedActionNames = config[i+1].split(":");

          i += 1;
        }
        else if (config[i].beginsWith("-t"))
        {
          if (i+1==config.size())
          {
            std::cerr << "error processing option: " << config[i] << "\n";
            exit(2);
          }
          Instance.tries = atoi(config[i+1].c_str());

          i += 1;
        }
        else if (config[i].beginsWith("--overwrite"))
        {
          Instance.overwriteResults = true;
        }
        else if (config[i].beginsWith("--nocheck"))
        {
          Instance.checkResults = false;
        }
        else if (config[i].beginsWith("--real"))
        {
          Instance.realclock = true;
        }
      }
    }

    BTL_DISABLE_SSE_EXCEPTIONS();
  }

  BTL_DONT_INLINE static bool skipAction(const std::string& _name)
  {
    if (Instance.m_selectedActionNames.empty())
      return false;

    BtlString name(_name);
    for (int i=0; i<Instance.m_selectedActionNames.size(); ++i)
      if (name.contains(Instance.m_selectedActionNames[i]))
        return false;

    return true;
  }

  static BtlConfig Instance;
  bool overwriteResults;
  bool checkResults;
  bool realclock;
  int tries;

protected:
  std::vector<BtlString> m_selectedActionNames;
};

#define BTL_MAIN \
  BtlConfig BtlConfig::Instance

#endif // BTL_HH
<commit_msg>check for !x86 platforms, otherwise the BTL benchmark doesn't compile on arm/powerpc<commit_after>//=====================================================
// File   :  btl.hh
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//=====================================================
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//
#ifndef BTL_HH
#define BTL_HH

#include "bench_parameter.hh"
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include "utilities.h"

#if (defined __GNUC__)
#define BTL_ALWAYS_INLINE __attribute__((always_inline)) inline
#else
#define BTL_ALWAYS_INLINE inline
#endif

#if (defined __GNUC__)
#define BTL_DONT_INLINE __attribute__((noinline))
#else
#define BTL_DONT_INLINE
#endif

#if (defined __GNUC__)
#define BTL_ASM_COMMENT(X)  asm("#"X)
#else
#define BTL_ASM_COMMENT(X)
#endif

#if (defined __GNUC__) && (!defined __INTEL_COMPILER) && !defined(__arm__) && !defined(__powerpc__)
#define BTL_DISABLE_SSE_EXCEPTIONS()  { \
  int aux; \
  asm( \
  "stmxcsr   %[aux]           \n\t" \
  "orl       $32832, %[aux]   \n\t" \
  "ldmxcsr   %[aux]           \n\t" \
  : : [aux] "m" (aux)); \
}
#else
#define BTL_DISABLE_SSE_EXCEPTIONS()
#endif

/** Enhanced std::string
*/
class BtlString : public std::string
{
public:
    BtlString() : std::string() {}
    BtlString(const BtlString& str) : std::string(static_cast<const std::string&>(str)) {}
    BtlString(const std::string& str) : std::string(str) {}
    BtlString(const char* str) : std::string(str) {}

    operator const char* () const { return c_str(); }

    void trim( bool left = true, bool right = true )
    {
        int lspaces, rspaces, len = length(), i;
        lspaces = rspaces = 0;

        if ( left )
            for (i=0; i<len && (at(i)==' '||at(i)=='\t'||at(i)=='\r'||at(i)=='\n'); ++lspaces,++i);

        if ( right && lspaces < len )
            for(i=len-1; i>=0 && (at(i)==' '||at(i)=='\t'||at(i)=='\r'||at(i)=='\n'); rspaces++,i--);

        *this = substr(lspaces, len-lspaces-rspaces);
    }

    std::vector<BtlString> split( const BtlString& delims = "\t\n ") const
    {
        std::vector<BtlString> ret;
        unsigned int numSplits = 0;
        size_t start, pos;
        start = 0;
        do
        {
            pos = find_first_of(delims, start);
            if (pos == start)
            {
                ret.push_back("");
                start = pos + 1;
            }
            else if (pos == npos)
                ret.push_back( substr(start) );
            else
            {
                ret.push_back( substr(start, pos - start) );
                start = pos + 1;
            }
            //start = find_first_not_of(delims, start);
            ++numSplits;
        } while (pos != npos);
        return ret;
    }

    bool endsWith(const BtlString& str) const
    {
        if(str.size()>this->size())
            return false;
        return this->substr(this->size()-str.size(),str.size()) == str;
    }
    bool contains(const BtlString& str) const
    {
        return this->find(str)<this->size();
    }
    bool beginsWith(const BtlString& str) const
    {
        if(str.size()>this->size())
            return false;
        return this->substr(0,str.size()) == str;
    }

    BtlString toLowerCase( void )
    {
        std::transform(begin(), end(), begin(), static_cast<int(*)(int)>(::tolower) );
        return *this;
    }
    BtlString toUpperCase( void )
    {
        std::transform(begin(), end(), begin(), static_cast<int(*)(int)>(::toupper) );
        return *this;
    }

    /** Case insensitive comparison.
    */
    bool isEquiv(const BtlString& str) const
    {
        BtlString str0 = *this;
        str0.toLowerCase();
        BtlString str1 = str;
        str1.toLowerCase();
        return str0 == str1;
    }

    /** Decompose the current string as a path and a file.
        For instance: "dir1/dir2/file.ext" leads to path="dir1/dir2/" and filename="file.ext"
    */
    void decomposePathAndFile(BtlString& path, BtlString& filename) const
    {
        std::vector<BtlString> elements = this->split("/\\");
        path = "";
        filename = elements.back();
        elements.pop_back();
        if (this->at(0)=='/')
            path = "/";
        for (unsigned int i=0 ; i<elements.size() ; ++i)
            path += elements[i] + "/";
    }
};

class BtlConfig
{
public:
  BtlConfig()
    : overwriteResults(false), checkResults(true), realclock(false), tries(DEFAULT_NB_TRIES)
  {
    char * _config;
    _config = getenv ("BTL_CONFIG");
    if (_config!=NULL)
    {
      std::vector<BtlString> config = BtlString(_config).split(" \t\n");
      for (int i = 0; i<config.size(); i++)
      {
        if (config[i].beginsWith("-a"))
        {
          if (i+1==config.size())
          {
            std::cerr << "error processing option: " << config[i] << "\n";
            exit(2);
          }
          Instance.m_selectedActionNames = config[i+1].split(":");

          i += 1;
        }
        else if (config[i].beginsWith("-t"))
        {
          if (i+1==config.size())
          {
            std::cerr << "error processing option: " << config[i] << "\n";
            exit(2);
          }
          Instance.tries = atoi(config[i+1].c_str());

          i += 1;
        }
        else if (config[i].beginsWith("--overwrite"))
        {
          Instance.overwriteResults = true;
        }
        else if (config[i].beginsWith("--nocheck"))
        {
          Instance.checkResults = false;
        }
        else if (config[i].beginsWith("--real"))
        {
          Instance.realclock = true;
        }
      }
    }

    BTL_DISABLE_SSE_EXCEPTIONS();
  }

  BTL_DONT_INLINE static bool skipAction(const std::string& _name)
  {
    if (Instance.m_selectedActionNames.empty())
      return false;

    BtlString name(_name);
    for (int i=0; i<Instance.m_selectedActionNames.size(); ++i)
      if (name.contains(Instance.m_selectedActionNames[i]))
        return false;

    return true;
  }

  static BtlConfig Instance;
  bool overwriteResults;
  bool checkResults;
  bool realclock;
  int tries;

protected:
  std::vector<BtlString> m_selectedActionNames;
};

#define BTL_MAIN \
  BtlConfig BtlConfig::Instance

#endif // BTL_HH
<|endoftext|>


<commit_before>/*
 * Trace.hpp
 *
 *  Created on: Jul 31, 2014
 *      Author: tgil
 */

#ifndef TRACE_HPP_
#define TRACE_HPP_

#ifndef __link

#include <mcu/types.h>
#include <iface/link.h>
#include <iface/stratify_link_transport_usb.h>

#include "../var/String.hpp"

namespace sys {

class Trace : public var::String {
public:
	Trace(){}

	Trace& operator=(const char * a){ var::String::operator=(a); return *this; }
	Trace& operator=(const var::String & a){ var::String::operator=(a); return *this; }

	inline void message() MCU_ALWAYS_INLINE { stratify_trace_event(POSIX_TRACE_MESSAGE, c_str(), size()); }
	inline void warning() MCU_ALWAYS_INLINE { stratify_trace_event(POSIX_TRACE_WARNING, c_str(), size()); }
	inline void critical() MCU_ALWAYS_INLINE { stratify_trace_event(POSIX_TRACE_CRITICAL, c_str(), size()); }
	inline void fatal() MCU_ALWAYS_INLINE { stratify_trace_event(POSIX_TRACE_FATAL, c_str(), size()); }

};

};

#endif

#endif /* TRACE_HPP_ */
<commit_msg>Add trace error<commit_after>/*
 * Trace.hpp
 *
 *  Created on: Jul 31, 2014
 *      Author: tgil
 */

#ifndef TRACE_HPP_
#define TRACE_HPP_

#ifndef __link

#include <mcu/types.h>
#include <iface/link.h>
#include <iface/stratify_link_transport_usb.h>

#include "../var/String.hpp"

namespace sys {

class Trace : public var::String {
public:
	Trace(){}

	Trace& operator=(const char * a){ var::String::operator=(a); return *this; }
	Trace& operator=(const var::String & a){ var::String::operator=(a); return *this; }

	inline void message() MCU_ALWAYS_INLINE { stratify_trace_event(POSIX_TRACE_MESSAGE, c_str(), size()); }
	inline void warning() MCU_ALWAYS_INLINE { stratify_trace_event(POSIX_TRACE_WARNING, c_str(), size()); }
	inline void error() MCU_ALWAYS_INLINE { stratify_trace_event(POSIX_TRACE_ERROR, c_str(), size()); }
	inline void critical() MCU_ALWAYS_INLINE { stratify_trace_event(POSIX_TRACE_CRITICAL, c_str(), size()); }
	inline void fatal() MCU_ALWAYS_INLINE { stratify_trace_event(POSIX_TRACE_FATAL, c_str(), size()); }

};

};

#endif

#endif /* TRACE_HPP_ */
<|endoftext|>


<commit_before>
#if defined(_WIN32)
#include <windows.h>
	double Timer()
	{
		LARGE_INTEGER ticksPerSecond;
		LARGE_INTEGER tick;
		QueryPerformanceFrequency(&ticksPerSecond);
		QueryPerformanceCounter(&tick);
		return (double)tick.QuadPart/(double)ticksPerSecond.QuadPart;
	}
#else
#include <sys/time.h>
#include <stddef.h>
	long double Timer()
	{
		double t1;
		struct timeval time;
		gettimeofday(&(time), NULL);
		t1 =  (double)time.tv_sec + (double)time.tv_usec/(1000.0*1000.0);
		return t1;
	}
#endif
<commit_msg>Fix Timer() on Linux<commit_after>
#if defined(_WIN32)
#include <windows.h>
	double Timer()
	{
		LARGE_INTEGER ticksPerSecond;
		LARGE_INTEGER tick;
		QueryPerformanceFrequency(&ticksPerSecond);
		QueryPerformanceCounter(&tick);
		return (double)tick.QuadPart/(double)ticksPerSecond.QuadPart;
	}
#else
#include <sys/time.h>
#include <stddef.h>
	double Timer()
	{
		double t1;
		struct timeval time;
		gettimeofday(&(time), NULL);
		t1 =  (double)time.tv_sec + (double)time.tv_usec/(1000.0*1000.0);
		return t1;
	}
#endif
<|endoftext|>