repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/Context.h
// // Context.hpp // // Created by <NAME> on 1/20/16. // // #pragma once #include "cinder/Color.h" #include "cinder/Cinder.h" #include "RenderEncoder.h" #include "RenderPipelineState.h" #include "DataBuffer.h" namespace cinder { namespace mtl { class Context; typedef std::shared_ptr<Context> ContextRef; class ShaderDef; class Context { public: struct PlatformData { PlatformData() : mDebug( false ), mObjectTracking( false ), mDebugLogSeverity( 0 ), mDebugBreakSeverity( 0 ) {} virtual ~PlatformData() {} bool mDebug, mObjectTracking; unsigned int mDebugLogSeverity, mDebugBreakSeverity; }; static ContextRef create( const Context *sharedContext ); static ContextRef createFromExisting( const std::shared_ptr<PlatformData> &platformData ); ~Context(); const std::shared_ptr<PlatformData> getPlatformData() const { return mPlatformData; } //! Makes this the currently active Metal Context. If \a force then the cached pointer to the current Context is ignored. void makeCurrent( bool force = false ) const; //! Returns the thread's currently active Metal Context static Context* getCurrent(); //! Set thread's local storage to reflect \a context as the active Context static void reflectCurrent( Context *context ); //! Returns a reference to the stack of Model matrices std::vector<mat4>& getModelMatrixStack() { return mModelMatrixStack; } //! Returns a const reference to the stack of Model matrices const std::vector<mat4>& getModelMatrixStack() const { return mModelMatrixStack; } //! Returns a reference to the stack of View matrices std::vector<mat4>& getViewMatrixStack() { return mViewMatrixStack; } //! Returns a const reference to the stack of Model matrices const std::vector<mat4>& getViewMatrixStack() const { return mViewMatrixStack; } //! Returns a reference to the stack of Projection matrices std::vector<mat4>& getProjectionMatrixStack() { return mProjectionMatrixStack; } //! Returns a const reference to the stack of Projection matrices const std::vector<mat4>& getProjectionMatrixStack() const { return mProjectionMatrixStack; } //! Returns the current active color, used in immediate-mode emulation and as UNIFORM_COLOR const ColorAf& getCurrentColor() const { return mColor; } void setCurrentColor( const ColorAf &color ) { mColor = color; } private: Context( const std::shared_ptr<PlatformData> &platformData ); std::shared_ptr<PlatformData> mPlatformData; ci::ColorAf mColor; std::vector<mat4> mModelMatrixStack; std::vector<mat4> mViewMatrixStack; std::vector<mat4> mProjectionMatrixStack; }; // Remember to add a matching case to uniformSemanticToString enum UniformSemantic { UNIFORM_MODEL_MATRIX, UNIFORM_MODEL_MATRIX_INVERSE, UNIFORM_MODEL_MATRIX_INVERSE_TRANSPOSE, UNIFORM_VIEW_MATRIX, UNIFORM_VIEW_MATRIX_INVERSE, UNIFORM_MODEL_VIEW, UNIFORM_MODEL_VIEW_INVERSE, UNIFORM_MODEL_VIEW_INVERSE_TRANSPOSE, UNIFORM_MODEL_VIEW_PROJECTION, UNIFORM_MODEL_VIEW_PROJECTION_INVERSE, UNIFORM_PROJECTION_MATRIX, UNIFORM_PROJECTION_MATRIX_INVERSE, UNIFORM_VIEW_PROJECTION, UNIFORM_NORMAL_MATRIX, // UNIFORM_VIEWPORT_MATRIX, UNIFORM_WINDOW_SIZE, UNIFORM_ELAPSED_SECONDS, UNIFORM_USER_DEFINED }; Context* context(); void setDefaultShaderVars( RenderEncoder & renderEncoder, RenderPipelineStateRef pipeline); //! Sets the View and Projection matrices based on a Camera void setMatrices( const ci::Camera &cam ); void setModelMatrix( const ci::mat4 &m ); void setViewMatrix( const ci::mat4 &m ); void setProjectionMatrix( const ci::mat4 &m ); void pushModelMatrix(); void popModelMatrix(); void pushViewMatrix(); void popViewMatrix(); void pushProjectionMatrix(); void popProjectionMatrix(); //! Pushes Model and View matrices void pushModelView(); //! Pops Model and View matrices void popModelView(); //! Pushes Model, View and Projection matrices void pushMatrices(); //! Pops Model, View and Projection matrices void popMatrices(); void multModelMatrix( const ci::mat4 &mtx ); void multViewMatrix( const ci::mat4 &mtx ); void multProjectionMatrix( const ci::mat4 &mtx ); mat4 getModelMatrix(); mat4 getViewMatrix(); mat4 getProjectionMatrix(); mat4 getModelView(); mat4 getModelViewProjection(); mat4 calcViewMatrixInverse(); mat3 calcModelMatrixInverseTranspose(); mat3 calcNormalMatrix(); // mat4 calcViewportMatrix(); mtl::RenderPipelineStateRef & getStockPipeline( const mtl::ShaderDef &shaderDef ); void setMatricesWindowPersp( int screenWidth, int screenHeight, float fovDegrees = 60.0f, float nearPlane = 1.0f, float farPlane = 1000.0f, bool originUpperLeft = true ); void setMatricesWindowPersp( const ci::ivec2 &screenSize, float fovDegrees = 60.0f, float nearPlane = 1.0f, float farPlane = 1000.0f, bool originUpperLeft = true ); void setMatricesWindow( int screenWidth, int screenHeight, bool originUpperLeft = true ); void setMatricesWindow( const ci::ivec2 &screenSize, bool originUpperLeft = true ); void rotate( const quat &quat ); //! Rotates the Model matrix by \a angleRadians around the \a axis void rotate( float angleRadians, const ci::vec3 &axis ); //! Rotates the Model matrix by \a angleRadians around the axis (\a x,\a y,\a z) inline void rotate( float angleRadians, float xAxis, float yAxis, float zAxis ) { rotate( angleRadians, ci::vec3(xAxis, yAxis, zAxis) ); } //! Rotates the Model matrix by \a zRadians around the z-axis inline void rotate( float zRadians ) { rotate( zRadians, vec3( 0, 0, 1 ) ); } //! Scales the Model matrix by \a v void scale( const ci::vec3 &v ); //! Scales the Model matrix by (\a x,\a y, \a z) inline void scale( float x, float y, float z ) { scale( vec3( x, y, z ) ); } //! Scales the Model matrix by \a v inline void scale( const ci::vec2 &v ) { scale( vec3( v.x, v.y, 1 ) ); } //! Scales the Model matrix by (\a x,\a y, 1) inline void scale( float x, float y ) { scale( vec3( x, y, 1 ) ); } //! Translates the Model matrix by \a v void translate( const ci::vec3 &v ); //! Translates the Model matrix by (\a x,\a y,\a z ) inline void translate( float x, float y, float z ) { translate( vec3( x, y, z ) ); } //! Translates the Model matrix by \a v inline void translate( const ci::vec2 &v ) { translate( vec3( v, 0 ) ); } //! Translates the Model matrix by (\a x,\a y) inline void translate( float x, float y ) { translate( vec3( x, y, 0 ) ); } //! Returns the object space coordinate of the specified window \a coordinate, using the specified \a modelMatrix and the currently active view and projection matrices. vec3 windowToObjectCoord( const mat4 &modelMatrix, const vec2 &coordinate, const std::pair<vec2,vec2> & viewport, float z = 0.0f ); //! Returns the window coordinate of the specified world \a coordinate, using the specified \a modelMatrix and the currently active view and projection matrices. vec3 objectToWindowCoord( const mat4 &modelMatrix, const vec3 &coordinate, const std::pair<vec2,vec2> & viewport ); //vec2 objectToWindowCoord( const mat4 &modelMatrix, const vec3 &coordinate, const std::pair<vec2,vec2> & viewport ); //! Returns the object space coordinate of the specified window \a coordinate, using the currently active model, view and projection matrices. inline vec3 windowToObjectCoord( const vec2 &coordinate, const std::pair<vec2,vec2> &viewport, float z = 0.0f ) { return windowToObjectCoord( mtl::getModelMatrix(), coordinate, viewport, z ); } //! Returns the window coordinate of the specified world \a coordinate, using the currently active model, view and projection matrices. inline vec3 objectToWindowCoord( const vec3 &coordinate, const std::pair<vec2,vec2> &viewport ) { return objectToWindowCoord( mtl::getModelMatrix(), coordinate, viewport ); } // inline vec2 objectToWindowCoord( const vec3 &coordinate, const std::pair<vec2,vec2> &viewport ) { return objectToWindowCoord( mtl::getModelMatrix(), coordinate, viewport ); } //! Returns the world space coordinate of the specified window \a coordinate, using the currently active view and projection matrices. inline vec3 windowToWorldCoord( const vec2 &coordinate, const std::pair<vec2,vec2> &viewport, float z = 0.0f ) { return windowToObjectCoord( mat4(), coordinate, viewport, z ); } //! Returns the window coordinate of the specified world \a coordinate, using the currently active view and projection matrices. // inline vec2 worldToWindowCoord( const vec3 &coordinate, const std::pair<vec2,vec2> & viewport ) { return objectToWindowCoord( mat4(), coordinate, viewport ); } inline vec3 worldToWindowCoord( const vec3 &coordinate, const std::pair<vec2,vec2> & viewport ) { return objectToWindowCoord( mat4(), coordinate, viewport ); } void color( float r, float g, float b ); void color( float r, float g, float b, float a ); void color( const ci::Color &c ); void color( const ci::ColorA &c ); void color( const ci::Color8u &c ); void color( const ci::ColorA8u &c ); //! Converts a UniformSemantic to its name std::string uniformSemanticToString( UniformSemantic uniformSemantic ); class Exception : public cinder::Exception { public: Exception() {} Exception( const std::string &description ) : cinder::Exception( description ) {} }; class ExceptionUnknownTarget : public Exception { }; } } // namespace cinder::mtl
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/MetalMacros.h
<reponame>iProfeten/cinder-metal-m1<gh_stars>10-100 // // MetalConstants.h // // Created by <NAME> on 11/8/15. // // #pragma once #include <simd/simd.h> #define MetalConstants \ \ namespace cinder { \ namespace mtl { \ enum DefaultBufferShaderIndices \ { \ ciBufferIndexUniforms = 0, \ ciBufferIndexInterleavedVerts = 1, \ ciBufferIndexIndices = 2, \ ciBufferIndexPositions = 3, \ ciBufferIndexColors = 4, \ ciBufferIndexTexCoords0 = 5, \ ciBufferIndexTexCoords1 = 6, \ ciBufferIndexTexCoords2 = 7, \ ciBufferIndexTexCoords3 = 8, \ ciBufferIndexNormals = 9, \ ciBufferIndexTangents = 10, \ ciBufferIndexBitangents = 11, \ ciBufferIndexBoneIndices = 12, \ ciBufferIndexBoneWeight = 13, \ ciBufferIndexCustom0 = 14, \ ciBufferIndexCustom1 = 15, \ ciBufferIndexCustom2 = 16, \ ciBufferIndexCustom3 = 17, \ ciBufferIndexCustom4 = 18, \ ciBufferIndexCustom5 = 19, \ ciBufferIndexCustom6 = 20, \ ciBufferIndexCustom7 = 21, \ ciBufferIndexCustom8 = 22, \ ciBufferIndexCustom9 = 23, \ ciBufferIndexInstanceData = 24, \ }; \ \ enum DefaultSamplerShaderIndices \ { \ ciSamplerIndex0 = 0, \ ciSamplerIndex1 = 1, \ ciSamplerIndex2 = 2, \ }; \ \ enum DefaultTextureShaderIndices \ { \ ciTextureIndex0 = 0, \ ciTextureIndex1 = 1, \ ciTextureIndex2 = 2, \ }; \ } \ } #define ShaderTypes \ \ namespace cinder { \ namespace mtl { \ typedef struct \ { \ matrix_float4x4 ciModelMatrix; \ matrix_float4x4 ciModelMatrixInverse; \ matrix_float3x3 ciModelMatrixInverseTranspose; \ matrix_float4x4 ciViewMatrix; \ matrix_float4x4 ciViewMatrixInverse; \ matrix_float4x4 ciModelView; \ matrix_float4x4 ciModelViewInverse; \ matrix_float3x3 ciModelViewInverseTranspose; \ matrix_float4x4 ciModelViewProjection; \ matrix_float4x4 ciModelViewProjectionInverse; \ matrix_float4x4 ciProjectionMatrix; \ matrix_float4x4 ciProjectionMatrixInverse; \ matrix_float4x4 ciViewProjection; \ matrix_float3x3 ciNormalMatrix; \ matrix_float4x4 ciNormalMatrix4x4; \ vector_float3 ciPositionOffset = {0,0,0}; \ vector_float3 ciPositionScale = {1,1,1}; \ vector_float2 ciTexCoordOffset = {0,0}; \ vector_float2 ciTexCoordScale = {1,1}; \ vector_int2 ciWindowSize; \ vector_float4 ciColor = {1,1,1,1}; \ float ciElapsedSeconds = 0.f; \ } ciUniforms_t; \ \ typedef struct Instance \ { \ float scale = 1.f; \ vector_float4 color = {1,1,1,1}; \ vector_float3 position = {0,0,0}; \ bool isTextured = false; \ int textureSlice = 0; \ vector_float4 texCoordRect = {0.f,0.f,1.f,1.f}; \ float floats[5] = {0.f,0.f,0.f,0.f,0.f}; \ int ints[5] = {0,0,0,0,0}; \ matrix_float4x4 modelMatrix = { \ (vector_float4){1,0,0,0}, \ (vector_float4){0,1,0,0}, \ (vector_float4){0,0,1,0}, \ (vector_float4){0,0,0,1} \ }; \ matrix_float4x4 normalMatrix = { \ (vector_float4){1,0,0,0}, \ (vector_float4){0,1,0,0}, \ (vector_float4){0,0,1,0}, \ (vector_float4){0,0,0,1} \ }; \ } Instance; \ \ typedef struct \ { \ vector_float4 position [[position]]; \ float pointSize [[point_size]]; \ vector_float3 normal; \ vector_float4 color; \ vector_float2 texCoords; \ int texIndex; \ } ciVertOut_t; \ \ } \ } #define ShaderUtils \ \ namespace cinder { \ namespace mtl { \ using namespace metal; \ inline vector_float3 rgb2hsv(vector_float3 c) \ { \ vector_float4 K = vector_float4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); \ vector_float4 p = c.g < c.b ? vector_float4(c.bg, K.wz) : vector_float4(c.gb, K.xy); \ vector_float4 q = c.r < p.x ? vector_float4(p.xyw, c.r) : vector_float4(c.r, p.yzx); \ float d = q.x - min(q.w, q.y); \ float e = 1.0e-10; \ return vector_float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); \ } \ \ inline vector_float3 hsv2rgb(float3 c) \ { \ vector_float4 K = vector_float4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); \ vector_float3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); \ return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); \ } \ \ inline matrix_float3x3 mat3( const matrix_float4x4 m ) \ { \ return matrix_float3x3((vector_float3){m[0][0], m[0][1], m[0][2]}, \ (vector_float3){m[1][0], m[1][1], m[1][2]}, \ (vector_float3){m[2][0], m[2][1], m[2][2]} ); \ } \ \ inline matrix_float4x4 rotationMatrix( const matrix_float4x4 m ) \ { \ return matrix_float4x4((vector_float4){m[0][0], m[0][1], m[0][2], 0}, \ (vector_float4){m[1][0], m[1][1], m[1][2], 0}, \ (vector_float4){m[2][0], m[2][1], m[2][2], 0}, \ (vector_float4){0, 0, 0, 1} ); \ } \ } \ }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/Library.h
// // Library.h // // Created by <NAME> on 1/13/16. // // #pragma once #include "cinder/Cinder.h" #include "MetalHelpers.hpp" #include "MetalEnums.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class Library> LibraryRef; class Library { public: // static Library::create( void * mtlLibrary ) // {}; // static Library::create( const std::string & libraryName ) // {}; // protected: void *mImpl; // <MTLLibrary> }; }}
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/RendererMetal.h
<filename>blocks/Cinder-Metal/include/RendererMetal.h<gh_stars>10-100 #pragma once #include "cinder/Cinder.h" #include "cinder/app/Renderer.h" #include "MetalEnums.h" #if defined( CINDER_COCOA ) //#include "CinderViewCocoaTouch+Metal.h" #if defined __OBJC__ @class RendererMetalImpl; #else class RendererMetalImpl; #endif #endif namespace cinder { namespace mtl { const static int DEFAULT_NUM_INFLIGHT_BUFFERS = 3; class CommandBuffer; } namespace app { typedef std::shared_ptr<class RendererMetal> RendererMetalRef; class RendererMetal : public Renderer { public: struct Options { public: Options() : mMaxInflightBuffers( mtl::DEFAULT_NUM_INFLIGHT_BUFFERS ) ,mFramebufferOnly(true) {} Options & numInflightBuffers( int numInflightBuffers ){ mMaxInflightBuffers = numInflightBuffers; return *this; }; const int getNumInflightBuffers() const { return mMaxInflightBuffers; } Options & framebufferOnly( bool framebufferOnly ){ mFramebufferOnly = framebufferOnly; return *this; }; const int getFramebufferOnly() const { return mFramebufferOnly; } Options & pixelFormat( mtl::PixelFormat format ){ mPixelFormat = format; return *this; }; const mtl::PixelFormat getPixelFormat() const { return mPixelFormat; } protected: int mMaxInflightBuffers; bool mFramebufferOnly; mtl::PixelFormat mPixelFormat = mtl::PixelFormatBGRA8Unorm; }; RendererMetal( const Options & options = Options() ); RendererRef clone() const override { return RendererMetalRef( new RendererMetal( *this ) ); } #if defined( CINDER_MAC ) void setup( CGRect frame, NSView *cinderView, RendererRef sharedRenderer, bool retinaEnabled ) override; #elif defined( CINDER_COCOA_TOUCH ) void setup( const Area &frame, UIView *cinderView, RendererRef sharedRenderer ) override; // NOTE: We're not technically an EAGL layer, but we can pretent to be for the same callback / loop behavior bool isEaglLayer() const override { return true; } #endif void setFrameSize( int width, int height ) override; const Options& getOptions() const { return mOptions; } Surface8u copyWindowSurface( const Area &area, int32_t windowHeightPixels ) override; void startDraw() override; void finishDraw() override; void makeCurrentContext( bool force = false ) override; int getNumInflightBuffers(){ return mOptions.getNumInflightBuffers(); }; protected: RendererMetalImpl *mImpl; Options mOptions; }; } // app }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/samples/Batch/include/SharedTypes.h
// // SharedTypes.h // Batch // // Created by <NAME> on 1/10/16. // // #pragma once #include <simd/simd.h> typedef struct { metal::packed_float4 ciPosition; metal::packed_float3 ciNormal; metal::packed_float2 ciTexCoord0; } CubeVertex;
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/samples/ARKit/src/NativeBridge.h
// // NativeBridge.h // CinderARKit // // Created by <NAME> on 7/6/17. // #import <Foundation/Foundation.h> #import <ARKit/ARKit.h> #import "CinderARKitApp.h" @interface NativeBridge : NSObject <ARSessionDelegate> { CinderARKitApp *_app; } - (instancetype)initWithApp:(CinderARKitApp *)app; - (void)handleTap:(UITapGestureRecognizer*)gestureRecognize; - (void)handleDoubleTap:(UITapGestureRecognizer*)gestureRecognize; - (void)handleSwipe:(UISwipeGestureRecognizer*)gestureRecognize; @end
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/ComputeEncoder.h
// // ComputeEncoder.hpp // // Created by <NAME> on 10/17/15. // // #pragma once #include "cinder/Cinder.h" #include "CommandEncoder.h" #include "ComputePipelineState.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class ComputeEncoder> ComputeEncoderRef; class ComputeEncoder : public CommandEncoder { public: // NOTE: // Generally ComputeEncoders should be created via the CommandBuffer // using CommandBuffer::createComputeEncoder. static ComputeEncoderRef create( void * mtlComputeCommandEncoder ); virtual ~ComputeEncoder(){}; virtual void setPipelineState( const ComputePipelineStateRef & pipeline ); virtual void setTexture( const TextureBufferRef & texture, size_t index = ciTextureIndex0 ); virtual void setUniforms( const DataBufferRef & buffer, size_t bytesOffset = 0, size_t bufferIndex = ciBufferIndexUniforms ); void setBufferAtIndex( const DataBufferRef & buffer, size_t bufferIndex , size_t bytesOffset = 0 ); void setBytesAtIndex( const void * bytes, size_t length, size_t index ); void setSamplerState( const SamplerStateRef & samplerState, int samplerIndex = 0 ); void setThreadgroupMemoryLength( size_t byteLength, size_t groupMemoryIndex ); void dispatch( ivec3 dataDimensions, ivec3 threadDimensions = ivec3(8,8,1) ); protected: ComputeEncoder( void * mtlComputeCommandEncoder ); }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/samples/VertexBuffer/include/SharedData.h
<filename>blocks/Cinder-Metal/samples/VertexBuffer/include/SharedData.h // // SharedData.h // Cinder-Metal // // Created by <NAME> on 12/5/15. // // #pragma once #include <simd/simd.h> typedef struct { metal::packed_float3 position; metal::packed_float3 normal; metal::packed_float2 texCoord0; } CubeVertex;
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/RenderPipelineState.h
<filename>blocks/Cinder-Metal/include/apple/RenderPipelineState.h // // Pipeline.hpp // // Created by <NAME> on 10/13/15. // // #pragma once #include "cinder/Cinder.h" #include "cinder/GeomIo.h" #include "MetalHelpers.hpp" #include "MetalEnums.h" #include "Argument.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class RenderPipelineState> RenderPipelineStateRef; class RenderPipelineState { public: struct Format { Format() : mSampleCount(1) ,mNumColorAttachments(1) ,mBlendingEnabled(false) ,mColorBlendOperation(BlendOperationAdd) ,mAlphaBlendOperation(BlendOperationAdd) ,mSrcColorBlendFactor(BlendFactorSourceAlpha) ,mSrcAlphaBlendFactor(BlendFactorSourceAlpha) ,mDstColorBlendFactor(BlendFactorOneMinusSourceAlpha) ,mDstAlphaBlendFactor(BlendFactorOneMinusSourceAlpha) ,mLabel("Default Pipeline") ,mColorPixelFormat(PixelFormatBGRA8Unorm) ,mDepthPixelFormat(PixelFormatDepth32Float) ,mStencilPixelFormat(PixelFormatInvalid) ,mPreprocessSource(true) {} public: Format& sampleCount( int sampleCount ) { setSampleCount( sampleCount ); return *this; }; void setSampleCount( int sampleCount ) { mSampleCount = sampleCount; }; int getSampleCount() const { return mSampleCount; }; Format& blendingEnabled( bool blendingEnabled = true ) { setBlendingEnabled( blendingEnabled ); return *this; }; void setBlendingEnabled( bool blendingEnabled ) { mBlendingEnabled = blendingEnabled; }; bool getBlendingEnabled() const { return mBlendingEnabled; }; Format& colorBlendOperation( BlendOperation colorBlendOperation ) { setColorBlendOperation( colorBlendOperation ); return *this; }; void setColorBlendOperation( BlendOperation colorBlendOperation ) { mColorBlendOperation = colorBlendOperation; }; BlendOperation getColorBlendOperation() const { return mColorBlendOperation; }; Format& alphaBlendOperation( BlendOperation alphaBlendOperation ) { setAlphaBlendOperation( alphaBlendOperation ); return *this; }; void setAlphaBlendOperation( BlendOperation alphaBlendOperation ) { mAlphaBlendOperation = alphaBlendOperation; }; BlendOperation getAlphaBlendOperation() const { return mAlphaBlendOperation; }; Format& srcColorBlendFactor( BlendFactor srcColorBlendFactor ) { setSrcColorBlendFactor( srcColorBlendFactor ); return *this; }; void setSrcColorBlendFactor( BlendFactor srcColorBlendFactor ) { mSrcColorBlendFactor = srcColorBlendFactor; }; BlendFactor getSrcColorBlendFactor() const { return mSrcColorBlendFactor; }; Format& srcAlphaBlendFactor( BlendFactor srcAlphaBlendFactor ) { setSrcAlphaBlendFactor( srcAlphaBlendFactor ); return *this; }; void setSrcAlphaBlendFactor( BlendFactor srcAlphaBlendFactor ) { mSrcAlphaBlendFactor = srcAlphaBlendFactor; }; BlendFactor getSrcAlphaBlendFactor() const { return mSrcAlphaBlendFactor; }; Format& dstColorBlendFactor( BlendFactor dstColorBlendFactor ) { setDstColorBlendFactor( dstColorBlendFactor ); return *this; }; void setDstColorBlendFactor( BlendFactor dstColorBlendFactor ) { mDstColorBlendFactor = dstColorBlendFactor; }; BlendFactor getDstColorBlendFactor() const { return mDstColorBlendFactor; }; Format& dstAlphaBlendFactor( BlendFactor dstAlphaBlendFactor ) { setDstAlphaBlendFactor( dstAlphaBlendFactor ); return *this; }; void setDstAlphaBlendFactor( BlendFactor dstAlphaBlendFactor ) { mDstAlphaBlendFactor = dstAlphaBlendFactor; }; BlendFactor getDstAlphaBlendFactor() const { return mDstAlphaBlendFactor; }; Format& preprocessSource( bool preprocessSource ) { setPreprocessSource( preprocessSource ); return *this; }; void setPreprocessSource( bool preprocessSource ) { mPreprocessSource = preprocessSource; }; bool getPreprocessSource() const { return mPreprocessSource; }; Format& label( std::string label ) { setLabel( label ); return *this; }; void setLabel( std::string label ) { mLabel = label; }; std::string getLabel() const { return mLabel; }; Format& colorPixelFormat( PixelFormat pixelFormat ) { setColorPixelFormat( pixelFormat ); return *this; }; void setColorPixelFormat( PixelFormat pixelFormat ) { mColorPixelFormat = pixelFormat; }; PixelFormat getColorPixelFormat() const { return mColorPixelFormat; }; Format& depthPixelFormat( PixelFormat pixelFormat ) { setDepthPixelFormat( pixelFormat ); return *this; }; void setDepthPixelFormat( PixelFormat pixelFormat ) { mDepthPixelFormat = pixelFormat; }; PixelFormat getDepthPixelFormat() const { return mDepthPixelFormat; }; Format& stencilPixelFormat( PixelFormat pixelFormat ) { setStencilPixelFormat( pixelFormat ); return *this; }; void setStencilPixelFormat( PixelFormat pixelFormat ) { mStencilPixelFormat = pixelFormat; }; PixelFormat getStencilPixelFormat() const { return mStencilPixelFormat; }; Format& numColorAttachments( int numAttachments ) { setNumColorAttachments( numAttachments ); return *this; }; void setNumColorAttachments( int numAttachments ) { mNumColorAttachments = numAttachments; }; int getNumColorAttachments() const { return mNumColorAttachments; }; protected: int mNumColorAttachments; int mSampleCount; bool mBlendingEnabled; BlendOperation mColorBlendOperation; BlendOperation mAlphaBlendOperation; BlendFactor mSrcColorBlendFactor; BlendFactor mSrcAlphaBlendFactor; BlendFactor mDstColorBlendFactor; BlendFactor mDstAlphaBlendFactor; std::string mLabel; PixelFormat mColorPixelFormat; PixelFormat mDepthPixelFormat; PixelFormat mStencilPixelFormat; bool mPreprocessSource; }; static RenderPipelineStateRef create( const std::string & vertShaderName, const std::string & fragShaderName, const Format & format = Format(), void * mtlLibrary = nullptr ) // native <MTLLibrary> { return RenderPipelineStateRef( new RenderPipelineState(vertShaderName, fragShaderName, format, mtlLibrary) ); } static RenderPipelineStateRef create( void * mtlRenderPipelineStateRef, void *mtlRenderPipelineReflection ) { return RenderPipelineStateRef( new RenderPipelineState(mtlRenderPipelineStateRef, mtlRenderPipelineReflection) ); } static RenderPipelineStateRef create( const std::string & librarySource, const std::string & vertName, const std::string & fragName, const mtl::RenderPipelineState::Format & format = mtl::RenderPipelineState::Format() ); virtual ~RenderPipelineState(); void * getNative(){ return mImpl; } void sampleLog(); //const std::vector<ci::geom::Attribute>& getActiveAttributes() const { return mAttributes; } const std::vector<ci::mtl::Argument> & getFragmentArguments(); const std::vector<ci::mtl::Argument> & getVertexArguments(); protected: RenderPipelineState( const std::string & vertShaderName, const std::string & fragShaderName, Format format, void * mtlLibrary ); RenderPipelineState( void * mtlRenderPipelineStateRef, void * mtlRenderPipelineReflection ); void * mImpl = NULL; // <MTLRenderPipelineState> void * mReflection = NULL; // <MTLRenderPipelineReflection> Format mFormat; std::vector<ci::mtl::Argument> mVertexArguments; std::vector<ci::mtl::Argument> mFragmentArguments; }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/DataBuffer.h
// // Buffer.hpp // // Created by <NAME> on 10/17/15. // // #pragma once #include "cinder/Cinder.h" #include "MetalHelpers.hpp" #include "MetalEnums.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class DataBuffer> DataBufferRef; class DataBuffer { public: struct Format { Format() : #if defined( CINDER_COCOA_TOUCH ) mStorageMode( StorageModeShared ) #else // NOTE: On OS X, programs run faster in "Shared" mode when using the integrated GPU, // and faster in "Managed" mode when using the descreet GPU. mStorageMode( StorageModeManaged ) #endif ,mCacheMode( CPUCacheModeDefaultCache ) ,mLabel("Default Data Buffer") ,mIsConstant(false) // used when measuring data allocation. Verts should be `false`, uniforms should be `true`. {}; public: Format& storageMode( StorageMode storageMode ) { setStorageMode( storageMode ); return *this; }; void setStorageMode( StorageMode storageMode ) { mStorageMode = storageMode; }; StorageMode getStorageMode() const { return mStorageMode; }; Format& cacheMode( CPUCacheMode cacheMode ) { setCacheMode( cacheMode ); return *this; }; void setCacheMode( CPUCacheMode cacheMode ) { mCacheMode = cacheMode; }; CPUCacheMode getCacheMode() const { return mCacheMode; }; Format& label( std::string label ) { setLabel( label ); return *this; }; void setLabel( std::string label ) { mLabel = label; }; std::string getLabel() const { return mLabel; }; Format& isConstant( bool isConstant = true ) { setIsConstant( isConstant ); return *this; }; void setIsConstant( bool isConstant ) { mIsConstant = isConstant; }; bool getIsConstant() const { return mIsConstant; }; protected: StorageMode mStorageMode; CPUCacheMode mCacheMode; std::string mLabel; bool mIsConstant; }; // Data stored at pointer will be copied into the buffer static DataBufferRef create( unsigned long length, const void * pointer, const Format & format = Format() ) { return DataBufferRef( new DataBuffer(length, pointer, format) ); } // Create with a native MTLBuffer static DataBufferRef create( void * mtlDataBuffer ) { return DataBufferRef( new DataBuffer( mtlDataBuffer ) ); } template <typename T> static DataBufferRef create( const std::vector<T> & dataVector, const Format & format = Format() ) { return DataBufferRef( new DataBuffer(dataVector, format) ); } virtual ~DataBuffer(); // A pointer to the data void * contents(); size_t getLength(); // Mark data changed. // NOTE: Only relevant to Managed storage on OS X void didModifyRange( size_t location, size_t length ); template <typename T> void update( const T * newData, const size_t lengthBytes, const size_t offsetBytes = 0 ) { uint8_t *bufferPointer = (uint8_t *)this->contents() + offsetBytes; memcpy( bufferPointer, newData, lengthBytes ); didModifyRange(offsetBytes, lengthBytes); } template <typename T> void update( const std::vector<T> & vectorData, const size_t offsetBytes = 0 ) { size_t length = sizeof(T) * vectorData.size(); if ( mFormat.getIsConstant() ) { length = mtlConstantBufferSize(length); } update(vectorData.data(), length, offsetBytes); } template <typename BufferObjectType> void setDataAtIndex( BufferObjectType *dataObject, int inflightBufferIndex ) { size_t dataSize = sizeof(BufferObjectType); if ( mFormat.getIsConstant() ) { dataSize = mtlConstantBufferSize(dataSize); } update( dataObject, dataSize, dataSize * inflightBufferIndex ); } void * getNative(){ return mImpl; } protected: DataBuffer( unsigned long length, const void * pointer, Format format ); DataBuffer( void *mtlDataBuffer ); void init( unsigned long length, const void * pointer, Format format ); template <typename T> DataBuffer( const std::vector<T> & dataVector, Format format ) { size_t dataSize = sizeof(T) * dataVector.size(); if ( format.getIsConstant() ) { dataSize = mtlConstantBufferSize(dataSize); } init(dataSize, dataVector.data(), format); } void * mImpl = NULL; // <MTLBuffer> Format mFormat; }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/DepthState.h
<gh_stars>10-100 // // DepthState.hpp // // Created by <NAME> on 11/7/15. // // #pragma once #include "cinder/Cinder.h" #include "MetalHelpers.hpp" #include "MetalEnums.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class DepthState> DepthStateRef; class DepthState { public: struct Format { Format() : mDepthCompareFunction(CompareFunctionLessEqual) ,mDepthWriteEnabled(false) ,mFrontFaceStencil(nullptr) ,mBackFaceStencil(nullptr) ,mLabel("Default Depth State") {} public: Format& depthCompareFunction( CompareFunction depthCompareFunction ) { setDepthCompareFunction( depthCompareFunction ); return *this; }; void setDepthCompareFunction( CompareFunction depthCompareFunction ) { mDepthCompareFunction = depthCompareFunction; }; CompareFunction getDepthCompareFunction() { return mDepthCompareFunction; }; Format& depthWriteEnabled( bool depthWriteEnabled = true ) { setDepthWriteEnabled( depthWriteEnabled ); return *this; }; void setDepthWriteEnabled( bool depthWriteEnabled ) { mDepthWriteEnabled = depthWriteEnabled; }; bool getDepthWriteEnabled() const { return mDepthWriteEnabled; }; // TODO: Maybe the back/front stencil descriptors don't belong in the format... Format& frontFaceStencil( void * frontFaceStencil ) { setFrontFaceStencil( frontFaceStencil ); return *this; }; void setFrontFaceStencil( void * frontFaceStencil ) { mFrontFaceStencil = frontFaceStencil; }; void * getFrontFaceStencil() const { return mFrontFaceStencil; }; Format& backFaceStencil( void * backFaceStencil ) { setBackFaceStencil( backFaceStencil ); return *this; }; void setBackFaceStencil( void * backFaceStencil ) { mBackFaceStencil = backFaceStencil; }; void * getBackFaceStencil() const { return mBackFaceStencil; }; Format& label( std::string label ) { setLabel( label ); return *this; }; void setLabel( std::string label ) { mLabel = label; }; std::string getLabel() const { return mLabel; }; protected: CompareFunction mDepthCompareFunction; bool mDepthWriteEnabled; void * mFrontFaceStencil; void * mBackFaceStencil; std::string mLabel; }; static DepthStateRef create( const Format & format = Format() ) { return DepthStateRef( new DepthState(format) ); } static DepthStateRef create( void *mtlDepthStencilState ) { return DepthStateRef( new DepthState(mtlDepthStencilState) ); } virtual ~DepthState(); void * getNative(){ return mImpl; } protected: DepthState( Format format ); DepthState( void *mtlDepthStencilState ); void * mImpl = NULL; // <MTLDepthStencilState> Format mFormat; }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/CommandBuffer.h
<reponame>iProfeten/cinder-metal-m1<filename>blocks/Cinder-Metal/include/apple/CommandBuffer.h // // CommandBuffer.hpp // // Created by <NAME> on 10/17/15. // // #pragma once #include "cinder/Cinder.h" #include "RenderEncoder.h" #include "ComputeEncoder.h" #include "BlitEncoder.h" #include "RenderPassDescriptor.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class CommandBuffer> CommandBufferRef; class CommandBuffer { public: static CommandBufferRef create( const std::string & bufferName ) { return CommandBufferRef( new CommandBuffer( bufferName ) ); } static CommandBufferRef create( void * mtlCommandBuffer ) { return CommandBufferRef( new CommandBuffer( mtlCommandBuffer ) ); } virtual ~CommandBuffer(); void addCompletionHandler( std::function< void( void * mtlCommandBuffer) > completionHandler ); void commit( std::function< void( void * mtlCommandBuffer) > completionHandler = NULL ); void waitUntilCompleted(); void * getNative(){ return mImpl; } virtual RenderEncoderRef createRenderEncoder( RenderPassDescriptorRef & descriptor, const std::string & encoderName = "Default Render Encoder" ); // Create a render encoder and apply the texture to the RenderPassDescriptor virtual RenderEncoderRef createRenderEncoder( RenderPassDescriptorRef & descriptor, void *drawableTexture, const std::string & encoderName = "Default Render Encoder" ); virtual ComputeEncoderRef createComputeEncoder( const std::string & encoderName = "Default Compute Encoder" ); virtual BlitEncoderRef createBlitEncoder( const std::string & encoderName = "Default Blit Encoder" ); protected: CommandBuffer( const std::string & bufferName ); CommandBuffer( void * mtlCommandBuffer ); void init( void * mtlCommandBuffer ); void * mImpl; // <MTLCommandBuffer> }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/CommandEncoder.h
<reponame>iProfeten/cinder-metal-m1 // // CommandEncoder.hpp // // Created by <NAME> on 11/12/15. // // #pragma once #include "cinder/Cinder.h" #include "MetalGeom.h" #include "DataBuffer.h" #include "TextureBuffer.h" #include "MetalConstants.h" #include "DepthState.h" #include "SamplerState.h" namespace cinder { namespace mtl { // Super class of ComputeEncoder, RenderEncoder and BlitEncoder class CommandEncoder { public: virtual ~CommandEncoder(); virtual void pushDebugGroup( const std::string & groupName ); virtual void popDebugGroup(); virtual void insertDebugSignpost( const std::string & name ); virtual void setTexture( const TextureBufferRef & texture, size_t index = ciTextureIndex0 ) = 0; virtual void setUniforms( const DataBufferRef & buffer, size_t bytesOffset = 0, size_t bufferIndex = ciBufferIndexUniforms ) = 0; virtual void endEncoding(); void * getNative(){ return mImpl; }; protected: CommandEncoder( void * mtlCommandEncoder ); void * mImpl = NULL; // <MTLRenderCommandEncoder> or <MTLComputeCommandEncoder> }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/samples/DepthOfField/include/SharedTypes.h
<gh_stars>10-100 // // SharedTypes.h // FoldingCube // // Created by <NAME> on 1/30/16. // // #pragma once // Add structs and types here that will be shared between your App and your Shaders #include <simd/simd.h> typedef struct { // float progress; } myUniforms_t; typedef struct TeapotInstance { vector_float3 position = {0,0,0}; vector_float3 axis = {0,0,0}; matrix_float4x4 modelMatrix = { (vector_float4){1,0,0,0}, (vector_float4){0,1,0,0}, (vector_float4){0,0,1,0}, (vector_float4){0,0,0,1} }; } TeapotInstance;
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/samples/ParticleSorting/include/SharedData.h
// // SharedData.h // ParticleSorting // // Created by <NAME> on 11/13/15. // // #pragma once #include "MetalConstants.h" #include <simd/simd.h> // Data shared by both the Cinder app and the Metal shader #define kParticleDimension 128 // Must be a power of 2 for the bitonic sort to work struct sortState_t { unsigned int direction = 1; // 1 == ascending, 0 == descending unsigned int stage = 0; unsigned int pass = 0; unsigned int passNum = 0; }; struct myUniforms_t { unsigned int numParticles = kParticleDimension * kParticleDimension; matrix_float4x4 modelMatrix; matrix_float4x4 modelViewProjectionMatrix; };
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/samples/TextureSlices/include/SharedTypes.h
<reponame>iProfeten/cinder-metal-m1 // // SharedTypes.h // FoldingCube // // Created by <NAME> on 1/30/16. // // #ifndef SharedTypes_h #define SharedTypes_h #include <simd/simd.h> #endif /* SharedTypes_h */
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/RendererMetalImpl.h
<reponame>iProfeten/cinder-metal-m1 // // RendererMetalImpl.h // // Created by <NAME> on 10/11/15. // // #pragma once #include <Metal/Metal.h> #include "RendererMetal.h" #include "CommandBuffer.h" #include "Context.h" // IMPORTANT: // Metal doesn't work in the iOS simulator. // If your build is failing here, try running on the device. #import <QuartzCore/CAMetalLayer.h> @interface RendererMetalImpl : NSObject { BOOL mLayerSizeDidUpdate; cinder::app::RendererMetal *mRenderer; #if defined( CINDER_MAC ) NSView *mCinderView; #elif defined( CINDER_COCOA_TOUCH ) UIView *mCinderView; #endif cinder::mtl::ContextRef mCinderContext; } @property (nonatomic, strong) id <MTLDevice> device; @property (nonatomic, strong) id <MTLCommandQueue> commandQueue; @property (nonatomic, strong) id <MTLLibrary> library; @property (nonatomic, strong) CAMetalLayer *metalLayer; @property (nonatomic, strong) id <CAMetalDrawable> currentDrawable; // Set by RenderCommandBuffer, when the command buffer is committed + (instancetype)sharedRenderer; #if defined( CINDER_MAC ) - (instancetype)initWithFrame:(CGRect)frame cinderView:(NSView *)cinderView renderer:(cinder::app::RendererMetal *)renderer options:(cinder::app::RendererMetal::Options &)options; #elif defined( CINDER_COCOA_TOUCH ) - (instancetype)initWithFrame:(CGRect)frame cinderView:(UIView *)cinderView renderer:(cinder::app::RendererMetal *)renderer options:(cinder::app::RendererMetal::Options &)options; #endif - (void)setFrameSize:(CGSize)newSize; - (void)startDraw; - (void)finishDraw; - (void)makeCurrentContext:(bool)force; - (dispatch_semaphore_t)inflightSemaphore; // Device support - (int)maxNumColorAttachments; @end
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/RenderCommandBuffer.h
// // RenderCommandBuffer.hpp // // Created by <NAME> on 11/15/15. // // #pragma once #include "cinder/Cinder.h" #include "CommandBuffer.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class RenderCommandBuffer> RenderCommandBufferRef; // NOTE: a RenderBuffer is just a CommandBuffer that // stores a reference to the device's "nextDrawable" and // presents it on commit. // It also synchronizes it's execution with the // shared inflight semaphore. class RenderCommandBuffer : public CommandBuffer { public: static RenderCommandBufferRef create( const std::string & bufferName ) { return RenderCommandBufferRef( new RenderCommandBuffer( bufferName ) ); } ~RenderCommandBuffer(); void commitAndPresent( std::function< void( void * mtlCommandBuffer) > completionHandler = NULL ); // Creates a render encoder for the main draw loop using the next "drawable". RenderEncoderRef createRenderEncoder( RenderPassDescriptorRef & renderDescriptor, const std::string & encoderName = "Default Render Encoder" ); virtual RenderEncoderRef createRenderEncoder( RenderPassDescriptorRef & descriptor, void *drawableTexture, const std::string & encoderName = "Default Render Encoder" ) { return CommandBuffer::createRenderEncoder(descriptor, drawableTexture, encoderName); } void * getDrawable(){ return mDrawable; } protected: RenderCommandBuffer( const std::string & bufferName ); void * mDrawable; // <CAMetalDrawable> }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/MetalGeom.h
<gh_stars>10-100 // // MetalGeom.h // // Created by <NAME> on 10/17/15. // // #pragma once #include "cinder/GeomIo.h" namespace cinder { namespace mtl { namespace geom { // NOTE: Metal uses "Line" and "Triangle", not the pluralized verions found in GL enum Primitive { POINT, LINE, LINE_STRIP, TRIANGLE, TRIANGLE_STRIP, NUM_PRIMITIVES }; // Converts ci::geom::Primitive into (ObjC) MTLPrimitiveType // Returns MTLPrimitiveType (must be cast) extern int nativeMTLPrimativeTypeFromGeom( const ci::geom::Primitive geomPrimitive ); // Converts ci::mtl::geom::Primitive into (ObjC) MTLPrimitiveType // Returns MTLPrimitiveType (must be cast) extern int nativeMTLPrimitiveType( const ci::mtl::geom::Primitive primitive ); // Converts ci::geom::Primitive into a mtl::geom::Primitive extern Primitive mtlPrimitiveTypeFromGeom( const ci::geom::Primitive primitive ); // Returns the shader index associated with a given attribute extern int defaultBufferIndexForAttribute( const ci::geom::Attrib attr ); } }}
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/MetalConstants.h
// // MetalConstants.h // // Created by <NAME> on 4/21/16. // // #pragma once #include "MetalMacros.h" // This is a macro. We've defined them this way so they can be rolled into // online shaders (which don't accept user includes). MetalConstants
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/TextureBuffer.h
// // TextureBuffer.hpp // // Created by <NAME> on 10/30/15. // // #pragma once #include "cinder/Cinder.h" #include "cinder/ImageIo.h" #include "MetalHelpers.hpp" #include "MetalEnums.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class TextureBuffer> TextureBufferRef; // http://metalbyexample.com/textures-and-samplers/ class TextureBuffer { friend class ImageSourceTextureBuffer; public: struct Format { Format() : mMipmapLevel(1) ,mSampleCount(1) ,mTextureType(TextureType2D) ,mPixelFormat(PixelFormatInvalid) ,mDepth(1) ,mArrayLength(1) ,mUsage(TextureUsageShaderRead) ,mFlipVertically(false) #if defined( CINDER_COCOA_TOUCH ) ,mStorageMode( StorageModeShared ) #else // NOTE: On OS X, programs run faster in "Shared" mode when using the integrated GPU, // and faster in "Managed" mode when using the descreet GPU. ,mStorageMode( StorageModeManaged ) #endif ,mCacheMode( CPUCacheModeDefaultCache ) {}; public: Format& mipmapLevel( int mipmapLevel ) { setMipmapLevel( mipmapLevel ); return *this; }; void setMipmapLevel( int mipmapLevel ) { mMipmapLevel = mipmapLevel; }; int getMipmapLevel() const { return mMipmapLevel; }; Format& sampleCount( int sampleCount ) { setSampleCount( sampleCount ); return *this; }; void setSampleCount( int sampleCount ) { mSampleCount = sampleCount; }; int getSampleCount() const { return mSampleCount; }; Format& textureType( TextureType textureType ) { setTextureType( textureType ); return *this; }; void setTextureType( TextureType textureType ) { mTextureType = textureType; }; TextureType getTextureType() const { return mTextureType; }; Format& pixelFormat( PixelFormat pixelFormat ) { setPixelFormat( pixelFormat ); return *this; }; void setPixelFormat( PixelFormat pixelFormat ) { mPixelFormat = pixelFormat; }; PixelFormat getPixelFormat() const { return mPixelFormat; }; Format& flipVertically( bool flipVertically = true ) { setFlipVertically( flipVertically ); return *this; }; void setFlipVertically( bool flipVertically ) { mFlipVertically = flipVertically; }; bool getFlipVertically() const { return mFlipVertically; }; Format& depth( int depth ) { setDepth( depth ); return *this; }; void setDepth( int depth ) { mDepth = depth; }; int getDepth() const { return mDepth; }; Format& arrayLength( int arrayLength ) { setArrayLength( arrayLength ); return *this; }; void setArrayLength( int arrayLength ) { mArrayLength = arrayLength; }; int getArrayLength() const { return mArrayLength; }; Format& usage( TextureUsage usage ) { setUsage( usage ); return *this; }; void setUsage( TextureUsage usage ) { mUsage = usage; }; TextureUsage getUsage() const { return mUsage; }; Format& storageMode( StorageMode storageMode ) { setStorageMode( storageMode ); return *this; }; void setStorageMode( StorageMode storageMode ) { mStorageMode = storageMode; }; StorageMode getStorageMode() const { return mStorageMode; }; Format& cacheMode( CPUCacheMode cacheMode ) { setCacheMode( cacheMode ); return *this; }; void setCacheMode( CPUCacheMode cacheMode ) { mCacheMode = cacheMode; }; CPUCacheMode getCacheMode() const { return mCacheMode; }; protected: int mMipmapLevel; int mSampleCount; TextureType mTextureType; PixelFormat mPixelFormat; int mDepth; int mArrayLength; TextureUsage mUsage; bool mFlipVertically; StorageMode mStorageMode; CPUCacheMode mCacheMode; }; static TextureBufferRef create( const ImageSourceRef & imageSource, const Format & format = Format() ) { return TextureBufferRef( new TextureBuffer( imageSource, format ) ); } static TextureBufferRef create( uint width, uint height, const Format & format = Format() ) { return TextureBufferRef( new TextureBuffer( width, height, format ) ); } static TextureBufferRef create( void * mtlTexture ) { return TextureBufferRef( new TextureBuffer( mtlTexture ) ); } // What's the right way to handle copy? TextureBufferRef clone(); virtual ~TextureBuffer(); void update( const ImageSourceRef & imageSource, unsigned int slice = 0, unsigned int mipmapLevel = 0 ); void update( void * mtlTexture ); void updateWithCGImage( void *, bool flipVertically, unsigned int slice = 0, unsigned int mipmapLevel = 0 ); // Getting & Setting Data for 2D images void setPixelData( const void *pixelBytes, unsigned int slice = 0, unsigned int mipmapLevel = 0 ); void getPixelData( void *pixelBytes, unsigned int slice = 0, unsigned int mipmapLevel = 0 ); void getPixelData( void *pixelBytes, const ivec2 & origin, const ivec2 & size, unsigned int slice = 0, unsigned int mipmapLevel = 0); ci::ImageSourceRef createSource( int slice = 0, int mipmapLevel = 0 ); // Accessors Format getFormat() const; long getWidth() const; long getHeight() const; long getDepth() const; ci::ivec2 getSize() const { return ivec2( getWidth(), getHeight() ); } long getMipmapLevelCount(); long getSampleCount(); long getArrayLength(); bool getFramebufferOnly(); TextureUsage getUsage(); // <MTLTextureUsage> void getBytes( void * pixelBytes, const ivec3 regionOrigin, const ivec3 regionSize, uint bytesPerRow, uint bytesPerImage, uint mipmapLevel = 0, uint slice = 0); void replaceRegion( const ivec3 regionOrigin, const ivec3 regionSize, const void * newBytes, uint bytesPerRow, uint bytesPerImage, uint mipmapLevel = 0, uint slice = 0 ); void replaceRegion(const ivec2 regionOrigin, const ivec2 regionSize, const void * newBytes, uint bytesPerRow, uint mipmapLevel = 0); TextureBufferRef newTexture( PixelFormat pixelFormat, TextureType type, uint levelOffset = 0, uint levelLength = 1, uint sliceOffset = 0, uint sliceLength = 1 ); void * getNative(){ return mImpl; }; protected: TextureBuffer( const ImageSourceRef & imageSource, Format format ); TextureBuffer( uint width, uint height, Format format ); TextureBuffer( void * mtlTexture ); void generateMipmap(); void *mImpl = NULL; // <MTLTexture> long mBytesPerRow; Format mFormat; ImageIo::DataType mDataType; }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/CinderMetalCocoa.h
<gh_stars>10-100 // // CinderMetalCocoa.h // // Created by <NAME> on 3/3/17. // // #pragma once #ifdef CINDER_COCOA_TOUCH #import <UIKit/UIKit.h> #endif #import <Metal/Metal.h> #include "cinder/Cinder.h" #include "metal.h" namespace cinder { namespace cocoa { CGImageRef convertMTLTexture(id <MTLTexture> texture); #ifdef CINDER_COCOA_TOUCH UIImage * convertTexture(ci::mtl::TextureBufferRef & texture); #else #ifdef CINDER_COCOA NSImage * convertTexture(ci::mtl::TextureBufferRef & texture); #endif #endif }}
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/MovieMetal.h
// // MovieMetal.h // VideoMetalTexture // // Created by <NAME> on 7/11/17. // #pragma once #include "cinder/Cinder.h" // TODO: Update with OS X support #ifdef CINDER_COCOA_TOUCH #include "metal.h" #include <memory> @class MovieMetalImpl; namespace cinder { namespace mtl { typedef std::shared_ptr<class MovieMetal> MovieMetalRef; class MovieMetal { public: struct Options { Options() : mLoops(false) {} public: Options & loops( bool shouldLoop ) { setLoops( shouldLoop ); return *this; }; void setLoops( bool shouldLoop ) { mLoops = shouldLoop; }; bool getLoops() const { return mLoops; }; protected: bool mLoops; }; static MovieMetalRef create( const ci::fs::path & movieURL, Options options = Options() ) { return MovieMetalRef(new MovieMetal(movieURL, options)); } void play( bool seekToZero = false ); void pause(); void seekToTime(double secondsOffset); void setPlaybackCompleteHandler( std::function<void (MovieMetal *)> handler ) { mPlaybackCompleteHandler = handler; } double getDuration(); void setRate(float rate); float getRate(); const Options & getOptions() { return mOptions; } TextureBufferRef & getTextureLuma(); TextureBufferRef & getTextureChroma(); protected: MovieMetal( const ci::fs::path & movieURL, Options options ); MovieMetalImpl *mVideoDelegate; bool mLoops; Options mOptions; std::function<void (MovieMetal *)> mPlaybackCompleteHandler; }; }} #endif
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/ComputePipelineState.h
// // ComputePipelineState.hpp // // Created by <NAME> on 11/13/15. // // #pragma once #include "cinder/Cinder.h" #include "MetalHelpers.hpp" namespace cinder { namespace mtl { typedef std::shared_ptr<class ComputePipelineState> ComputePipelineStateRef; class ComputePipelineState { public: static ComputePipelineStateRef create( const std::string & computeShaderName, void * mtlLibrary = nullptr) // native <MTLLibrary> { return ComputePipelineStateRef( new ComputePipelineState( computeShaderName, mtlLibrary ) ); } static ComputePipelineStateRef create( void * mtlComputePipelineState ) { return ComputePipelineStateRef( new ComputePipelineState(mtlComputePipelineState) ); } virtual ~ComputePipelineState(); void * getNative(){ return mImpl; } protected: ComputePipelineState( const std::string & computeShaderName, void * mtlLibrary = nullptr ); ComputePipelineState( void * mtlComputePipelineState ); void * mImpl = NULL; // <MTLComputePipelineState> }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/Batch.h
<reponame>iProfeten/cinder-metal-m1 // // Batch.hpp // // Created by <NAME> on 1/10/16. // // #pragma once #include "cinder/Cinder.h" #include "cinder/GeomIo.h" #include "MetalGeom.h" #include "DataBuffer.h" #include "RenderEncoder.h" #include "VertexBuffer.h" #include "apple/RenderPipelineState.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class Batch> BatchRef; /* Batch infers attribute mapping by name. If you use the names found in src/Batch.cpp for your custom structs, the Batch class will know where to put the data. e.g.: typedef struct { metal::packed_float3 ciPosition; metal::packed_float3 ciNormal; metal::packed_float2 ciTexCoord0; metal::packed_float4 ciColor; } MyVertex; Batch will inspect your vertex function and look for parameters with pre-defined names and buffer indices. ciVerts: The vertex data populated by a Batch. Should use buffer index ciBufferIndexInterleavedVerts. ciUniforms: The uniforms passed in by the context. Should be located at ciBufferIndexUniforms. */ class Batch { public: //! Maps a geom::Attrib to a named attribute in the Pipeline typedef std::map<ci::geom::Attrib,std::string> AttributeMapping; //! Builds a Batch from a VboMesh and a Pipeline. Attributes defined in \a attributeMapping override the default mapping between AttributeSemantics and Pipeline attribute names static BatchRef create( const VertexBufferRef & vertexBuffer, const RenderPipelineStateRef & renderPipeline, const AttributeMapping &attributeMapping = AttributeMapping() ) { return BatchRef(new Batch(vertexBuffer, renderPipeline, attributeMapping)); } //! Builds a Batch from a geom::Source and a Pipeline. Attributes defined in \a attributeMapping override the default mapping static BatchRef create( const ci::geom::Source &source, const RenderPipelineStateRef & renderPipeline, const AttributeMapping &attributeMapping = AttributeMapping() ) { return BatchRef(new Batch(source, renderPipeline, attributeMapping)); } void draw( RenderEncoder & renderEncoder ); void drawInstanced( RenderEncoder & renderEncoder, size_t instanceCount ); void draw( RenderEncoder & renderEncoder, size_t vertexStart, size_t vertexLength, size_t instanceCount = 1 ); //! Returns OpenGL primitive type (GL_TRIANGLES, GL_TRIANGLE_STRIP, etc) ci::mtl::geom::Primitive getPrimitive(){ return mVertexBuffer->getPrimitive(); }; //! Returns the total number of vertices in the associated geometry size_t getNumVertices() const { return mVertexBuffer->getNumVertices(); } //! Returns the number of element indices in the associated geometry; 0 for non-indexed geometry size_t getNumIndices() const { return mVertexBuffer->getNumIndices(); } //! Returns the data type for indices; GL_UNSIGNED_INT or GL_UNSIGNED_SHORT // GLenum getIndexDataType() const { return mVboMesh->getIndexDataType(); } //! Returns the shader pipeline associated with the Batch const RenderPipelineStateRef& getPipeline() const { return mRenderPipeline; } //! Replaces the shader pipeline associated with the Batch. void replacePipeline( const RenderPipelineStateRef& pipeline ); //! Returns the VertexBuffer associated with the Batch VertexBufferRef getVertexBuffer() const { return mVertexBuffer; }; //! Replaces the VertexBuffer associated with the Batch. void replaceVertexBuffer( const VertexBufferRef &vertexBuffer ); protected: Batch( const VertexBufferRef & vertexBuffer, const RenderPipelineStateRef & pipeline, const AttributeMapping &attributeMapping ); Batch( const ci::geom::Source &source, const RenderPipelineStateRef &pipeline, const AttributeMapping &attributeMapping ); void initBufferLayout( const AttributeMapping &attributeMapping = AttributeMapping() ); void checkBufferLayout(); VertexBufferRef mVertexBuffer; RenderPipelineStateRef mRenderPipeline; AttributeMapping mAttribMapping; ci::geom::BufferLayout mInterleavedLayout; std::map<ci::geom::Attrib, unsigned long> mAttribBufferIndices; //unsigned long mIndicesBufferIndex = ciBufferIndexIndices; }; }}
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/Draw.h
<reponame>iProfeten/cinder-metal-m1 // // Draw.h // // Created by <NAME> on 2/23/16. // // #pragma once #include "cinder/Cinder.h" #include "VertexBuffer.h" #include "RenderPipelineState.h" #include "Context.h" #include "cinder/app/App.h" #include "cinder/CameraUi.h" #include "cinder/GeomIo.h" #include "metal.h" #include "Batch.h" #include "ShaderTypes.h" namespace cinder { namespace mtl { #pragma mark - Generic Batches ci::mtl::BatchRef getStockBatchWireCube(); ci::mtl::BatchRef getStockBatchWireCircle(); ci::mtl::BatchRef getStockBatchWireRect(); ci::mtl::BatchRef getStockBatchTexturedRect( bool isCentered = true ); ci::mtl::BatchRef getStockBatchMultiTexturedRect( bool isCentered = true ); ci::mtl::BatchRef getStockBatchBillboard(); ci::mtl::BatchRef getStockBatchMultiBillboard(); ci::mtl::BatchRef getStockBatchSolidRect(); ci::mtl::BatchRef getStockBatchSphere(); ci::mtl::BatchRef getStockBatchCube(); ci::mtl::BatchRef getStockBatchColoredCube(); ci::mtl::BatchRef getStockBatchPlane(); // NOTE: Ring can be a circle by passing in an inner radius of 0 ci::mtl::BatchRef getStockBatchRing(); ci::mtl::BatchRef getStockBatchBillboardRing(); ci::mtl::VertexBufferRef getRingBuffer(); }}
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/Scope.h
<reponame>iProfeten/cinder-metal-m1 // // Scope.hpp // // Created by <NAME> on 11/4/15. // // #pragma once #include "cinder/Cinder.h" #include "cinder/Noncopyable.h" #include "CommandBuffer.h" #include "RenderCommandBuffer.h" #include "Context.h" namespace cinder { namespace mtl { class ScopedRenderEncoder : public RenderEncoder { friend class ScopedRenderCommandBuffer; friend class ScopedCommandBuffer; public: ~ScopedRenderEncoder(); private: ScopedRenderEncoder( void * mtlRenderCommandEncoder ); Context *mCtx; }; class ScopedComputeEncoder : public ComputeEncoder { friend class ScopedCommandBuffer; friend class ScopedRenderCommandBuffer; public: ~ScopedComputeEncoder(); private: ScopedComputeEncoder( void * mtlComputeEncoder ); }; class ScopedBlitEncoder : public BlitEncoder { friend class ScopedCommandBuffer; friend class ScopedRenderCommandBuffer; public: ~ScopedBlitEncoder(); private: ScopedBlitEncoder( void * mtlBlitEncoder ); }; class ScopedCommandBuffer : public CommandBuffer { public: ScopedCommandBuffer( bool waitUntilCompleted = false, const std::string & bufferName = "Scoped Command Buffer" ); ~ScopedCommandBuffer(); void addCompletionHandler( std::function< void( void * mtlCommandBuffer) > handler ){ mCompletionHandler = handler; } ScopedComputeEncoder scopedComputeEncoder( const std::string & bufferName = "Scoped Compute Encoder" ); ScopedBlitEncoder scopedBlitEncoder( const std::string & bufferName = "Scoped Blit Encoder" ); ScopedRenderEncoder scopedRenderEncoder( RenderPassDescriptorRef & descriptor, mtl::TextureBufferRef & drawableTexture, const std::string & bufferName = "Scoped Render Encoder" ); ScopedRenderEncoder scopedRenderEncoder( RenderPassDescriptorRef & descriptorWithDrawableAttachments, const std::string & bufferName = "Scoped Render Encoder" ); private: bool mWaitUntilCompleted; std::function< void( void * mtlCommandBuffer) > mCompletionHandler; }; class ScopedRenderCommandBuffer : public RenderCommandBuffer { public: ScopedRenderCommandBuffer( bool waitUntilCompleted = false, const std::string & bufferName = "Scoped Render Buffer" ); ~ScopedRenderCommandBuffer(); void addCompletionHandler( std::function< void( void * mtlCommandBuffer) > handler ){ mCompletionHandler = handler; } ScopedComputeEncoder scopedComputeEncoder( const std::string & bufferName = "Scoped Compute Encoder" ); ScopedBlitEncoder scopedBlitEncoder( const std::string & bufferName = "Scoped Blit Encoder" ); ScopedRenderEncoder scopedRenderEncoder( RenderPassDescriptorRef & descriptor, const std::string & bufferName = "Scoped Render Encoder" ); private: bool mWaitUntilCompleted; std::function< void( void * mtlCommandBuffer) > mCompletionHandler; }; // Context Scopes struct ScopedModelMatrix : private Noncopyable { ScopedModelMatrix() { pushModelMatrix(); } ~ScopedModelMatrix() { popModelMatrix(); } }; struct ScopedViewMatrix : private Noncopyable { ScopedViewMatrix() { pushViewMatrix(); } ~ScopedViewMatrix() { popViewMatrix(); } }; struct ScopedProjectionMatrix : private Noncopyable { ScopedProjectionMatrix() { pushProjectionMatrix(); } ~ScopedProjectionMatrix() { popProjectionMatrix(); } }; //! Preserves all matrices struct ScopedMatrices : private Noncopyable { ScopedMatrices() { pushMatrices(); } ~ScopedMatrices() { popMatrices(); } }; struct ScopedColor : private Noncopyable { ScopedColor(); ScopedColor( const ColorAf &color ); ScopedColor( float red, float green, float blue, float alpha = 1 ); ~ScopedColor(); private: Context *mCtx; ColorAf mColor; }; }}
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/VertexBuffer.h
// // GeomTarget.hpp // // Created by <NAME> on 10/24/15. // // #pragma once #include "cinder/Cinder.h" #include "cinder/GeomIo.h" #include "MetalGeom.h" #include "DataBuffer.h" #include "RenderEncoder.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class VertexBuffer> VertexBufferRef; class VertexBuffer : public ci::geom::Target { public: // Create a VertexBuffer with interleaved data. Optionally pass in indices if the data is indexed. static VertexBufferRef create( uint32_t numVertices, const DataBufferRef interleavedData, const DataBufferRef bufferedIndices = DataBufferRef(), const ci::mtl::geom::Primitive primitive = ci::mtl::geom::TRIANGLE ); static VertexBufferRef create( uint32_t numVertices, const ci::mtl::geom::Primitive primitive = ci::mtl::geom::TRIANGLE ); static VertexBufferRef create( const ci::geom::Source & source, const std::vector<ci::geom::Attrib> & orderedAttribs = {{}}, const DataBuffer::Format & format = DataBuffer::Format() .label("Verts") ); // The DataBuffer::Format will be used to create the index and interleaved data buffers. static VertexBufferRef create( const ci::geom::Source & source, const ci::geom::BufferLayout & layout, const DataBuffer::Format & format = DataBuffer::Format() .label("Verts") ); virtual ~VertexBuffer(){} ci::mtl::geom::Primitive getPrimitive(){ return mPrimitive; }; void setPrimitive( const ci::mtl::geom::Primitive primitive ){ mPrimitive = primitive; }; // Set shaderBufferIndex to something > -1 if you wish to update / assign the shader index for this attribute void setBufferForAttribute( DataBufferRef buffer, const ci::geom::Attrib attr, int shaderBufferIndex = -1 ); DataBufferRef getBufferForAttribute( const ci::geom::Attrib attr ); void setInterleavedBuffer( DataBufferRef buffer ){ mInterleavedData = buffer; }; DataBufferRef getInterleavedBuffer(){ return mInterleavedData; }; void setIndexBuffer( DataBufferRef buffer ){ mIndexBuffer = buffer; }; DataBufferRef getIndexBuffer(){ return mIndexBuffer; }; // Override the default shader indices. // The default geom::Attr shader indices are defined in MetalConstants.h void setAttributeBufferIndex( const ci::geom::Attrib attr, unsigned long shaderBufferIndex ); // Returns -1 if the attr doesnt have an index unsigned long getAttributeBufferIndex( const ci::geom::Attrib attr ); // void setIndicesBufferIndex( unsigned long shaderBufferIndex ){ mBufferIndexIndices = shaderBufferIndex; }; // unsigned long getIndicesBufferIndex(){ return mBufferIndexIndices; }; template<typename T> void update( ci::geom::Attrib attr, std::vector<T> vectorData ) { getBufferForAttribute(attr)->update(vectorData); } bool getIsInterleaved(){ return mIsInterleaved; }; size_t getNumVertices(){ return mVertexLength; }; size_t getNumIndices(){ return mIndexLength; }; void draw( RenderEncoder & renderEncoder ); void drawInstanced( RenderEncoder & renderEncoder, size_t instanceCount ); void draw( RenderEncoder & renderEncoder, size_t vertexLength, size_t vertexStart = 0, size_t instanceCount = 1 ); protected: VertexBuffer( uint32_t numVertices, const DataBufferRef interleavedData, const DataBufferRef bufferedIndices, const ci::mtl::geom::Primitive primitive); VertexBuffer( const ci::geom::Source & source, const ci::geom::BufferLayout & layout, DataBuffer::Format format ); VertexBuffer( uint32_t numVertices, const ci::mtl::geom::Primitive primitive ); // geom::Target subclass void copyAttrib( ci::geom::Attrib attr, uint8_t dims, size_t strideBytes, const float *srcData, size_t count ); void copyIndices( ci::geom::Primitive primitive, const uint32_t *source, size_t numIndices, uint8_t requiredBytesPerIndex ); uint8_t getAttribDims( ci::geom::Attrib attr ) const; void createDefaultIndices(); ci::mtl::geom::Primitive mPrimitive; std::map<ci::geom::Attrib, DataBufferRef> mAttributeBuffers; std::map<ci::geom::Attrib, unsigned long> mAttributeBufferIndices; ci::geom::SourceRef mSource; size_t mVertexLength; size_t mIndexLength; // unsigned long mBufferIndexIndices = ciBufferIndexIndices; // default ci::geom::BufferLayout mBufferLayout; DataBufferRef mInterleavedData; DataBufferRef mIndexBuffer; bool mIsInterleaved; }; }}
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/RenderEncoder.h
<filename>blocks/Cinder-Metal/include/apple/RenderEncoder.h // // RenderEncoder.hpp // // Created by <NAME> on 10/16/15. // // #pragma once #include "cinder/Cinder.h" #include "MetalGeom.h" #include "RenderPipelineState.h" #include "DataBuffer.h" #include "TextureBuffer.h" #include "DepthState.h" #include "SamplerState.h" #include "MetalConstants.h" #include "CommandEncoder.h" #include "MetalEnums.h" namespace cinder { namespace mtl { class Instance; typedef std::shared_ptr<class RenderEncoder> RenderEncoderRef; class VertexBuffer; typedef std::shared_ptr<VertexBuffer> VertexBufferRef; class Batch; typedef std::shared_ptr<Batch> BatchRef; class RenderEncoder : public CommandEncoder { public: // NOTE: // Generally RenderEncoders should be created via the RenderCommandBuffer or CommandBuffer // using RenderCommandBuffer::createRenderEncoder. static RenderEncoderRef create( void * mtlRenderCommandEncoder ); // <MTLRenderCommandEncoder> virtual ~RenderEncoder(){}; virtual void setPipelineState( const RenderPipelineStateRef & pipeline ); // NOTE: setTexture is an alias for setFragmentTextureAtIndex virtual void setTexture( const TextureBufferRef & texture, size_t index = ciTextureIndex0 ); virtual void setFragmentTexture( const TextureBufferRef & texture, size_t index ); virtual void setVertexTexture( const TextureBufferRef & texture, size_t index ); // Sets buffer at ciBufferIndexUniforms for both vertex and fragment shaders virtual void setUniforms( const DataBufferRef & buffer, size_t bytesOffset = 0, size_t bufferIndex = ciBufferIndexUniforms ); void setVertexBufferAtIndex( const DataBufferRef & buffer, size_t bufferIndex , size_t bytesOffset = 0 ); void setFragmentBufferAtIndex( const DataBufferRef & buffer, size_t bufferIndex , size_t bytesOffset = 0 ); void setVertexBytesAtIndex( const void * bytes, size_t length , size_t index ); void setFragmentBytesAtIndex( const void * bytes, size_t length , size_t index ); // Pass in single POD values to a shader param index template <typename T> void setVertexValueAtIndex( const T * bytes, size_t index ) { setVertexBytesAtIndex( bytes, sizeof(T), index ); } template <typename T> void setFragmentValueAtIndex( const T * bytes, size_t index ) { setFragmentBytesAtIndex( bytes, sizeof(T), index ); } void setFragSamplerState( const SamplerStateRef & samplerState, int samplerIndex = 0 ); void setDepthStencilState( const DepthStateRef & depthState ); void setViewport( vec2 origin, vec2 size, float near = 0.0, float far = 1.f ); void setFrontFacingWinding( bool isClockwise ); void setCullMode( int mtlCullMode ); #if !defined( CINDER_COCOA_TOUCH ) void setDepthClipMode( int mtlDepthClipMode ); #endif void setDepthBias( float depthBias, float slopeScale, float clamp ); void setScissor( Area scissor ); void setTriangleFillMode( int mtlTriangleFillMode ); void setVertexBufferOffsetAtIndex( size_t offset, size_t index ); void setFragmentBufferOffsetAtIndex( size_t offset, size_t index ); void setBlendColor( ColorAf blendColor ); void setStencilReferenceValue( uint32_t frontReferenceValue, uint32_t backReferenceValue ); void setVisibilityResultMode( int mtlVisibilityResultMode, size_t offset ); void draw( ci::mtl::geom::Primitive primitive, size_t vertexCount, size_t vertexStart = 0, size_t instanceCount = 1, size_t baseInstance = 0 ); void drawIndexed( ci::mtl::geom::Primitive primitive, const DataBufferRef & indexBuffer, size_t indexCount, size_t instanceCount = 1, size_t bufferOffset = 0, IndexType indexType = IndexTypeUInt32, size_t baseVertex = 0, size_t baseInstance = 0 ); #if !defined( CINDER_COCOA_TOUCH ) void textureBarrier(); #endif // Convenience functions for setting encoder state void operator<<( mtl::DepthStateRef & depthState ) { setDepthStencilState(depthState); } void operator<<( mtl::SamplerStateRef & samplerState ) { setFragSamplerState(samplerState); } void operator<<( mtl::RenderPipelineStateRef & renderPipeline ) { setPipelineState(renderPipeline); } #pragma mark - Drawing Convenience Functions // Drawing helpers void draw( ci::mtl::VertexBufferRef vertBuffer, ci::mtl::RenderPipelineStateRef pipeline, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void draw( ci::mtl::BatchRef batch, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void draw( ci::mtl::BatchRef batch, size_t vertexLength, size_t vertexStart, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawOne( ci::mtl::BatchRef batch, const ci::mtl::Instance & i); void drawStrokedCircle( ci::vec3 position, float radius, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawSolidCircle( ci::vec3 position, float radius, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawBillboardCircle( ci::vec3 position, float radius, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawRing( ci::vec3 position, float outerRadius, float innerRadius, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawStrokedRect( ci::Rectf rect, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawSolidRect( ci::Rectf rect, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawCube( ci::vec3 position, ci::vec3 size, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawStrokedCube( ci::vec3 position, ci::vec3 size, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawSphere( ci::vec3 position, float radius, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); // NOTE: This is not designed to be fast—just convenient void drawLines( std::vector<ci::vec3> lines, bool isLineStrip = false, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); // NOTE: This is not designed to be fast—just convenient void drawLine( ci::vec3 from, ci::vec3 to, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawColoredCube( ci::vec3 position, ci::vec3 size, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void draw( ci::mtl::TextureBufferRef & texture, ci::Rectf rect = ci::Rectf(0,0,0,0), ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); void drawBillboard( mtl::TextureBufferRef & texture, ci::mtl::DataBufferRef instanceBuffer = ci::mtl::DataBufferRef(), unsigned int numInstances = 1 ); // Instance data void setIdentityInstance(); void setInstanceData( ci::mtl::DataBufferRef & instanceBuffer ); // Basic state changes void enableDepth(); void disableDepth(); protected: RenderEncoder( void * mtlRenderCommandEncoder ); }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/SamplerState.h
<filename>blocks/Cinder-Metal/include/apple/SamplerState.h<gh_stars>10-100 // // SamplerState.hpp // // Created by <NAME> on 11/7/15. // // #pragma once #include "cinder/Cinder.h" #include "MetalHelpers.hpp" #include "MetalEnums.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class SamplerState> SamplerStateRef; class SamplerState { public: struct Format { Format() : mMipFilter(SamplerMipFilterLinear) ,mMaxAnisotropy(3) ,mMinFilter(SamplerMinMagFilterLinear) ,mMagFilter(SamplerMinMagFilterLinear) ,mSAddressMode(SamplerAddressModeClampToEdge) ,mTAddressMode(SamplerAddressModeClampToEdge) ,mRAddressMode(SamplerAddressModeClampToEdge) ,mNormalizedCoordinates(true) ,mLodMinClamp(0.f) ,mLodMaxClamp(FLT_MAX) #if defined( CINDER_COCOA_TOUCH ) ,mLodAverage(false) #endif ,mCompareFunction(CompareFunctionNever) ,mLabel("Default Sampler State") {} public: Format& mipFilter( SamplerMipFilter mipFilter ) { setMipFilter( mipFilter ); return *this; }; void setMipFilter( SamplerMipFilter mipFilter ) { mMipFilter = mipFilter; }; SamplerMipFilter getMipFilter() const { return mMipFilter; }; Format& maxAnisotropy( int maxAnisotropy ) { setMaxAnisotropy( maxAnisotropy ); return *this; }; void setMaxAnisotropy( int maxAnisotropy ) { mMaxAnisotropy = maxAnisotropy; }; int getMaxAnisotropy() const { return mMaxAnisotropy; }; Format& minFilter( SamplerMinMagFilter minFilter ) { setMinFilter( minFilter ); return *this; }; void setMinFilter( SamplerMinMagFilter minFilter ) { mMinFilter = minFilter; }; SamplerMinMagFilter getMinFilter() const { return mMinFilter; }; Format& magFilter( SamplerMinMagFilter magFilter ) { setMagFilter( magFilter ); return *this; }; void setMagFilter( SamplerMinMagFilter magFilter ) { mMagFilter = magFilter; }; SamplerMinMagFilter getMagFilter() const { return mMagFilter; }; Format& sAddressMode( SamplerAddressMode sAddressMode ) { setSAddressMode( sAddressMode ); return *this; }; void setSAddressMode( SamplerAddressMode sAddressMode ) { mSAddressMode = sAddressMode; }; SamplerAddressMode getSAddressMode() const { return mSAddressMode; }; Format& tAddressMode( SamplerAddressMode tAddressMode ) { setTAddressMode( tAddressMode ); return *this; }; void setTAddressMode( SamplerAddressMode tAddressMode ) { mTAddressMode = tAddressMode; }; SamplerAddressMode getTAddressMode() const { return mTAddressMode; }; Format& rAddressMode( SamplerAddressMode rAddressMode ) { setRAddressMode( rAddressMode ); return *this; }; void setRAddressMode( SamplerAddressMode rAddressMode ) { mRAddressMode = rAddressMode; }; SamplerAddressMode getRAddressMode() const { return mRAddressMode; }; Format& normalizedCoordinates( int normalizedCoordinates ) { setNormalizedCoordinates( normalizedCoordinates ); return *this; }; void setNormalizedCoordinates( int normalizedCoordinates ) { mNormalizedCoordinates = normalizedCoordinates; }; int getNormalizedCoordinates() const { return mNormalizedCoordinates; }; Format& lodMinClamp( int lodMinClamp ) { setLodMinClamp( lodMinClamp ); return *this; }; void setLodMinClamp( int lodMinClamp ) { mLodMinClamp = lodMinClamp; }; int getLodMinClamp() const { return mLodMinClamp; }; Format& lodMaxClamp( int lodMaxClamp ) { setLodMaxClamp( lodMaxClamp ); return *this; }; void setLodMaxClamp( int lodMaxClamp ) { mLodMaxClamp = lodMaxClamp; }; int getLodMaxClamp() const { return mLodMaxClamp; }; #if defined( CINDER_COCOA_TOUCH ) Format& lodAverage( int lodAverage ) { setLodAverage( lodAverage ); return *this; }; void setLodAverage( int lodAverage ) { mLodAverage = lodAverage; }; int getLodAverage() const { return mLodAverage; }; #endif Format& compareFunction( CompareFunction compareFunction ) { setCompareFunction( compareFunction ); return *this; }; void setCompareFunction( CompareFunction compareFunction ) { mCompareFunction = compareFunction; }; CompareFunction getCompareFunction() const { return mCompareFunction; }; Format& label( std::string label ) { setLabel( label ); return *this; }; void setLabel( std::string label ) { mLabel = label; }; std::string getLabel() const { return mLabel; }; protected: SamplerMipFilter mMipFilter; int mMaxAnisotropy; SamplerMinMagFilter mMinFilter; SamplerMinMagFilter mMagFilter; SamplerAddressMode mSAddressMode; SamplerAddressMode mTAddressMode; SamplerAddressMode mRAddressMode; int mNormalizedCoordinates; int mLodMinClamp; int mLodMaxClamp; #if defined( CINDER_COCOA_TOUCH ) int mLodAverage; #endif CompareFunction mCompareFunction; std::string mLabel; }; static SamplerStateRef create( const Format & format = Format() ) { return SamplerStateRef( new SamplerState(format) ); } static SamplerStateRef create( void * mtlSamplerState ) { return SamplerStateRef( new SamplerState(mtlSamplerState) ); } virtual ~SamplerState(); void * getNative(){ return mImpl; } protected: SamplerState( Format format ); SamplerState( void * mtlSamplerState ); void * mImpl = NULL; // <MTLSamplerState> Format mFormat; }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/samples/StockShader/include/SharedTypes.h
<gh_stars>10-100 // // SharedTypes.h // FoldingCube // // Created by <NAME> on 1/30/16. // // #pragma once // Add structs and types here that will be shared between your App and your Shaders #include <simd/simd.h> typedef struct { // float progress; } myUniforms_t;
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/apple/RenderPassDescriptor.h
// // MetalRenderPass.hpp // // Created by <NAME> on 10/13/15. // // #pragma once #include "cinder/Cinder.h" #include "MetalHelpers.hpp" #include "MetalEnums.h" #include "TextureBuffer.h" namespace cinder { namespace mtl { typedef std::shared_ptr<class RenderPassDescriptor> RenderPassDescriptorRef; class RenderPassDescriptor { friend class CommandBuffer; friend class RenderCommandBuffer; public: struct Format { Format() : mShouldClearColor(true) ,mShouldClearDepth(true) ,mShouldClearStencil(true) ,mClearColor(0.f,0.f,0.f,1.f) ,mClearDepth(1.f) ,mClearStencil(0) ,mColorStoreAction(StoreActionStore) ,mDepthStoreAction(StoreActionDontCare) ,mStencilStoreAction(StoreActionDontCare) ,mDepthUsage(TextureUsageRenderTarget) ,mStencilUsage(TextureUsageRenderTarget) ,mHasDepth(true) ,mHasStencil(false) ,mDepthPixelFormat(PixelFormatDepth32Float) ,mStencilPixelFormat(PixelFormatStencil8) {}; public: Format& shouldClearColor( bool shouldClearColor ) { setShouldClearColor( shouldClearColor ); return *this; }; void setShouldClearColor( bool shouldClearColor ) { mShouldClearColor = shouldClearColor; }; bool getShouldClearColor() const { return mShouldClearColor; }; Format& clearColor( ci::ColorAf clearColor ) { setClearColor( clearColor ); return *this; }; void setClearColor( ci::ColorAf clearColor ) { mClearColor = clearColor; }; ci::ColorAf getClearColor() const { return mClearColor; }; Format& colorStoreAction( StoreAction colorStoreAction ) { setColorStoreAction( colorStoreAction ); return *this; }; void setColorStoreAction( StoreAction colorStoreAction ) { mColorStoreAction = colorStoreAction; }; StoreAction getColorStoreAction() const { return mColorStoreAction; }; Format& shouldClearDepth( bool shouldClearDepth ) { setShouldClearDepth( shouldClearDepth ); return *this; }; void setShouldClearDepth( bool shouldClearDepth ) { mShouldClearDepth = shouldClearDepth; }; bool getShouldClearDepth() const { return mShouldClearDepth; }; Format& clearDepth( float clearDepth ) { setClearDepth( clearDepth ); return *this; }; void setClearDepth( float clearDepth ) { mClearDepth = clearDepth; }; float getClearDepth() const { return mClearDepth; }; Format& depthStoreAction( StoreAction depthStoreAction ) { setDepthStoreAction( depthStoreAction ); return *this; }; void setDepthStoreAction( StoreAction depthStoreAction ) { mDepthStoreAction = depthStoreAction; }; StoreAction getDepthStoreAction() const { return mDepthStoreAction; }; Format& depthUsage( TextureUsage depthUsage ) { setDepthUsage( depthUsage ); return *this; }; void setDepthUsage( TextureUsage depthUsage ) { mDepthUsage = depthUsage; }; TextureUsage getDepthUsage() const { return mDepthUsage; }; Format& shouldClearStencil( bool shouldClearStencil ) { setShouldClearStencil( shouldClearStencil ); return *this; }; void setShouldClearStencil( bool shouldClearStencil ) { mShouldClearStencil = shouldClearStencil; }; bool getShouldClearStencil() const { return mShouldClearStencil; }; Format& clearStencil( uint32_t clearStencil ) { setClearStencil( clearStencil ); return *this; }; void setClearStencil( uint32_t clearStencil ) { mClearStencil = clearStencil; }; uint32_t getClearStencil() const { return mClearStencil; }; Format& stencilStoreAction( StoreAction stencilStoreAction ) { setStencilStoreAction( stencilStoreAction ); return *this; }; void setStencilStoreAction( StoreAction stencilStoreAction ) { mStencilStoreAction = stencilStoreAction; }; StoreAction getStencilStoreAction() const { return mStencilStoreAction; }; Format& stencilUsage( TextureUsage stencilUsage ) { setStencilUsage( stencilUsage ); return *this; }; void setStencilUsage( TextureUsage stencilUsage ) { mStencilUsage = stencilUsage; }; TextureUsage getStencilUsage() const { return mStencilUsage; }; Format& hasDepth( bool hasDepth ) { setHasDepth( hasDepth ); return *this; }; void setHasDepth( bool hasDepth ) { mHasDepth = hasDepth; }; bool getHasDepth() const { return mHasDepth; }; Format& hasStencil( bool hasStencil ) { setHasStencil( hasStencil ); return *this; }; void setHasStencil( bool hasStencil ) { mHasStencil = hasStencil; }; bool getHasStencil() const { return mHasStencil; }; Format& depthPixelFormat( PixelFormat pixelFormat ) { setDepthPixelFormat( pixelFormat ); return *this; }; void setDepthPixelFormat( PixelFormat pixelFormat ) { mDepthPixelFormat = pixelFormat; }; PixelFormat getDepthPixelFormat() const { return mDepthPixelFormat; }; Format& stencilPixelFormat( PixelFormat pixelFormat ) { setStencilPixelFormat( pixelFormat ); return *this; }; void setStencilPixelFormat( PixelFormat pixelFormat ) { mStencilPixelFormat = pixelFormat; }; PixelFormat getStencilPixelFormat() const { return mStencilPixelFormat; }; protected: bool mShouldClearColor; ci::ColorAf mClearColor; StoreAction mColorStoreAction; bool mHasDepth; bool mShouldClearDepth; float mClearDepth; StoreAction mDepthStoreAction; TextureUsage mDepthUsage; PixelFormat mDepthPixelFormat; bool mHasStencil; bool mShouldClearStencil; uint32_t mClearStencil; StoreAction mStencilStoreAction; TextureUsage mStencilUsage; PixelFormat mStencilPixelFormat; }; static RenderPassDescriptorRef create( const Format & format = Format() ) { return RenderPassDescriptorRef( new RenderPassDescriptor( format ) ); } static RenderPassDescriptorRef create( void * mtlRenderPassDescriptor ) { return RenderPassDescriptorRef( new RenderPassDescriptor( mtlRenderPassDescriptor ) ); } ~RenderPassDescriptor(); void * getNative(){ return mImpl; }; mtl::TextureBufferRef & getDepthTexture(); mtl::TextureBufferRef & getStencilTexture(); mtl::TextureBufferRef & getColorAttachment( int colorAttachmentIndex = 0 ); void setColorAttachment( TextureBufferRef & texture, int colorAttachmentIndex = 0 ); protected: RenderPassDescriptor( Format format ); RenderPassDescriptor( void * mtlRenderPassDescriptor ); void applyToDrawableTexture( void * texture, int colorAttachmentIndex = 0 ); // <MTLTexture> void setShouldClearColor( bool shouldClear, int colorAttachementIndex = 0 ); void setClearColor( const ColorAf clearColor, int colorAttachementIndex = 0 ); void setColorStoreAction( StoreAction storeAction, int colorAttachementIndex = 0 ); void setShouldClearDepth( bool shouldClear ); void setClearDepth( float clearValue ); void setDepthStoreAction( StoreAction storeAction ); void setShouldClearStencil( bool shouldClear ); void setClearStencil( uint32_t clearValue ); void setStencilStoreAction( StoreAction storeAction ); void * mImpl = NULL; // MTLRenderPassDescriptor * void * mDepthTexture = NULL; // <MTLTexture> void * mStencilTexture = NULL; // <MTLTexture> mtl::TextureBufferRef mDepthTextureBuffer; mtl::TextureBufferRef mStencilTextureBuffer; std::vector<mtl::TextureBufferRef> mColorTextureBuffers; Format mFormat; bool mHasDepth; bool mHasStencil; }; } }
iProfeten/cinder-metal-m1
blocks/Cinder-Metal/include/CameraManager.h
<reponame>iProfeten/cinder-metal-m1 // // CameraManager.h // MetalCamSlices // // Created by <NAME> on 2/10/17. // // #include "cinder/cinder.h" #include "metal.h" #ifdef CINDER_COCOA_TOUCH typedef void (^PixelBufferCallback)( CVPixelBufferRef pxBuffer ); typedef void (^FaceDetectionCallback)( const std::map<long, ci::Rectf> & faceRegionsByID ); class CameraManager { public: struct Options { Options() : mTargetFramerate(60) ,mTargetWidth(640) ,mTargetHeight(480) ,mIsFrontFacing(false) ,mMipMapLevel(1) ,mUsesCinematicStabilization(false) ,mTracksFaces(false) {} public: Options& targetFramerate( int framerate ) { setTargetFramerate( framerate ); return *this; }; void setTargetFramerate( int framerate ) { mTargetFramerate = framerate; }; int getTargetFramerate() const { return mTargetFramerate; }; Options& targetWidth( int width ) { setTargetWidth( width ); return *this; }; void setTargetWidth( int width ) { mTargetWidth = width; }; int getTargetWidth() const { return mTargetWidth; }; Options& targetHeight( int height ) { setTargetHeight( height ); return *this; }; void setTargetHeight( int height ) { mTargetHeight = height; }; int getTargetHeight() const { return mTargetHeight; }; Options& mipMapLevel( int mipMapLevel ) { setMipMapLevel( mipMapLevel ); return *this; }; void setMipMapLevel( int mipMapLevel ) { mMipMapLevel = mipMapLevel; }; int getMipMapLevel() const { return mMipMapLevel; }; Options& isFrontFacing( bool isFrontFacing ) { setIsFrontFacing( isFrontFacing ); return *this; }; void setIsFrontFacing( bool isFrontFacing ) { mIsFrontFacing = isFrontFacing; }; bool getIsFrontFacing() const { return mIsFrontFacing; }; Options& tracksFaces( bool trackFaces ) { setTracksFaces( trackFaces ); return *this; }; void setTracksFaces( bool trackFaces ) { mTracksFaces = trackFaces; }; bool getTracksFaces() const { return mTracksFaces; }; Options& usesCinematicStabilization( bool useCinematicStabilization ) { setUsesCinematicStabilization( useCinematicStabilization ); return *this; }; void setUsesCinematicStabilization( bool useCinematicStabilization ) { mUsesCinematicStabilization = useCinematicStabilization; }; bool getUsesCinematicStabilization() const { return mUsesCinematicStabilization; }; protected: int mTargetFramerate; int mTargetWidth; int mTargetHeight; bool mIsFrontFacing; bool mTracksFaces; bool mUsesCinematicStabilization; int mMipMapLevel; }; CameraManager( Options options = Options() ); bool hasTexture(); cinder::mtl::TextureBufferRef & getTexture( const int inflightBufferIndex = -1 ); double getTimeLastFrame(); // Comes from a CFAbsoluteTime void startCapture(); void stopCapture(); bool isCapturing(); bool isFrontFacing(){ return mOptions.getIsFrontFacing(); } // restartWithOptions is good for toggling between front and back cameras with different resolutions, etc void restartWithOptions( const Options & options ); void lockConfiguration( bool isExposureLocked = true, bool isWhiteBalanceLocked = true, bool isFocusLocked = true ); void unlockConfiguration( bool isExposureUnlocked = true, bool isWhiteBalanceUnlocked = true, bool isFocusUnlocked = true ); void setPixelBufferCallback( const PixelBufferCallback & pxBufferCallback ); void setFaceDetectionCallback( const FaceDetectionCallback & faceDetectionCallback ); protected: void init(); void *mImpl; bool mIsCapturing; Options mOptions; }; #endif
dacaiguoguo/bubbleSort
BubbleSort/main.c
// // main.c // BubbleSort // // Created by dacaiguoguo on 2020/8/14. // Copyright © 2020 dacaiguoguo. All rights reserved. // #include <stdio.h> #include <stdbool.h> void bubbleSort(int* array, int length, _Bool betterFlag); void logArray(int* toSortArray, int length); int main(int argc, const char * argv[]) { // int toSortArray[10] = {3, 6, 8, 2, 1, 0, 9, 4, 7, 5}; int toSortArray[10] = {13, 6, 38, 22, 81, 170, 29, 34, 167, 135}; // int toSortArray[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; int lengthOfArray = sizeof(toSortArray)/sizeof(int); logArray(toSortArray, lengthOfArray); bubbleSort(toSortArray, lengthOfArray, true); return 0; } void logArray(int* toSortArray, int length) { for (int i=0; i<length; i++) { printf("%d ", toSortArray[i]); if (i == length-1) { printf("\n"); } } } void bubbleSort(int* array, int length, _Bool betterFlag) { int exchangeCount = 0; int totalExchangeCount = 0; for (int maxLoopCount = length-1; maxLoopCount > 1; maxLoopCount--) { exchangeCount = 0; int initIndex = length - 1 - maxLoopCount; int maxIndex = initIndex; if (!betterFlag) { initIndex = 0; } for (int i=initIndex, j = initIndex+1; i < maxLoopCount; i++, j++) { int initNumber = array[i]; int nextNumber = array[j]; if (nextNumber > initNumber) { exchangeCount++; array[j] = initNumber; array[i] = nextNumber; logArray(array, length); if (array[i] > array[maxIndex]) { maxIndex = i; } } } if (betterFlag && initIndex != maxIndex) { // 如果找到的最大值的位置不是起点位置就把最大值换到起点,这样一次循环就完成了冒泡和最大下沉的动作 exchangeCount++; int temp = array[initIndex]; array[initIndex] = array[maxIndex]; array[maxIndex] =temp; } totalExchangeCount += exchangeCount; if (exchangeCount == 0) { // 如果没有发生位置交换说明已经完成排序 终止程序 break; } logArray(array, length); } printf("totalexchangeCount:%d\n", totalExchangeCount); }
norio-nomura/RxSwift
RxSwift/RxSwift.h
// // RxSwift.h // RxSwift // // Created by <NAME> on 4/1/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for RxSwift. FOUNDATION_EXPORT double RxSwiftVersionNumber; //! Project version string for RxSwift. FOUNDATION_EXPORT const unsigned char RxSwiftVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <RxSwift/PublicHeader.h>
samuelkgutierrez/gladius
source/ui/term/term.h
/* * Copyright (c) 2014-2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. * * Copyright (c) 1992,1993 The Regents of the University of California. * All rights reserved. * See tc1.c in the libedit distribution for more details. */ /** * Implements the (pseudo) terminal functionality for the tool front-end UI. The * heavy lifting for the CLI is performed by editline (libedit). */ #ifndef GLADIUS_UI_TERM_TERM_H_INCLUDED #define GLADIUS_UI_TERM_TERM_H_INCLUDED #include "core/core.h" #include "core/args.h" #include "core/session.h" #include "ui/ui.h" #include <string> #include <vector> #include <utility> #include <map> #include <initializer_list> #include <functional> #include <algorithm> #include <sstream> #include "histedit.h" namespace gladius { namespace ui { namespace term { class Terminal; /** * */ struct EvalInputCmdCallBackArgs { Terminal *terminal; int argc; char **argv; EvalInputCmdCallBackArgs( Terminal *t, int argc, const char **argv ) : terminal(t) , argc(argc) , argv((char **)argv) { ; } }; /** * */ class TermCommand { private: /// Command name std::string mCMD; /// Command name aliases in "v, v, v" format. std::string mCMDAliases; /// Short command usage. std::string mShortUsage; /// Long command usage. std::string mLongUsage; /// The call-back function that implements the command's functionality. std::function<bool (const EvalInputCmdCallBackArgs &)> mCBFun; public: TermCommand(void) { ; } TermCommand( std::string cmd, std::string cmdAliases, std::string shortUsage, std::string longUsage, std::function<bool (const EvalInputCmdCallBackArgs &)> cmdCallBack ) : mCMD(cmd) , mCMDAliases(cmdAliases) , mShortUsage(shortUsage) , mLongUsage(longUsage) , mCBFun(cmdCallBack) { ; } std::string command(void) const { return mCMD; } std::string commandAliases(void) const { return mCMDAliases; } std::string shortUsage(void) const { return mShortUsage; } std::string longUsage(void) const { return mLongUsage; } bool exec(const EvalInputCmdCallBackArgs &args) const { return mCBFun(args); } }; /** * */ class TermCommands { private: // Map containing command name, callback pairs. std::map<std::string , TermCommand> mNameTermMap; /** * Returns a vector of command aliases from a string of comma-separated * values. */ std::vector<std::string> getCommandAliases(std::string nameCSV) { std::vector<std::string> nameVec; std::istringstream buf(nameCSV); for (std::string tok; std::getline(buf, tok, ','); ) { nameVec.push_back(core::utils::trim(tok)); } return nameVec; } public: /** * */ TermCommands(std::initializer_list<TermCommand> tCMDs) { // For each TermCommand for (auto tm : tCMDs) { // Bind the official name with the callback mNameTermMap[tm.command()] = tm; // And do the rest (aliases) for (auto cmdName : getCommandAliases(tm.commandAliases())) { mNameTermMap[cmdName] = tm; } } } /** * */ const TermCommand * getTermCMD(std::string name) const { auto tmi = mNameTermMap.find(name); // not found, so return nullptr; if (tmi == mNameTermMap.end()) { return nullptr; } else { return &tmi->second; } } /** * Returns a vector of available terminal commands. */ std::vector<TermCommand> availableCommands(void) const { std::vector<TermCommand> tv; for (auto nameCmd : mNameTermMap) { tv.push_back(nameCmd.second); } return tv; } }; class Terminal : public UI { // static constexpr int sHistSize = 100; // static const std::string sHistFileName; // core::SessionFE &mSession; // std::string mHistFile; // EditLine *mEditLine = nullptr; // Tokenizer *mTokenizer = nullptr; // History *mHist = nullptr; // HistEvent mHistEvent; // Terminal(void) : mSession(core::SessionFE::TheSession()) { ; } // ~Terminal(void); // void evaluateInput( int ac, const char **argv, bool &continueREPL ); // void mEnterREPL(void); // void mLoadHistory(void); // void mSaveHistory(void); // bool mHistRecallRequest( const std::string &input, std::string &histStringIfValid ); public: // static Terminal & TheTerminal(void); /** * Disable copy constructor. */ Terminal(const Terminal &that) = delete; /** * Just return the singleton. */ Terminal & operator=(const Terminal &other) { GLADIUS_UNUSED(other); return Terminal::TheTerminal(); } /** * */ EditLine * getEditLine(void) { return mEditLine; } /** * */ History * getHistory(void) { return mHist; } /** * */ HistEvent & getHistEvent(void) { return mHistEvent; } /** * */ const TermCommands & getTermCommands(void) const { return sTermCommands; } // void init(const core::Args &args); // void interact(void); // bool quit(void); // std::vector< std::pair<std::string, std::string> > cmdPairs(void) const; // void installSignalHandlers(void); // void uninstallSignalHandlers(void); private: static TermCommands sTermCommands; }; } // end term namespace } // end ui namespace } // end gladius namespace #endif
samuelkgutierrez/gladius
source/timeline/graph-widget.h
/** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef TIMELINE_GRAPH_WIDGET_H #define TIMELINE_GRAPH_WIDGET_H #include "common.h" #include "info-types.h" #include <QGraphicsView> #include <QMap> QT_BEGIN_NAMESPACE class QWidget; class QGraphicsScene; QT_END_NAMESPACE class ProcTimeline; class GraphWidget : public QGraphicsView { Q_OBJECT public: // GraphWidget(QWidget *parent = nullptr); // void addProcTimeline(const ProcDesc &procDesc); // void plot(void); // void addPlotData(const LegionProfData &plotData); // void updateProcTimelineLayout(void); private: // QGraphicsScene *mScene = nullptr; // QMap<procid_t, ProcTimeline *> mProcTimelines; }; #endif // TIMELINE_GRAPHWIDGET_H
samuelkgutierrez/gladius
source/tool-be/tool-be.h
/* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * The Back-End (BE) API. The interface to the back-end tool actions. */ #pragma once #include "tool-api/gladius-toolbe.h" #include "core/core.h" #include "mrnet/mrnet-be.h" #include "plugin/core/gp-manager.h" #include "plugin/core/gladius-plugin.h" #include <string> namespace gladius { namespace toolbe { class Tool::ToolBE { private: // bool mBeVerbose; // Out UID for the job. int mUID; // Our MRNet back-end instance. mrnetbe::MRNetBE mMRNBE; // The name of the target plugin. std::string mPluginName; // The path to the plugin pack. std::string mPathToPluginPack; // The plugin manager. gpa::GladiusPluginManager mPluginManager; // The plugin pack for our current session. gpa::GladiusPluginPack mPluginPack; // The plugin instance pointer. gpi::GladiusPlugin *mBEPlugin = nullptr; // void mLoadPlugins(void); public: // ToolBE(void); // ~ToolBE(void); // int init(bool beVerbose); // int create(int uid); // int connect(void); // static int redirectOutputTo(const std::string &base); // void enterPluginMain(void); }; } // end toolbe namespace } // end gladius namespace
samuelkgutierrez/gladius
source/dsys/dsi.h
/* * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * The Distributed System (dsys) Interface (DSI). */ #pragma once #include "dsys/palp.h" #include "core/process-landscape.h" #include "tool-common/session-key.h" #include <string> #include <vector> namespace gladius { namespace dsi { /** * */ class DSI { private: // static const char sDSysName[]; // static const char sPromptString[]; //The initial size of the output buffer. 16k should be plenty. static constexpr size_t sInitBufSize = 1024 * 16; // dsys::AppLauncherPersonality mLauncherPersonality; // size_t mCurLineBufSize = 0; // bool mBeVerbose = false; // int mToAppl[2]; // int mFromAppl[2]; // PID of application launcher process. pid_t mApplPID = 0; // char *mFromDSysLineBuf = nullptr; // FILE *mTo = nullptr; // size_t mGetRespLine(void); // void mWaitForPrompt(void); // int mDrainToString( std::string &result ); // int mSendCommand( const std::string &rawCMD ); // int mRecvResp( std::string &outputIfSuccess ); // void mChildCleanup(void); public: // DSI(void); // ~DSI(void); // int init( const dsys::AppLauncherPersonality &palp, bool beVerbose ); // int getProcessLandscape( core::ProcessLandscape &pl ); // int publishConnectionInfo( toolcommon::SessionKey sessionKey, const std::vector<std::string> &leafInfos ); // int shutdown(void); }; } // end dsi namespace } // end gladius namespace
samuelkgutierrez/gladius
source/ui/term/term-cmds.h
<gh_stars>1-10 /* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include "term.h" #include "core/core.h" #include "core/colors.h" #include "core/env.h" #include "tool-fe/tool-fe.h" #include <string> #include <vector> #include <iostream> #include <sys/types.h> #include <signal.h> namespace { /** * */ void echoCommandUsage( const gladius::ui::term::EvalInputCmdCallBackArgs &args, const std::string &cmdName ) { using namespace gladius; auto trmCMD = args.terminal->getTermCommands().getTermCMD(cmdName); GLADIUS_CERR_WARN << "Usage: " << trmCMD->shortUsage() << std::endl; } } namespace gladius { namespace ui { namespace term { /** * Clears the screen. */ inline bool clearCMDCallback(const EvalInputCmdCallBackArgs &args) { static char clearHex[2] = {0x0C, '\0'}; el_push(args.terminal->getEditLine(), clearHex); return true; } /** * Quits. */ inline bool quitCMDCallback(const EvalInputCmdCallBackArgs &args) { using namespace std; GLADIUS_UNUSED(args); GLADIUS_CERR_WARN << "Quitting. Do you really want to proceed: [Y/n]: " << flush; char answer[8]; cin.getline(answer, sizeof(answer)); if (0 == strcmp("Y", answer)) { // Done with REPL return false; } // The answer was not "Y", so continue REPL. return true; } /** * Displays help message. */ inline bool helpCMDCallback(const EvalInputCmdCallBackArgs &args) { using namespace gladius::core; using namespace std; string header(PACKAGE_NAME " help"); stringstream hbot; for (auto ci = header.cbegin(); ci != header.cend(); ++ci) { hbot << "-"; } // Print help banner. cout << '\n' << colors::color().ansiBeginColor(colors::MAGENTA) << header << colors::color().ansiEndColor() << '\n' << hbot.str() << endl; // Print available commands. cout << "o Available Commands" << endl; for (const auto cmdp : args.terminal->cmdPairs()) { cout << "- " << cmdp.first << " : " << cmdp.second << endl; } cout << endl; /* Continue REPL */ return true; } /** * Displays the available modes. */ inline bool modesCMDCallback(const EvalInputCmdCallBackArgs &args) { GLADIUS_UNUSED(args); /* Continue REPL */ return true; } /** * Sets an environment variable during a debug session. * Form: setenv ENV_VAR VAL */ inline bool setEnvCMDCallback(const EvalInputCmdCallBackArgs &args) { using std::string; using namespace gladius::core; if (args.argc != 3) { // should have 3 arguments. So, print out the usage. echoCommandUsage(args, args.argv[0]); return true; } try { char **argv = args.argv; utils::setEnv(string(argv[1]), string(argv[2])); } catch(const std::exception &e) { throw core::GladiusException(GLADIUS_WHERE, e.what()); } // Continue REPL return true; } /** * Unsets an environment variable during a debug session. * Form: unsetenv ENV_VAR */ inline bool unsetEnvCMDCallback(const EvalInputCmdCallBackArgs &args) { using std::string; using namespace gladius::core; if (args.argc != 2) { // should have 3 arguments. So, print out the usage. echoCommandUsage(args, args.argv[0]); return true; } char **argv = args.argv; auto err = 0; if (GLADIUS_SUCCESS != utils::unsetEnv(string(argv[1]), err)) { string whatsWrong = utils::getStrError(err); GLADIUS_CERR_WARN << "unsetenv Failed: " << whatsWrong << std::endl; } // Continue REPL return true; } /** * Displays history. */ inline bool historyCMDCallback(const EvalInputCmdCallBackArgs &args) { Terminal *t = args.terminal; HistEvent &histEvent = t->getHistEvent(); for (int rv = history(t->getHistory(), &histEvent, H_LAST); rv != -1; rv = history(t->getHistory(), &histEvent, H_PREV)) { (void)fprintf(stdout, "%4d %s", histEvent.num, histEvent.str); } /* Continue REPL */ return true; } /** * Launches target application. * Expecting: * launch application [OPTION]... with launcher [OPTION]... */ inline bool launchCMDCallback(const EvalInputCmdCallBackArgs &args) { using namespace std; // Recall: 'launch' will always be the first argument in argv // launch should have at least 4 arguments. So, print out the usage. if (args.argc < 4) { echoCommandUsage(args, args.argv[0]); return true; } // Index of where the launcher argv begins. 1 to skip 'launch' int li = 1; // Grab application argv. vector<string> appArgv; for (; li < args.argc; ++li) { const string arg = args.argv[li]; if ("with" == arg) break; appArgv.push_back(arg); } if (appArgv.empty() || li == args.argc || "with" != string(args.argv[li])) { GLADIUS_CERR << "Malformed launch command... Please try again." << endl; echoCommandUsage(args, args.argv[0]); return true; } // Grab launcher argv. // Skip 'with' li += 1; vector<string> launcherArgv; for (; li < args.argc; ++li) { launcherArgv.push_back(args.argv[li]); } // Make sure with what is provided. if (launcherArgv.empty()) { GLADIUS_CERR << "Launcher command not provided. 'with' what?" << endl; echoCommandUsage(args, args.argv[0]); return true; } // args.terminal->TheTerminal().uninstallSignalHandlers(); // A new instance every time we are here. toolfe::ToolFE toolFE; // Enter the tool's main loop. (void)toolFE.main(core::Args(appArgv), core::Args(launcherArgv)); // args.terminal->TheTerminal().installSignalHandlers(); // Continue REPL return true; } /** * Prints environment variables. * Expecting: * env */ inline bool envCMDCallback(const EvalInputCmdCallBackArgs &args) { // env should have 1 argument if (args.argc != 1) { echoCommandUsage(args, args.argv[0]); return true; } core::Environment::TheEnvironment().prettyPrint(); /* Continue REPL */ return true; } } // end term namespace } // end ui namespace } // end gladius namespace
samuelkgutierrez/gladius
source/mrnet/mrnet-fe.h
<reponame>samuelkgutierrez/gladius /** * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. * * Copyright (c) 2003-2012 <NAME>, <NAME>, <NAME> * Detailed MRNet usage rights in "LICENSE" file in the MRNet distribution. * */ #pragma once #include "core/process-landscape.h" #include "tool-common/tool-common.h" #include <string> #include <cstdint> #include "mrnet/MRNet.h" namespace gladius { namespace mrnetfe { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// struct LeafInfo { MRN::NetworkTopology *networkTopology = nullptr; std::vector<MRN::NetworkTopology::Node *> leaves; }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// class MRNetTopology { public: // enum TopologyType { FLAT = 0 }; private: // std::string mTopoFilePath; // TopologyType mTopoType; // Hostname of the tool front-end. std::string mFEHostName; // core::ProcessLandscape mProcLandscape; // std::string mGenFlatTopo(void); // bool mCanRMFile = false; public: /** * */ MRNetTopology(void) = default; /** * */ ~MRNetTopology(void) { if (mCanRMFile) remove(mTopoFilePath.c_str()); } // MRNetTopology( const std::string &topoFilePath, TopologyType topoType, const std::string &feHostName, const core::ProcessLandscape &procLandscape ); }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * Implements the MRNet interface for a tool front-end. */ class MRNetFE { private: // static const std::string sCommNodeName; // static const std::string sCoreFiltersSO; // Be verbose or not. bool mBeVerbose; // Base session directory. std::string mSessionDir; // Path to MRNet topology file. std::string mTopoFile; // Name of the backend executable std::string mBEExe; // Absolute path to MRNet installation. std::string mPrefixPath; // The process landscape of our job. core::ProcessLandscape mProcLandscape; // Leaf infos LeafInfo mLeafInfo; // The MRNet network instance. MRN::Network *mNetwork = nullptr; // MRN::Communicator *mBcastComm = nullptr; // MRN::Stream *mProtoStream = nullptr; // The number of tree nodes in our topology. unsigned int mNTreeNodes = 0; // Number of tool threads per target. unsigned int mNThread = 0; // unsigned int mNExpectedBEs = 0; // int mBuildNetwork(void); // Registers MRNet even callbacks. int mRegisterEventCallbacks(void); // int mPopulateLeafInfo(void); // int mEchoNetStats(void); // int mDetermineAndSetPaths(void); // int mGetPrefixFromCommNode( const std::string &whichString, std::string &prefix ); // int mLoadCoreFilters(void); public: MRNetFE(void); // ~MRNetFE(void); // int mSetEnvs(void); // int createNetworkFE( const core::ProcessLandscape &procLandscape ); // int init(bool beVerbose = false); // int generateConnectionMap( std::vector<toolcommon::ToolLeafInfoT> &cMap ); // void finalize(void); /** * Sets MRNetFE verbosity. */ void verbose(bool b) { mBeVerbose = b; } /** * */ MRN::Network * getNetwork(void) { return mNetwork; } /** * */ MRN::Stream * getProtoStream(void) { return mProtoStream; } // int connect(void); // int networkInit(void); // int handshake(void); // int pluginInfoBCast( const std::string &validPluginName, const std::string &pathToValidPlugin ); }; } // end mrnetfe namespace } // end gladius namespace
samuelkgutierrez/gladius
source/plugin/hello/hello-filters.h
/** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef GLADIUS_PLUGIN_HELLO_FILTERS_H_INCLUDED #define GLADIUS_PLUGIN_HELLO_FILTERS_H_INCLUDED #include "mrnet/Types.h" #endif
samuelkgutierrez/gladius
source/tool-common/session-key.h
/* * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * Home to job the SessionKey type. * Session keys are used as a unique identifier to differentiate between * different analysis jobs, etc. */ #pragma once #include <limits.h> namespace gladius { namespace toolcommon { typedef char SessionKey[32 + HOST_NAME_MAX]; } // end namespace } // end namespace
samuelkgutierrez/gladius
source/core/colors.h
/* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include <string> #include <vector> #include <utility> namespace gladius { namespace core { class colors { private: // Are we colorizing the output? bool mColorize = false; // colors(void) { ; } // ~colors(void) { ; } public: /** * Supported colors. Order matters here. If updated, also update * ColorCodeTab. */ enum Color { NONE = 0, WHITE, RED, GREEN, YELLOW, MAGENTA, DGRAY, }; /** * Returns reference to the color instance. */ static colors & color(void); /** * Disable copy constructor. */ colors(const colors &that) = delete; // colors & operator=(const colors &other); /** * */ std::string ansiBeginColor( Color c ) const { if (!mColorize || c > ColorCodeTab.size()) return ""; return ColorCodeTab[c].second; } /** * */ std::string ansiEndColor( void ) const { if (!mColorize) return ""; return "\033[0m"; } /** * */ void colorize(bool colors) { mColorize = colors; } private: // static std::vector< std::pair<Color, std::string> > ColorCodeTab; }; } // end core namespace } // end gladius namespace
samuelkgutierrez/gladius
source/core/gladius-rc.h
<gh_stars>1-10 /* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once /** * Return codes. */ enum { GLADIUS_SUCCESS = 0, GLADIUS_ERR, GLADIUS_ERR_OOR, GLADIUS_ERR_IO, GLADIUS_ERR_SYS, GLADIUS_ERR_MRNET, GLADIUS_ENV_NOT_SET, GLADIUS_NOT_CONNECTED, GLADIUS_PLUGIN_NOT_FOUND };
samuelkgutierrez/gladius
source/core/console.h
<filename>source/core/console.h /* * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include <iostream> #include <sstream> #include <string> namespace gladius { namespace core { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// class console { /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// class OutS : public std::ostream { //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// class StreamBuf : public std::stringbuf { // std::ostream &mOutput; public: /** * */ StreamBuf(std::ostream &str) : mOutput(str) { ; } /** * */ virtual int sync(void) { mOutput << "[blah]" << str(); str(""); mOutput.flush(); return 0; } }; // class StreamBuf // StreamBuf mBuffer; public: /** * */ OutS( void ) : std::ostream(&mBuffer) , mBuffer(std::cout) { ; } /** * */ OutS( std::ostream &os ) : std::ostream(&mBuffer) , mBuffer(os) { ; } }; // class OutS // std::string mMsgPrefix; // OutS *mOuts = nullptr; // OutS *mErrs = nullptr; public: /** * */ console( std::string msgPrefix = "" ) : mMsgPrefix(msgPrefix) , mOuts(new OutS(std::cout)) , mErrs(new OutS(std::cerr)) { ; } /** * */ OutS & outs(void) { return *mOuts; } /** * */ OutS & errs(void) { return *mErrs; } }; // class console } // end core namespace } // end gladius namespace
samuelkgutierrez/gladius
testing/legion/mrnet-mapper/tool/tool-proto.h
/* * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include "mrnet/Types.h" #define PROTO_CONN (FirstApplicationTag) #define PROTO_PING (FirstApplicationTag + 1) #define PROTO_EXIT (FirstApplicationTag + 2) #define PROTO_STEP (FirstApplicationTag + 3)
samuelkgutierrez/gladius
source/plugin/core/gp-manager.h
<filename>source/plugin/core/gp-manager.h /* * Copyright (c) 2015-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * The gladius plugin manager. */ #pragma once #include "plugin/core/gladius-plugin.h" #include <cstdint> #include <string> #include <map> namespace gladius { // The "Gladius Plugin Architecture (GPA) " namespace. namespace gpa { /** * */ struct GladiusPluginPack { // IDs of the different kinds of plugin packs that can be returned. enum PluginPackType { PluginFE = 0, PluginBE, }; // ID to name map of required plugins. static const std::map<uint8_t, std::string> sRequiredPlugins; // gpi::GladiusPluginInfo *pluginInfo = nullptr; }; /** * Gladius plugin manager. */ class GladiusPluginManager { // Flag indicating whether or not we'll be verbose about our actions. bool mBeVerbose = false; // std::string mTargetModeName; // bool mPluginPackLooksGood( const std::string &pathToPackBase ); public: // GladiusPluginManager(void) { ; } // ~GladiusPluginManager(void) { ; } // GladiusPluginManager( const std::string &targetModeName, bool beVerbose = false ) : mBeVerbose(beVerbose) , mTargetModeName(targetModeName) { ; } // bool pluginPackAvailable( std::string &pathToPluginPackIfAvail ); // GladiusPluginPack getPluginPackFrom( GladiusPluginPack::PluginPackType pluginPackType, const std::string &validPluginPackPath ); // TODO close handles! Add function to close plugin pack. }; } // end gpa namespace } // end gladius namespace
samuelkgutierrez/gladius
source/core/process-landscape.h
/* * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * Gives the 'process landscape' of a parallel and distributed application * wherein the used hosts and number of targets for each host is maintained. */ #pragma once #include "core/core.h" #include "core/macros.h" #include <iostream> #include <string> #include <map> #include <set> namespace gladius { namespace core { class ProcessLandscape { // Mapping between hostnames and the number of processes they'll be hosting. // Guaranteed to be unique by host name. std::map<std::string, int> mLandscape; public: /** * */ ProcessLandscape(void) { ; } /** * Returns a const reference to the current landscape. */ const std::map<std::string, int> & landscape(void) const { return mLandscape; } /** * Returns a set of all the host names in the current landscape. */ const std::set<std::string> hostNames(void) const { std::set<std::string> res; for (const auto mi : mLandscape) { res.insert(mi.first); } return res; } /** * Returns the number of hosts. */ size_t nHosts(void) const { return mLandscape.size(); } /** * Returns the total number of tasks across all the hosts. */ size_t nProcesses(void) const { size_t res = 0; for (const auto &mi : mLandscape) { res += mi.second; } return res; } /** * */ int insert( const std::string &hn, int nProc ) { using namespace std; // Already in the table. Warn and just update. if (0 != mLandscape.count(hn)) { GLADIUS_CERR_WARN << hn << " already in table..." << endl; } mLandscape[hn] = nProc; // return GLADIUS_SUCCESS; } }; } // end core namespace } // end gladius namespace
samuelkgutierrez/gladius
source/core/exception.h
/** * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include <string> #include <exception> namespace gladius { namespace core { #define GLADIUS_WHERE __FILE__, __LINE__ class GladiusException : public std::exception { private: std::string whatString; GladiusException(void); public: ~GladiusException(void) throw() { } GladiusException(std::string fileName, int lineNo, const std::string &errMsg, bool where = true); virtual const char *what(void) const throw(); void fooBar(void); }; } // end core namespace } // end gladius namespace
samuelkgutierrez/gladius
testing/legion/mrnet-mapper/tool/tooli.h
<reponame>samuelkgutierrez/gladius<gh_stars>1-10 /* * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include "tool-proto.h" #include <cassert> #include <cstdlib> #include <iostream> #include <string> #include <map> #include <fstream> #include <thread> #include <atomic> #include <mutex> #include <condition_variable> #include <chrono> #include <limits.h> #include <unistd.h> #include "mrnet/MRNet.h" #include "xplat/Monitor.h" // TODO move using namespace MRN; using namespace std; struct ThreadPersonality { int rank = 0; static constexpr int argc = 6; char *argv[argc]; }; class ToolContext { public: enum ToolConditions { MAP = 0 }; private: ssize_t mUID = 0; size_t mNToolThreads = 0; size_t mNToolThreadsAttached = 0; std::vector<std::thread> mThreads; std::string mConnectionFile; public: std::condition_variable allThreadsAttached; std::mutex allThreadsAttachedMutex; XPlat::Monitor *inMapper = NULL; // TODO make thread-safe and have many. MRN::Network *net = NULL; char mHostname[HOST_NAME_MAX]; char parentHostname[HOST_NAME_MAX], parentPort[16], parentRank[16]; ToolContext( ssize_t uid, size_t nToolThreads, std::string connectionFile ) : mUID(uid) , mNToolThreads(nToolThreads) , mConnectionFile(connectionFile) { // TODO delete inMapper = new XPlat::Monitor(); inMapper->RegisterCondition(MAP); assert(-1 != gethostname(mHostname, sizeof(mHostname))); } std::vector<std::thread> & getThreads(void) { return mThreads; } ssize_t getUID(void) const { return mUID; } std::string getConnectionInfo(void) const { return mConnectionFile; } size_t getNToolThreads(void) { return mNToolThreads; } void threadAttached(void) { std::lock_guard<std::mutex> lock(allThreadsAttachedMutex); ++mNToolThreadsAttached; allThreadsAttached.notify_one(); } void waitForAttach(void) { // TODO FIXME const auto timeout = std::chrono::seconds(100000); std::unique_lock<std::mutex> lock(allThreadsAttachedMutex); auto status = allThreadsAttached.wait_for( lock, timeout, [&](){ return mNToolThreads == mNToolThreadsAttached; } ); // TODO make sure all are fine and report to caller. if (status) { cout << "success!!!!!" << endl; fflush(stdout); } else { cout << "timed out!!!!!!!!!!!!" << endl; fflush(stdout); } } }; int getParentInfo(ToolContext &tc) { char lineBuf[256]; const char *file = tc.getConnectionInfo().c_str(); ifstream ifs(file); assert(ifs.is_open()); while (ifs.good()) { ifs.getline(lineBuf, sizeof(lineBuf)); char pname[64]; int tpport, tprank, trank; int matches = sscanf( lineBuf, "%s %d %d %d", pname, &tpport, &tprank, &trank ); if (4 != matches) { fprintf(stderr, "Error while scanning %s\n", file); ifs.close(); return 1; } if (trank == tc.getUID()) { sprintf(tc.parentHostname, "%s", pname); sprintf(tc.parentPort, "%d", tpport); sprintf(tc.parentRank, "%d", tprank); ifs.close(); return 0; } } ifs.close(); // my rank not found :( return 1; } void * toolThreadMain( ToolContext *tc, ThreadPersonality *tp ) { char rankStr[64]; snprintf(rankStr, sizeof(rankStr), "%d", tp->rank); tp->argv[5] = rankStr; int32_t recv_int = 0; int tag; PacketPtr p; Stream *stream; assert(6 == tp->argc); tc->net = Network::CreateNetworkBE(tp->argc, tp->argv); assert(tc->net); if (tc->net->recv(&tag, p, &stream) != 1) { fprintf( stderr, "BE[%s]: net->recv() failure\n", rankStr); tag = PROTO_EXIT; } switch (tag) { case PROTO_CONN: { if (p->unpack( "%d", &recv_int) == -1) { fprintf( stderr, "BE[%s]: stream::unpack(%%d) failure\n", rankStr); return NULL; } // Ack if ((stream->send(PROTO_CONN, "%d", recv_int) == -1) || (stream->flush() == -1 )) { fprintf( stderr, "BE[%s]: stream::send(%%d) failure\n", rankStr); assert(false); } printf("connected!\n"); tc->threadAttached(); break; } default: fprintf( stderr, "BE[%s]: Unknown Protocol %d\n", rankStr, tag); tag = PROTO_EXIT; break; } fflush(stdout); fflush(stderr); #if 0 // FE delete of the network will cause us to exit, wait for it net->waitfor_ShutDown(); delete net; #endif delete tp; return NULL; } int toolAttach( ToolContext &tc ) { if (0 == tc.getUID()) cout << "=== attaching tool..." << endl; // TODO add as class member assert(!getParentInfo(tc)); std::vector<std::thread> &threads = tc.getThreads(); const auto nThreads = tc.getNToolThreads(); for (size_t i = 0; i < nThreads; ++i) { ThreadPersonality *tp = new ThreadPersonality(); tp->rank = (10000 * (i + 1)) + tc.getUID(); tp->argv[0] = (char *)"./toolBE"; tp->argv[1] = tc.parentHostname; tp->argv[2] = tc.parentPort; tp->argv[3] = tc.parentRank; tp->argv[4] = tc.mHostname; threads.push_back(std::thread(toolThreadMain, &tc, tp)); } tc.waitForAttach(); tc.inMapper->WaitOnCondition(ToolContext::ToolConditions::MAP); // wait for all the threads to start return 0; } int toolDetach(ToolContext &tc) { if (0 == tc.getUID()) cout << "=== detaching tool..." << endl; std::vector<std::thread> &threads = tc.getThreads(); const auto nThreads = threads.size(); for (size_t t = 0; t < nThreads; ++t) { threads[t].join(); } return 0; }
samuelkgutierrez/gladius
source/plugin/hello/hello-common.h
/* * Copyright (c) 2015-2106 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * Common stuff (FE/BE) for the Parallel Step (hello) plugin. */ #pragma once #include "plugin/core/gladius-plugin.h" // The plugin's name. #define PLUGIN_NAME "hello" // The plugin's version string. #define PLUGIN_VERSION "0.0.1" namespace hello { // enum HelloProtoTags { // Notice where we start here. ALL plugins MUST start with this tag value. SayHello = gladius::toolcommon::FirstPluginTag, Shutdown }; } // end hello namesapce.
samuelkgutierrez/gladius
source/gladius/gladius.h
/* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include "core/core.h" #include "core/session.h" #include "core/env.h" #include "ui/ui.h" namespace gladius { class Gladius { private: // core::Args mArgs; // core::SessionFE &mCurrentSession; // core::Environment &mEnv; // ui::UI &mUI; // Gladius(void); // void mCoreComponentRegistration(void); public: /** * */ ~Gladius(void); /** * */ Gladius(const core::Args &args); /** * */ void run(void); // bool shutdown(void); }; } // end gladius namespace
samuelkgutierrez/gladius
source/core/session.h
<gh_stars>1-10 /* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include <string> namespace gladius { namespace core { /** * */ class SessionFE { // The name of our user-specific session directory where we stash some of // our stuff. static const std::string sDotName; // The installation prefix of the tool front-end. std::string mExecPrefix; // std::string mSessionFEDir; // SessionFE(void) { ; } // void mOpen(void); // void init(void); // void mSetExecPrefix(void); // ~SessionFE(void) { ; } public: // static SessionFE & TheSession(void); // std::string sessionDir(void) { return mSessionFEDir; } /** * Disable copy constructor. */ SessionFE(const SessionFE &that) = delete; // SessionFE & operator=(const SessionFE &other); /** * */ std::string execPrefix(void) { return mExecPrefix; } }; } }
samuelkgutierrez/gladius
source/core/core.h
<reponame>samuelkgutierrez/gladius<filename>source/core/core.h /** * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "core/gladius-rc.h" #include "core/env.h"
samuelkgutierrez/gladius
source/ui/ui-factory.h
<reponame>samuelkgutierrez/gladius /** * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include "ui.h" #include "term/term.h" #include "core/core.h" namespace gladius { namespace ui { /** * User Interface (UI) factory class. */ class UIFactory { public: /** * UI Types. */ enum UIType { UI_TERM, UI_GUI }; /** * Factory function that takes a UI type and args and produces a UI based on * the provided input. Throws GladiusException on failure. */ static UI & getUI( const core::Args &args, UIType uiType ) { GLADIUS_UNUSED(args); switch (uiType) { case UI_TERM: return term::Terminal::TheTerminal(); default: GLADIUS_THROW_INVLD_ARG(); } } }; } // end ui namespace } // end gladius namespace
samuelkgutierrez/gladius
source/tool-common/tool-common.h
/* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. * * Copyright (c) 2008-2012, Lawrence Livermore National Security, LLC */ /** * Home to common infrastructure used by tool front-ends and back-ends. */ #pragma once #include "tool-common/faux-mpir.h" #include "tool-common/gladius-tli.h" #include "core/core.h" #include "core/utils.h" #include <cstring> #include <cstdint> #include <string> #include <set> #include <cstdlib> #include <ostream> #include <iostream> #include <memory> #include <limits.h> namespace gladius { namespace toolcommon { //////////////////////////////////////////////////////////////////////////////// // Types and constants. //////////////////////////////////////////////////////////////////////////////// // Timeout type. typedef int64_t timeout_t; // Constant that means "no timeout." const timeout_t unlimitedTimeout = -1; // Retry type typedef int64_t retry_t; // Constant that means "unlimited retries." const retry_t unlimitedRetries = -1; /** * */ static inline std::string genNotInPathErrString( const std::string &whatsNotInPath ) { auto msg = "It appears as if '" + whatsNotInPath + "', is not in your $PATH.\n" + "Please update your $PATH to include its location."; return msg; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// static const int GladiusFirstApplicationTag = GLADIUS_MRNET_FIRST_APP_TAG; enum MRNetCoreTags { // Tag for initial lash-up handshake. InitHandshake = GladiusFirstApplicationTag, // Tag for sending plugin info. PluginNameInfo, // Back-end plugins ready. BackEndPluginsReady, // Shutdown tag. Shutdown, // First plugin tag. FirstPluginTag }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * A struct of items and meta-data that can be transfered over-the-wire. No * complex data types, please! T should be things like: int, double, etc. */ template <class T> class TxList { // T * dupElems(size_t ne, T *es) { if (0 == ne || !es) return nullptr; auto res = (T *)calloc(ne, sizeof(T)); if (!res) GLADIUS_THROW_OOR(); (void)memmove(res, es, sizeof(T) * ne); return res; } public: // The length of the elems array. size_t nElems = 0; // Points to the element array. T *elems = nullptr; /** * */ TxList(void) : nElems(0) , elems(nullptr) { ; } /** * */ ~TxList(void) { if (elems) { free(elems); elems = nullptr; } nElems = 0; } /** * Copy constructor. */ TxList(const TxList &other) { nElems = other.nElems; elems = dupElems(nElems, other.elems); } /** * */ TxList & operator=(const TxList &other) { nElems = other.nElems; elems = dupElems(nElems, other.elems); return *this; } }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * Process table class. */ class ProcessTable { // unsigned int mNEntries = 0; // MPIR_PROCDESC_EXT *mProcTab = nullptr; /** * Allocates space for process table. */ void mAllocate(size_t nEntries) { mNEntries = nEntries; // Now that we know this, allocate the process table. mProcTab = (MPIR_PROCDESC_EXT *)calloc(nEntries, sizeof(*mProcTab)); if (!mProcTab) GLADIUS_THROW_OOR(); } /** * */ void mDeallocate(void) { if (mProcTab) { for (decltype(mNEntries) i = 0; i < mNEntries; ++i) { if (mProcTab[i].pd.executable_name) { free(mProcTab[i].pd.executable_name); } if (mProcTab[i].pd.host_name) { free(mProcTab[i].pd.host_name); } } free(mProcTab); mProcTab = nullptr; } mNEntries = 0; } /** * */ static MPIR_PROCDESC_EXT * dupMPIRProcDescExt( unsigned int nEntries, MPIR_PROCDESC_EXT *from ) { if (!from || 0 == nEntries) return nullptr; MPIR_PROCDESC_EXT *res = nullptr; res = (MPIR_PROCDESC_EXT *)calloc(nEntries, sizeof(*res)); if (!res) GLADIUS_THROW_OOR(); for (decltype(nEntries) i = 0; i < nEntries; ++i) { res[i].cnodeid = from[i].cnodeid; res[i].mpirank = from[i].mpirank; res[i].pd.pid = from[i].pd.pid; if (from[i].pd.host_name) { res[i].pd.host_name = strdup(from[i].pd.host_name); if (!res[i].pd.host_name) GLADIUS_THROW_OOR(); } if (from[i].pd.executable_name) { res[i].pd.executable_name = strdup(from[i].pd.executable_name); if (!res[i].pd.executable_name) GLADIUS_THROW_OOR(); } } return res; } public: /** * Constructors. */ ProcessTable(size_t nEntries) { mAllocate(nEntries); } // ProcessTable(void) : mNEntries(0) , mProcTab(nullptr) { ; } /** * Copy constructor. */ ProcessTable( const ProcessTable &other ) { mNEntries = other.mNEntries; mProcTab = dupMPIRProcDescExt(mNEntries, other.mProcTab); } /** * Destructor. */ ~ProcessTable(void) { mDeallocate(); } /** * */ ProcessTable & operator=( const ProcessTable &other ) { mNEntries = other.mNEntries; mProcTab = dupMPIRProcDescExt(mNEntries, other.mProcTab); return *this; } // void dumpTo( std::ostream &os, const std::string &outPrefix = "", core::colors::Color color = core::colors::Color::NONE ) const; /** * Returns the number of entries in the process table. */ size_t nEntries(void) const { return mNEntries; }; /** * Returns pointer to the process table. */ MPIR_PROCDESC_EXT * procTab(void) { return mProcTab; } /** * Returns a set of node (host) names. */ std::set<std::string> hostNamesInTable(void) const { std::set<std::string> nameSet; for (decltype(mNEntries) te = 0; te < mNEntries; ++te) { nameSet.insert(mProcTab[te].pd.host_name); } return nameSet; } }; } // end namespace } // end namespace
samuelkgutierrez/gladius
source/tool-common/faux-mpir.h
<reponame>samuelkgutierrez/gladius<filename>source/tool-common/faux-mpir.h /* * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. * * Copyright (c) 2008-2012, Lawrence Livermore National Security, LLC */ /** * Home to convenient structures in MPIR land that are mimicked here. */ #pragma once #ifdef __cplusplus extern "C" { #endif typedef struct { char *host_name; /* Something we can pass to inet_addr */ char *executable_name; /* The name of the image */ int pid; /* The pid of the process */ } MPIR_PROCDESC; typedef struct { MPIR_PROCDESC pd; int mpirank; int cnodeid; } MPIR_PROCDESC_EXT; #ifdef __cplusplus } #endif
samuelkgutierrez/gladius
source/mrnet/filters/core-filters.h
<filename>source/mrnet/filters/core-filters.h /** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef GLADIUS_MRNET_FILTERS_CORE_FILTERS_H_INCLUDED #define GLADIUS_MRNET_FILTERS_CORE_FILTERS_H_INCLUDED #include "mrnet/Types.h" #define GladiusMRNetProtoFilterMagic 87560 #endif
samuelkgutierrez/gladius
source/timeline/proc-timeline.h
<filename>source/timeline/proc-timeline.h /** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef TIMELINE_PROC_TIMELINE_H_INCLUDED #define TIMELINE_PROC_TIMELINE_H_INCLUDED #include "common.h" #include "info-types.h" #include "graph-widget.h" #include <QList> #include <QGraphicsItem> #include <QPainter> #include <QBrush> #include <QStyleOptionGraphicsItem> #include <iostream> #include <boost/icl/split_interval_map.hpp> QT_BEGIN_NAMESPACE class QRectF; class QGraphicsView; class QGraphicsLineItem; QT_END_NAMESPACE class TaskWidget; //////////////////////////////////////////////////////////////////////////////// class ProcTimeline : public QGraphicsItem { public: // ProcTimeline( const ProcDesc &procDesc, QGraphicsView *parent ); // QRectF boundingRect(void) const Q_DECL_OVERRIDE; // void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget ) Q_DECL_OVERRIDE; // void addTask(const TaskInfo &info); // void setTaskColorPalette(const QList<QColor> &colorPalette) { mColorPalette = colorPalette; } // void propagatePositionUpdate(void); private: // ProcDesc mProcDesc; // qreal mMaxX = 0.0; // QGraphicsView *mView = nullptr; // QList<TaskWidget *> mTaskWidgets; // QList<QColor> mColorPalette; // A map of time intervals (in ustime_t) and number of overlaps at // a given interval. Inclusive, so no overlap is not 0, it's 1. boost::icl::split_interval_map<ustime_t, uint32_t> mTimeIntervals; // Since mTimeIntervalMap is inclusive, 1 is the minimum level. static constexpr uint16_t sMinTaskLevel = 1; // If the number of concurrent threads exceeds 2^16, then wow... uint16_t mCurrentMaxTaskLevel = 0; // GraphWidget * mGraphWidget(void) const { return static_cast<GraphWidget *>(mView); } }; //////////////////////////////////////////////////////////////////////////////// class TaskWidget : public QGraphicsItem { public: TaskWidget( const TaskInfo &info, const ProcDesc &execResource, uint16_t level, qreal zVal, ProcTimeline *timeline ) : mInfo(info) , mExecResource(execResource) , mLevel(level) , mZValueStash(zVal) , mWidth((mInfo.uStopTime - mInfo.uStartTime) / sMicroSecPerPixel) , mColor(Qt::gray /* Default Color */) , mLightColor(mColor.light(sLightness)) { static const QString us = ' ' + QChar(0x03BC) + 's'; // setPos(mInfo.uStartTime / sMicroSecPerPixel, timeline->pos().y()); // setFlags(ItemIsSelectable); // setAcceptHoverEvents(true); // TODO Add Cache const auto durationInUs = mInfo.uStopTime - mInfo.uStartTime; const auto durationInS = float(durationInUs) / 1e6; const QString toolTip = "Name: " + QString("TODO") + "\nExecuted on: " + Common::procType2QString(mExecResource.kind) + ' ' + QString::number(mExecResource.procID) + "\nStart: " + QString::number(mInfo.uStartTime) + us + "\nEnd: " + QString::number(mInfo.uStopTime) + us + "\nDuration: " + QString::number(durationInS, 'f', 1) + " s (" + QString::number(durationInUs) + us + ')'; setToolTip(toolTip); } // QRectF boundingRect(void) const Q_DECL_OVERRIDE { return QRectF(0, 0, mWidth, sHeight); } // void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget * /* widget */) Q_DECL_OVERRIDE { const bool selected = option->state & QStyle::State_Selected; // const QColor penColor = selected ? mColor : mLightColor; const QColor fillColor = selected ? mLightColor : mColor; // Bring foward if selected. if (selected) setZValue(sMaxZVal); else setZValue(mZValueStash); // painter->setPen(penColor); painter->setBrush(fillColor); painter->drawRect(boundingRect()); } // ustime_t getCreateTime(void) const { return mInfo.uCreateTime; } // ustime_t getReadyTime(void) const { return mInfo.uReadyTime; } // ustime_t getStartTime(void) const { return mInfo.uStartTime; } // ustime_t getStopTime(void) const { return mInfo.uStopTime; } // void setFillColor(const QColor &color) { mColor = color; mLightColor = mColor.light(sLightness); } // static qreal getHeight(void) { return sHeight; } // uint16_t getLevel(void) const { return mLevel; } // void updateZValue(qreal newZVal) { mZValueStash = newZVal; setZValue(mZValueStash); } private: TaskInfo mInfo; // ProcDesc mExecResource; // uint16_t mLevel = 0; // qreal mZValueStash = 0.0; // qreal mWidth = 0.0; // static constexpr qreal sHeight = 30; // static constexpr int sLightness = 128; // static constexpr qreal sMaxZVal = 10.0; // QColor mColor; // QColor mLightColor; }; #endif // TIMELINE_PROC_TIMELINE_H_INCLUDED
samuelkgutierrez/gladius
source/mrnet/mrnet-be.h
<filename>source/mrnet/mrnet-be.h /** * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. * * Copyright (c) 2003-2012 <NAME>, <NAME>, <NAME> * Detailed MRNet usage rights in "LICENSE" file in the MRNet distribution. * */ #pragma once #include "tool-common/tool-common.h" #include <vector> #include <thread> // Forward declarations namespace MRN { class Network; class Stream; } namespace gladius { namespace mrnetbe { //////////////////////////////////////////////////////////////////////////////// // Container for tool thread personalities. //////////////////////////////////////////////////////////////////////////////// struct ThreadPersonality { int rank = 0; static constexpr int argc = 6; const char *argv[argc]; }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /** * Implements the MRNet interface for a tool back-end. */ class MRNetBE { private: // Constant indicating that we don't yet have a unique ID. static constexpr int sNOUID = -1; // Flag indicating whether or not we'll be verbose about our actions. bool mBeVerbose; // Our unique identifier in the parallel job. int mUID; // Total number of participants in this job. int mTargetCount; // Host's name std::string mHostName; // Absolute path to target application in which we are embedded. std::string mHostExecPath; // Host's local IP std::string mLocalIP; // std::string mSessionKey; // Pointer to connection information. toolcommon::ToolLeafInfoArrayT *mtli; // Buffers for stringified connection info. char mParentHostname[HOST_NAME_MAX]; char mParentPort[16]; char mParentRank[16]; // Handle to tool network. MRN::Network *mNet; // Tool OOB protocol stream. MRN::Stream *mProtoStream = nullptr; // Pool of tool threads. std::vector<std::thread> mToolThreads; // int mSetLocalIP(void); // int mSetSelfPath(void); // int mGetConnectionInfo(void); // int mStartToolThreads(void); // int mToolThreadMain( ThreadPersonality *tp ); // int mHandshake(void); // int mPluginInfoRecv( std::string &validPluginName, std::string &pathToValidPlugin ); public: // MRNetBE(void); // ~MRNetBE(void); // int init(bool beVerbose); // int create(int uid); // int connect(void); }; } // end mrnetbe namespace } // end gladius namespace
samuelkgutierrez/gladius
source/core/macros.h
<reponame>samuelkgutierrez/gladius /* * Copyright (c) 2014-2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "core/exception.h" #include "core/colors.h" /** * Convenience macro used for stringification. */ #define GLADIUS_STRINGIFY(x) #x #define GLADIUS_TOSTRING(x) GLADIUS_STRINGIFY(x) /** * Convenience macro used to silence warnings about unused variables. */ #define GLADIUS_UNUSED(x) \ do { \ (void)(x); \ } while (0) /** * Convenience macro for throwing an out of resource exception. */ #define GLADIUS_THROW_OOR() \ do { \ throw gladius::core::GladiusException( \ GLADIUS_WHERE, \ "Out of Resources" \ ); \ } while (0) /** * Convenience macro for throwing an exception with a given string. */ #define GLADIUS_THROW(msg) \ do { \ throw gladius::core::GladiusException( \ GLADIUS_WHERE, \ std::string(msg) \ ); \ } while (0) /** * Convenience macro for throwing an invalid argument exception. */ #define GLADIUS_THROW_INVLD_ARG() \ do { \ throw gladius::core::GladiusException( \ GLADIUS_WHERE, \ "Invalid argument detected" \ ); \ } while (0) /** * Convenience macro for throwing a call failure message. */ #define GLADIUS_THROW_CALL_FAILED(msg) \ do { \ throw gladius::core::GladiusException( \ GLADIUS_WHERE, \ "The following call failed: '" + std::string(msg) + "'." \ ); \ } while (0) /** * Convenience macro for throwing a call failure message with a numerical status * code. */ #define GLADIUS_THROW_CALL_FAILED_RC(msg, rc) \ do { \ throw gladius::core::GladiusException( \ GLADIUS_WHERE, \ "The following call failed: '" + std::string(msg) + \ "' with status code " + std::to_string(rc) + "." \ ); \ } while (0) /** * Convenience macro for printing out warning messages. */ #define GLADIUS_WARN(msg) \ do { \ using namespace gladius::core; \ std::cerr << colors::color().ansiBeginColor(colors::YELLOW) \ << "[" PACKAGE_NAME " WARNING @ " \ << __FILE__ << ": " << __LINE__ << "]: " \ << colors::color().ansiEndColor() \ << std::string(msg) << std::endl; \ } while (0) /** * Convenience macro for printing out messages to cerr; */ #define GLADIUS_CERR \ std::cerr << gladius::core::colors::color().ansiBeginColor( \ gladius::core::colors::RED \ ) \ << "[" PACKAGE_NAME "] " \ << gladius::core::colors::color().ansiEndColor() /** * Convenience macro for printing out warning messages to cerr; */ #define GLADIUS_CERR_WARN \ std::cerr << gladius::core::colors::color().ansiBeginColor( \ gladius::core::colors::YELLOW \ ) \ << "[" PACKAGE_NAME "] " \ << gladius::core::colors::color().ansiEndColor() /** * Convenience macro for printing out status messages to cout; */ #define GLADIUS_COUT_STAT \ std::cout << gladius::core::colors::color().ansiBeginColor( \ gladius::core::colors::GREEN \ ) \ << "[" PACKAGE_NAME "] " \ << gladius::core::colors::color().ansiEndColor() /** * Convenience macro for printing out component-specific status messages to * cout; The caller is able to customize (w00t) the output for their needs. */ #define GLADIUS_COMP_COUT(compName, compNameColorCode) \ std::cout << compNameColorCode \ << "[" + std::string(compName) + "] " \ << gladius::core::colors::color().ansiEndColor()
samuelkgutierrez/gladius
source/plugin/core/gladius-plugin.h
/* * Copyright (c) 2015-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * The Gladius Plugin Interface (GPI). */ #pragma once #include "core/args.h" #include "core/macros.h" #include "tool-common/tool-common.h" #include <functional> // Forward declarations. namespace MRN { class Stream; class Network; } // end namespace MRN namespace gladius { namespace gpi { /** * Update when breaking plugin ABI. */ #define GLADIUS_PLUGIN_ABI 0 /** * The plugin entry poing (symbol name). */ #define GLADIUS_PLUGIN_ENTRY_POINT GladiusPluginInfo /** * The name of the plugin entry point. */ #define GLADIUS_PLUGIN_ENTRY_POINT_NAME \ GLADIUS_TOSTRING(GLADIUS_PLUGIN_ENTRY_POINT) #define GLADIUS_PLUGIN(pluginImpl, pluginName, pluginVersion) \ extern "C" { \ /* Return pointer here because of C linkage... Sigh... */ \ gladius::gpi::GladiusPlugin * \ constructPlugin(void) { \ static pluginImpl singleton; \ return &singleton; \ } \ \ gladius::gpi::GladiusPluginInfo GLADIUS_PLUGIN_ENTRY_POINT = { \ GLADIUS_PLUGIN_ABI, \ pluginName, \ pluginVersion, \ constructPlugin \ }; \ \ } /** * A structure that hold arguments that are passed to pluginMain. */ struct GladiusPluginArgs { // std::string myHome; // gladius::core::Args appArgs; // The stream that is setup by the tool FE and handed to the plugin for use // for tool front-end <--> tool back-end protocol communication. MRN::Stream *protoStream = nullptr; // MRN::Network *network = nullptr; // GladiusPluginArgs(void) { ; } /** * */ GladiusPluginArgs( const std::string &home, const gladius::core::Args &args, MRN::Stream *protoStream, MRN::Network *mrnetNet ) : myHome(home) , appArgs(args) , protoStream(protoStream) , network(mrnetNet) { ; } /** * */ ~GladiusPluginArgs(void) = default; }; /** * The Gladius Plugin Interface (GPI) interface that plugins must * adhere to. */ class GladiusPlugin { public: /** * */ GladiusPlugin(void) = default; /** * */ virtual ~GladiusPlugin(void) = default; // virtual void pluginMain( GladiusPluginArgs &pluginArgs ) = 0; }; /** * Exposes plugin info and plugin entry point. */ struct GladiusPluginInfo { // Plugin ABI. int pluginABI; // Plugin name. const char *pluginName; // Plugin version string. const char *pluginVersion; // Plugin activation. std::function<GladiusPlugin *(void)> pluginConstruct; // GladiusPluginInfo(void) : pluginABI(0) , pluginName(nullptr) , pluginVersion(nullptr) , pluginConstruct(nullptr) { ; } // GladiusPluginInfo( int pabi, const char *pname, const char *pver, const std::function<GladiusPlugin *(void)> &pconst ) : pluginABI(pabi) , pluginName(pname) , pluginVersion(pver) , pluginConstruct(pconst) { ; } }; } // end gpi namespace } // end gladius namespace
samuelkgutierrez/gladius
source/timeline/info-types.h
<filename>source/timeline/info-types.h /** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef TIMELINE_INFO_TYPES_H_INCLUDED #define TIMELINE_INFO_TYPES_H_INCLUDED #include "common.h" #include <string> #include <deque> #include <string> #include <map> #include <stdint.h> typedef uint32_t taskid_t; typedef uint32_t funcid_t; typedef uint64_t procid_t; typedef uint64_t ustime_t; typedef uint32_t opid_t; typedef uint32_t hlrid_t; //////////////////////////////////////////////////////////////////////////////// struct TaskKind { taskid_t taskID = 0; // std::string name; // TaskKind( taskid_t taskID, const std::string &name ) : taskID(taskID) , name(name) { } }; //////////////////////////////////////////////////////////////////////////////// struct TaskInfo { taskid_t taskID = 0; // funcid_t funcID = 0; // procid_t procID = 0; // ustime_t uCreateTime = 0; // ustime_t uReadyTime = 0; // ustime_t uStartTime = 0; // ustime_t uStopTime = 0; // TaskInfo( taskid_t taskID, funcid_t funcID, procid_t procID, ustime_t uCreateTime, ustime_t uReadyTime, ustime_t uStartTime, ustime_t uStopTime ) : taskID(taskID) , funcID(funcID) , procID(procID) , uCreateTime(uCreateTime) , uReadyTime(uReadyTime) , uStartTime(uStartTime) , uStopTime(uStopTime) { } }; //////////////////////////////////////////////////////////////////////////////// struct ProcDesc { // procid_t procID = 0; // ProcType kind = ProcType::UNKNOWN; // ProcDesc( procid_t procID, ProcType kind ) : procID(procID) , kind(kind) { } }; //////////////////////////////////////////////////////////////////////////////// struct MetaDesc { // opid_t id = 0; // std::string name; // MetaDesc( opid_t id, const std::string &name ) : id(id) , name(name) { } }; //////////////////////////////////////////////////////////////////////////////// struct LegionProfData { // LegionProfData& operator=(const LegionProfData&) = delete; // Map between taskIDs to TaskKinds std::map<taskid_t, TaskKind *> taskKinds; // std::deque<TaskInfo> taskInfos; // std::deque<TaskInfo> metaInfos; // std::deque<ProcDesc> procDescs; // std::map<opid_t, MetaDesc *> metaDescs; // ~LegionProfData(void) { for (auto &taskKind : taskKinds) { delete taskKind.second; } for (auto &metaDesc: metaDescs) { delete metaDesc.second; } } // size_t nProcessors(void) const { return procDescs.size(); } // TODO add a time range for the analysis? void analyze(void) { } // std::string getAnalysisReport(void) { return ""; } }; //////////////////////////////////////////////////////////////////////////////// class Task { public: Task( const std::string &name ); private: std::string mName; }; #endif
samuelkgutierrez/gladius
source/timeline/main-window.h
<reponame>samuelkgutierrez/gladius<gh_stars>1-10 /** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef TIMELINE_MAIN_WINDOW_H_INCLUDED #define TIMELINE_MAIN_WINDOW_H_INCLUDED #include <QWidget> class MainWindow : public QWidget { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); }; #endif // TIMELINE_MAIN_WINDOW_H_INCLUDED
samuelkgutierrez/gladius
source/core/env.h
<gh_stars>1-10 /* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * Home to the environment variable registry that impact gladius' behavior. */ #pragma once #include <string> #include <vector> #include <map> /** * NOTE: Environment Variable Naming Convention: * GLADIUS_ENV_X_NAME */ /** * If this environment variable is set, then the tool front-end will be verbose * about its actions. */ #define GLADIUS_ENV_TOOL_FE_VERBOSE_NAME "GLADIUS_TOOL_FE_VERBOSE" /** * If this environment variable is set, then the tool back-end will be verbose * about its actions. */ #define GLADIUS_ENV_TOOL_BE_VERBOSE_NAME "GLADIUS_TOOL_BE_VERBOSE" /** * If this environment variable is set, then the tool back-ends will log their * output to the specified path. This assumes that all tool processes can reach * the specified path and that the path exists and is usable by each process. */ #define GLADIUS_ENV_TOOL_BE_LOG_DIR_NAME "GLADIUS_TOOL_BE_LOG_DIR" /** * If this environment variable is set, then the tool will not colorize its * terminal output. */ #define GLADIUS_ENV_NO_TERM_COLORS_NAME "GLADIUS_NO_TERM_COLORS" /** * A colon-delimited list of paths to search for Gladius plugins. */ #define GLADIUS_ENV_PLUGIN_PATH_NAME "GLADIUS_PLUGIN_PATH" /** * Name of the session's default "domain mode" (i.e. domain plugin). */ #define GLADIUS_ENV_DOMAIN_MODE_NAME "GLADIUS_DOMAIN_MODE" /** * Job session key environment variable name. */ #define GLADIUS_ENV_GLADIUS_SESSION_KEY "GLADIUS_SESSION_KEY" namespace gladius { namespace core { /** * */ struct EnvironmentVar { // The name of the environment variable. std::string envName; // A description of what the variable is and does. std::string envDesc; }; /** * */ class Environment { // std::map<std::string, std::string> mEnvVarNameCompNameMap; // std::map< std::string, std::map<std::string, EnvironmentVar> > mCompNameVarMap; /** * */ Environment(void) { ; } /** * */ ~Environment(void) { ; } public: // static Environment & TheEnvironment(void); /** * Disable copy constructor. */ Environment(const Environment &that) = delete; // Environment & operator=(const Environment &other); // size_t addToRegistry( const std::string &compName, const std::vector<EnvironmentVar> &envVars ); // void prettyPrint(void); }; } }
samuelkgutierrez/gladius
source/core/utils.h
<filename>source/core/utils.h /* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include "core/gladius-rc.h" #include "core/exception.h" #include "core/macros.h" #include <cstdlib> #include <cstring> #include <string> #include <algorithm> #include <functional> #include <cctype> #include <locale> #include <iostream> #include <errno.h> #include <limits.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <signal.h> namespace gladius { namespace core { class utils { private: // utils(void) { ; } // ~utils(void) { ; } public: /** * OS-specific path separator. */ static const std::string osPathSep; // static char ** dupArgv( int argc, const char **argv ); // static void freeDupArgv(char **dup); /** * Returns the strerror error string that corresponds to the provided errno. */ static std::string getStrError(int errNum) { return std::string(strerror(errNum)); } /** * Returns path to tmp directory. */ static std::string getTmpDir(void) { char *tmpDir = getenv("TMPDIR"); if (!tmpDir) { tmpDir = (char *)"/tmp"; } return std::string(tmpDir); } /** * Leading whitespace stripper for a given string. */ static std::string & ltrim(std::string &s) { using namespace std; s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))); return s; } /** * Trailing whitespace stripper for a given string. */ static std::string & rtrim(std::string &s) { using namespace std; s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end()); return s; } /** * Leading and trailing whitespace stripper for a given string. */ static std::string & trim(std::string &s) { return ltrim(rtrim(s)); } // static std::string getHostname(void); // static std::string getEnv(const std::string &envVarName); // static int setEnv( const std::string &envVarName, const std::string &value, bool overwrite = true ); // static int unsetEnv( const std::string &envVarName, int &errNo ); /** * Returns whether or not a given environment variable is defined. */ static bool envVarSet(const std::string &envVarName) { return (NULL != getenv(envVarName.c_str())); } /** * Returns whether or not a given path is an absolute path or not. */ static bool isAbsolutePath(std::string path) { // If the path starts with a '/', then it's absolute. return std::string(path[0], 1) == utils::osPathSep; } // static int which(std::string execName, std::string &result); /** * Returns whether or now a given file exists. */ static bool fileExists(const std::string &file) { return (0 == access(file.c_str(), F_OK)); } // static int mkDir( const std::string &path, int &errnoOnFailure ); // static int getSelfPath( std::string &maybeRes, int &errnoIfNotSuccess ); /** * */ template <typename T> static int getEnvAs( const std::string &envString, T &as, int base = 10 ) { using std::is_same; if (!envVarSet(envString)) { return GLADIUS_ENV_NOT_SET; } // Else it's set, so grab its value. auto envVal = getEnv(envString); try { if (is_same<T, int>::value) { as = std::stoi(envVal, 0, base); } else if (is_same<T, long>::value) { as = std::stol(envVal, 0, base); } else { // Type not supported. GLADIUS_THROW("Type case not implemented!"); } return GLADIUS_SUCCESS; } catch (const std::exception &e) { return GLADIUS_ERR; } } // static std::vector<std::string> strTok( const std::string &theString, const std::string &theDelimiters ); /** * */ static int sendSignal( pid_t target, int signal ) { return kill(target, signal); } /** * Returns the short hostname form from an arbitrary hostname string. * Example: Given foo.bar, returns foo */ static std::string shortHostname(const std::string &hostname) { auto chn = hostname; auto dotPos = chn.find_first_of("."); if (std::string::npos != dotPos) { chn = chn.substr(0, dotPos); } return chn; } /** * */ static std::string formatCallFailed( const std::string &inErrs, std::string fileName, int lineNo ) { const std::string lineNoStr = std::to_string(lineNo); std::string errs = "[" + fileName + ", line " + lineNoStr + "] "; errs += "A call failed that shouldn't have: "; errs += inErrs; return errs; } // static std::string base64Encode(const std::string &val); // static std::string base64Decode(const std::string &val); // static int getSizeOfFile( const std::string &file, size_t &outSize ); }; } // end core namespace } // end gladius namespace
samuelkgutierrez/gladius
source/tool-common/gladius-tli.h
/* * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * Home to connection information types. */ #pragma once #include <limits.h> namespace gladius { namespace toolcommon { extern "C" { /** * */ typedef struct ToolLeafInfoT { // TODO RM char hostName[HOST_NAME_MAX]; char parentHostName[HOST_NAME_MAX]; int rank; int parentPort; int parentRank; } ToolLeafInfoT; /** * */ typedef struct ToolLeafInfoArrayT { int size; ToolLeafInfoT *leaves; } ToolLeafInfoArrayT; } // extern "C" } // end namespace } // end namespace
samuelkgutierrez/gladius
source/timeline/common.h
<gh_stars>1-10 /** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef TIMELINE_COMMON_H #define TIMELINE_COMMON_H #include <QMetaType> #include <QString> #include <cstring> #include <stdint.h> #define APP_NAME "timeline" #define APP_WIN_TITLE "Task Execution Timeline" struct Status { // static constexpr uint8_t ok = 0; static constexpr uint8_t errors = 1; // uint8_t code; // QString errs; // Status(const QString &errs) : code(errors) , errs(errs) { } // Status( uint8_t code, const QString &errs ) : code(code) , errs(errs) { } // static Status Okay(void) { static const Status statOk(ok, "Ok"); return statOk; } // bool operator==(const Status &other) const { return other.code == this->code; } // bool operator!=(const Status &other) const { return other.code != this->code; } }; // Keep This In Sync With Legion enum ProcType { TOC_PROC, // Throughput core (GPU) LOC_PROC, // Latency core (CPU) UTIL_PROC, // Utility core IO_PROC, // I/O core PROC_GROUP, // Processor group UNKNOWN // ??? }; // enum StatusKind { INFO = 0, WARN, ERR }; Q_DECLARE_METATYPE(StatusKind); namespace Common { inline void registerMetaTypes(void) { qRegisterMetaType<StatusKind>("StatusKindType"); } // inline QString procType2QString(ProcType pType) { switch (pType) { case TOC_PROC : return "GPU"; case LOC_PROC : return "CPU"; case UTIL_PROC : return "Utility"; case IO_PROC : return "IO"; case PROC_GROUP: return "Proc Group"; case UNKNOWN : return "Unknown"; default : Q_ASSERT(false); } } } // end namespace Common static const int sMicroSecPerPixel = 1e2; #endif // TIMELINE_COMMON_H
samuelkgutierrez/gladius
source/timeline/color-palette-factory.h
<gh_stars>1-10 /** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef COLOR_PALETTE_FACTORY_H_INCLUDED #define COLOR_PALETTE_FACTORY_H_INCLUDED #include <QList> #include <QString> #include <QObject> #include <QColor> class ColorPaletteFactory { private: // ColorPaletteFactory(void) { } public: // From: https://en.wikipedia.org/wiki/Help:Distinguishable_colors static QList<QColor> getColorAlphabet(void) { static const QList<QString> colors = QList<QString>() << "#F0A3FF" << "#0075DC" << "#993F00" << "#4C005C" << "#191919" << "#005C31" << "#2BCE48" << "#FFCC99" << "#808080" << "#94FFB5" << "#8F7C00" << "#9DCC00" << "#C20088" << "#003380" << "#FFA405" << "#FFA8BB" << "#426600" << "#FF0010" << "#5EF1F2" << "#00998F" << "#E0FF66" << "#740AFF" << "#990000" << "#FFFF80" << "#FFFF00" << "#FF5005"; // QList<QColor> result; // foreach (const QString &color, colors) { result << QColor(color); } // return result; } // From: http://tools.medialab.sciences-po.fr/iwanthue/ // I forgot the settings used :-(. 64 colors. static QList<QColor> getColorAlphabet2(void) { static const QList<QString> colors = QList<QString>() << "#A06787" << "#59E240" << "#E8A22F" << "#64E2DB" << "#D14DE0" << "#3C6E3C" << "#547AD9" << "#DE412C" << "#492518" << "#D2DD80" << "#E44094" << "#D37C68" << "#C6C0DE" << "#315470" << "#978E72" << "#DAE43F" << "#903587" << "#8C2B1F" << "#DD435E" << "#50A837" << "#5BE8B0" << "#4E4586" << "#D5DBB1" << "#5A93CA" << "#4C9DA6" << "#997D22" << "#396056" << "#9266D9" << "#66E47C" << "#682452" << "#E07427" << "#28321E" << "#8EA23C" << "#CE77C3" << "#2B253D" << "#51B26F" << "#7A4A1E" << "#DDAB9E" << "#A9E063" << "#AEEAA5" << "#9FE12D" << "#50511E" << "#7A5B52" << "#9C8CD2" << "#E0A85D" << "#983948" << "#52937A" << "#E17C98" << "#9D9B9F" << "#D846BA" << "#C6DED7" << "#76C6E3" << "#D5BF38" << "#7FCAA9" << "#83A86E" << "#D9C284" << "#E0A9D3" << "#9B844C" << "#B5376F" << "#BB6232" << "#47721E" << "#511827" << "#5E445D" << "#72788B"; // QList<QColor> result; // foreach (const QString &color, colors) { result << QColor(color); } // return result; } // Adapted From: https://wiki.qt.io/Color_palette_generator static QList<QColor> getColors(uint32_t numColorsNeeded) { static const double golden_ratio = 0.618033988749895; QList<QColor> brushScale; double h = 0; const uint32_t realNumColorsNeeded = numColorsNeeded + 1; for (uint32_t i = 0; i < realNumColorsNeeded; ++i) { h = golden_ratio * 360 / realNumColorsNeeded * i; h = floor(h * 6); brushScale.append(QColor::fromHsv(int(h) % 128, 245, 230, 255)); } return brushScale; } }; #endif // COLOR_PALETTE_FACTORY_H_INCLUDED
samuelkgutierrez/gladius
source/timeline/main-frame.h
/** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef TIMELINE_MAIN_FRAME_H_INCLUDED #define TIMELINE_MAIN_FRAME_H_INCLUDED #include "info-types.h" #include <QFrame> #include <QPixmap> #include <QStackedLayout> #include <QStringList> #include <QMap> #include <QString> #include <QStringList> QT_BEGIN_NAMESPACE class QThreadPool; class QLabel; class QSlider; class QToolButton; class QTextEdit; QT_END_NAMESPACE class GraphWidget; class LegionProfLogParser; /** * @brief The View class */ class MainFrame : public QFrame { Q_OBJECT public: // explicit MainFrame(QWidget *parent = nullptr); protected: // void keyPressEvent(QKeyEvent *keyEvent) Q_DECL_OVERRIDE; private slots: // void mFitViewToScene(void); // void mSetupMatrix(void); // void mPrint(void); // void mOnStatusChange(StatusKind status, QString statusStr); // void mOnParseDone(void); // void mOnGraphStatsButtonPressed(bool pressed); // void mOnHelpButtonPressed(bool pressed); signals: void sigStatusChange(StatusKind kind, QString status); private: // Update if the order of mStackedGraphStatsLayout additions changes. enum StackedLayoutIndex { TIMELINE = 0, STATS, HELP }; // static constexpr qreal sMinZoomValue = -512.0; // static constexpr qreal sMaxZoomValue = 512.0; // static constexpr qreal sZoomKeyIncrement = 4.0; // qreal mInitZoomValue = 0.0; // QThreadPool *mThreadPool = nullptr; // qreal mZoomValue = 0; // int mNumFilesParsed = 0; // QStackedLayout *mStackedGraphStatsLayout = nullptr; // GraphWidget *mGraphWidget = nullptr; // Map between log file name and parser. QMap<QString, LegionProfLogParser *> mLegionProfLogParsers; // QLabel *mStatusLabel = nullptr; // QPixmap *mTimelinePixmap = nullptr; // QToolButton *mGraphStatsButton = nullptr; // QToolButton *mHelpButton = nullptr; // QTextEdit *mStatsTextArea = nullptr; // QTextEdit *mHelpTextArea = nullptr; // QStringList mOpenLogFiles(void); // void mParseLogFile(const QString &fileName); // void mPreProcessLogFiles(void); // void mProcessLogFiles(const QStringList &fileNames); // bool mTimelineInFocus(void) { const auto cIndex = mStackedGraphStatsLayout->currentIndex(); return StackedLayoutIndex::TIMELINE == cIndex; } // QString mGetGraphStatsButtonToolTip(bool pressed) { static const QString timelineTip = "Show Exection Timeline"; static const QString statsTip = "Show Statistics"; return (pressed ? timelineTip : statsTip); } // void mRecalibrateZoomValues( qreal targetScale ); // QStringList mGetFileNamesFromArgv(void); // void mPopulateHelpTextArea(void); }; #endif // TIMELINE_MAIN_FRAME_H_INCLUDED
samuelkgutierrez/gladius
source/ui/ui.h
<filename>source/ui/ui.h /* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include "core/args.h" namespace gladius { namespace ui { /** * Base User Interface (UI) (virtual) class. */ class UI { protected: core::Args mArgs; public: /** * */ UI(void) { ; } /** * */ virtual ~UI(void) { ; } /** * Top-level function that inits the UI. */ virtual void init(const core::Args &args) = 0; /** * Top-level function that starts the UI interaction. */ virtual void interact(void) = 0; /** * Top-level function that sends a quit request to the UI instance. Returns * true if the quit request was accepted. */ virtual bool quit(void) = 0; }; } // end ui namespace } // end gladius namespace
samuelkgutierrez/gladius
source/pty/pty.h
/* * Copyright (c) 2015-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * */ #pragma once #include <string> #include <unistd.h> namespace gladius { namespace dmi { /** * Debugger Machine Interface. */ class DMI { private: static const std::string sPromptString; // static const size_t sInitBufSize; // size_t mCurLineBufSize = 0; // bool mBeVerbose = false; // std::string mPathToGDB; // int mToGDB[2]; // int mFromGDB[2]; // PID of GDB process. pid_t mGDBPID = 0; // char *mFromGDBLineBuf = nullptr; // pid_t mTargetPID = 0; // FILE *mTo = nullptr; // FILE *mFrom = nullptr; // size_t mGetGDBRespLine(void); // void mWaitForPrompt(void); // std::string mDrainToString(void); public: // DMI(void); // ~DMI(void); // void init( bool beVerbose ); // void attach(pid_t targetPID); // int sendCommand( const std::string &rawCMD ); // int recvResp( std::string &outputIfSuccess ); }; } // end dmi namespace } // end gladius namespace #endif
samuelkgutierrez/gladius
source/tool-api/gladius-toolbe.h
/* * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * Outward facing back-end interface used by tools developers. */ #pragma once #include "core/gladius-rc.h" #include <memory> namespace gladius { namespace toolbe { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// class Tool { public: // Tool(void); // ~Tool(void); // int create( int uid, bool beVerbose = false ); // int connect(void); private: // Forward declaration of ToolBE to avoid include hell on the app side. class ToolBE; // std::unique_ptr<ToolBE> mImpl; }; } // namespace toolbe } // gladius
samuelkgutierrez/gladius
source/core/args.h
/* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #pragma once #include "core/utils.h" #include <cstdlib> #include <cstring> #include <vector> #include <string> #include <iostream> namespace gladius { namespace core { class Args { private: // int mArgC = 0; // char **mArgV = nullptr; // char **mEnv = nullptr; // void mNewArgvFrom(const std::vector<std::string> &argv) { // Free up previously allocated argv. if (mArgV) core::utils::freeDupArgv(mArgV); // mArgC = argv.size(); char **tmpArgv = (char **)calloc(mArgC, sizeof(char *)); if (!tmpArgv) GLADIUS_THROW_OOR(); for (int argi = 0; argi < mArgC; ++argi) { tmpArgv[argi] = (char *)argv[argi].c_str(); } mArgV = core::utils::dupArgv(mArgC, (const char **)tmpArgv); // Done with this free(tmpArgv); } public: /** * */ Args(void) = default; /** * */ Args(int argc, const char **argv, const char **envp = nullptr ) { mArgC = argc; mArgV = core::utils::dupArgv(argc, argv); mEnv = const_cast<char **>(envp); } /** * Same as above, just initialize from vector of strings. */ Args(const std::vector<std::string> &argv) { mNewArgvFrom(argv); } /** * Appends the argv from args to current argv of this. Leaves env untouched. */ void argvAppend(const Args &args) { // Construct new vector of args. auto a0 = toArgv(); auto a1 = args.toArgv(); a0.insert(std::end(a0), std::begin(a1), std::end(a1)); mNewArgvFrom(a0); } /** * */ ~Args(void) { mArgC = 0; if (mArgV) { core::utils::freeDupArgv(mArgV); mArgV = nullptr; } } /** * */ Args(const Args &other) { mArgC = other.mArgC; mArgV = core::utils::dupArgv(other.argc(), (const char **)other.argv()); mEnv = other.mEnv; } /** * */ Args & operator=(const Args &other) { mArgC = other.mArgC; mArgV = core::utils::dupArgv(other.argc(), (const char **)other.argv()); mEnv = other.mEnv; return *this; } /** * */ int argc(void) const { return mArgC; } /** * */ char ** argv(void) const { return mArgV; } /** * */ std::vector<std::string> toArgv(void) const { std::vector<std::string> res; for (int i = 0; i < mArgC; ++i) { res.push_back(mArgV[i]); } return res; } /** * */ char ** envp(void) const { return mEnv; } }; } // end core namespace } // end gladius namespace
samuelkgutierrez/gladius
testing/misc/interpose-mpi-start-end.c
/* * Copyright (c) 2014-2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * To Build * mpicc -o interpose-mpi-start-end.so -shared -fPIC interpose-mpi-start-end.c */ #include <stdio.h> #include <stdlib.h> #include "mpi.h" typedef struct csy_state_t { int numpe; int rank; char hostbuf[MPI_MAX_PROCESSOR_NAME]; } csy_state_t; static csy_state_t my_context; /* ////////////////////////////////////////////////////////////////////////// */ int MPI_Init(int *argc, char ***argv) { int rc = MPI_ERR_OTHER, len = 0; if (MPI_SUCCESS != (rc = PMPI_Init(argc, argv))) { perror("PMPI_Init failed"); } if (MPI_SUCCESS != (rc = MPI_Comm_size(MPI_COMM_WORLD, &my_context.numpe))) { perror("MPI_Comm_size failed"); } if (MPI_SUCCESS != (rc = MPI_Comm_rank(MPI_COMM_WORLD, &my_context.rank))) { perror("MPI_Comm_rank failed"); } if (MPI_SUCCESS != (rc = MPI_Get_processor_name(my_context.hostbuf, &len))) { perror("MPI_Get_processor_name failed"); } if (0 == my_context.rank) { fprintf(stdout, "\n@@@ %s @@@\n", __func__); } return MPI_SUCCESS; } /* ////////////////////////////////////////////////////////////////////////// */ int MPI_Abort(MPI_Comm comm, int errorcode) { fprintf(stdout, "\n\n @@@ rank %d on host %s called MPI_Abort @@@\n\n", my_context.rank, my_context.hostbuf); fflush(stdout); return PMPI_Abort(comm, errorcode); } /* ////////////////////////////////////////////////////////////////////////// */ int MPI_Finalize(void) { if (0 == my_context.rank) { fprintf(stdout, "\n@@@ %s @@@\n", __func__); } return PMPI_Finalize(); }
samuelkgutierrez/gladius
source/tool-fe/tool-fe.h
/* * Copyright (c) 2014-2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * The Front-End (FE) API. The interface to the tool actions. */ #pragma once #include "core/core.h" #include "core/process-landscape.h" #include "tool-common/tool-common.h" #include "tool-common/session-key.h" #include "dsys/palp.h" #include "dsys/dsi.h" #include "mrnet/mrnet-fe.h" #include "plugin/core/gp-manager.h" #include "plugin/core/gladius-plugin.h" #include <string> #include <thread> #include <mutex> namespace gladius { namespace toolfe { class ToolFE { private: // Flag indicating whether or not we'll be verbose about our actions. bool mBeVerbose; #if 0 // stdin copy int mStdInCopy = 0; #endif // Our distributed system interface. dsi::DSI mDSI; // Our parallel application launcher personality. dsys::AppLauncherPersonality mLauncherPersonality; // Our target process landscape. core::ProcessLandscape mProcLandscape; // Our MRNet instance. mrnetfe::MRNetFE mMRNFE; // The plugin manager. gpa::GladiusPluginManager mPluginManager; // The plugin instance pointer. gpi::GladiusPlugin *mFEPlugin = nullptr; // Target application arguments. core::Args mAppArgs; // Launcher arguments. core::Args mLauncherArgs; // Connection timeout (in seconds). toolcommon::timeout_t mConnectionTimeoutInSec; // Max number of connection retries. toolcommon::retry_t mMaxRetries; // Unique ID for a given job. toolcommon::SessionKey mSessionKey; // The path to a valid plugin pack. std::string mPathToPluginPack; // The plugin pack for our current session. gpa::GladiusPluginPack mPluginPack; // int mSetupCore(void); // int mGetStateFromEnvs(void); // int mInitializeParallelLauncher(void); // int mPreToolInitActons(void); // int mDetermineProcLandscape(void); // int mBuildNetwork(void); // std::vector <std::pair<std::string, std::string> > mForwardEnvsToBEsIfSetOnFE(void); // int mPostToolInitActons(void); // int mLaunchUserApp(void); // int mInitiateToolLashUp(void); // int mPublishConnectionInfo(void); // int mLoadPlugins(void); // int mSendPluginInfoToBEs(void); // int mEnterPluginMain(void); public: // Default timeout (in seconds) static constexpr toolcommon::timeout_t sDefaultTimeout = 30; // Default max number of retry attempts. static constexpr toolcommon::retry_t sDefaultMaxRetries = 8; // ToolFE(void); // ~ToolFE(void) = default; // int main( const core::Args &appArgv, const core::Args &launcherArgv ); // int mConnectMRNetTree(void); // static void registerComponent(void); }; // class ToolFE } // end toolfe namespace } // end gladius namespace
samuelkgutierrez/gladius
source/dsys/palp.h
/** * Copyright (c) 2016 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ /** * Implements generating launch commands for various parallel launchers like * orterun, aprun, srun, etc. */ #pragma once #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "core/core.h" #include "core/args.h" #include "core/utils.h" #include <vector> #include <string> namespace gladius { namespace dsys { class AppLauncherPersonality { public: /** * Supported launcher types. */ enum Type { ORTE, /* orte */ NONE /* none specified/unknown */ }; private: // Name of the launcher, e.g. mpirun, srun, aprun std::string mName; // Absolute that to the launcher. std::string mAbsolutePath; // The launcher "personality", i.e. what kind of launcher. Type mType; // All (original) arguments supplied to launch request. core::Args mLauncherArgs; // Arguments used to forward environment variables to remote environments. core::Args mForwardEnvArgs; public: /** * */ AppLauncherPersonality( void ) : mName("") , mAbsolutePath("") , mType(NONE) { ; } /** * */ int init(const core::Args &args) { mLauncherArgs = args; // First argument should be launcher name mName = mLauncherArgs.argv()[0]; mType = getPersonalityByName(mName); // if (dsys::AppLauncherPersonality::NONE == mType) { static const std::string errs = "Cannot determine launcher type by name: '" + mName + "'"; GLADIUS_CERR << errs << std::endl; return GLADIUS_ERR; } // auto status = core::utils::which(mName, mAbsolutePath); if (GLADIUS_SUCCESS != status) { static const std::string errs = "It appears as if " + std::string(mName) + " is either " "not installed or not in your $PATH. " " Please fix this and try again."; GLADIUS_CERR << errs << std::endl; return GLADIUS_ERR; } return GLADIUS_SUCCESS; } /** * */ ~AppLauncherPersonality(void) = default; /** * */ Type getPersonality(void) const { return mType; } /** * */ std::string getPersonalityName(void) const { switch(mType) { // TODO mpich v. open mpi's mpirun? Add a more robust check here. case (ORTE): return "orte"; case (NONE): return "none"; default: return "???"; } } /** * */ std::string which(void) const { return mAbsolutePath; } /** * */ core::Args getLaunchCMDFor( const core::Args &appArgs ) const { using namespace std; // vector<string> args = mLauncherArgs.toArgv(); vector<string> aargs = appArgs.toArgv(); args.insert(end(args), begin(aargs), end(aargs)); // return core::Args(args); } /** * Returns personality based on launcher name. */ static Type getPersonalityByName(const std::string &name) { // TODO deal with all mpiruns if ("mpirun" == name) return ORTE; else return NONE; } }; } // end gladius dsys } // end gladius namespace
samuelkgutierrez/gladius
source/timeline/legion-prof-log-parser.h
/** * Copyright (c) 2015 Triad National Security, LLC * All rights reserved. * * This file is part of the Gladius project. See the LICENSE.txt file at the * top-level directory of this distribution. */ #ifndef TIMELINE_LEGION_PROF_LOG_PARSER_H #define TIMELINE_LEGION_PROF_LOG_PARSER_H #include "common.h" #include "info-types.h" #include <QObject> #include <deque> QT_BEGIN_NAMESPACE class QString; QT_END_NAMESPACE class LegionProfLogParser : public QObject { Q_OBJECT public: LegionProfLogParser(QString file); // ~LegionProfLogParser(void); // No copy constructor. LegionProfLogParser(const LegionProfLogParser&) = delete; // No assignment. LegionProfLogParser& operator=(const LegionProfLogParser&) = delete; // const LegionProfData& results(void) const { return *mProfData; } // Status status(void) { return mStatus; } // QString getFileName(void) const { return mFileName; } public slots: // void parse(void); signals: void sigParseDone(void); private: // Status mStatus; // QString mFileName; // LegionProfData *mProfData = nullptr; // bool mParseSuccessful(void) const; }; #endif // TIMELINE_LEGION_PROF_LOG_PARSER_H
swiimii/pomegranate
Checkers/Piece.h
// // Created by coltw on 4/7/2018. // #ifndef CHECKERS_PIECE_H #define CHECKERS_PIECE_H #include <iostream> using namespace std; class Piece { private: bool isDead, isKing; int team, row, col; public: Piece(); Piece(int row, int col, int team); void display(); //bool canMove(Spot &c); void setRow(int r); void setColumn(int c); int getRow(); int getColumn(); void setKing(); void setDead(); }; #endif //CHECKERS_PIECE_H0
swiimii/pomegranate
lab9/pointers.h
#ifndef POINTERS_H #define POINTERS_H // Author: <NAME> // Source File: Pointers.h // Description: Implements a convoluted class to exercise pointers, // dynamic memory, and reference manipulations. #include <iostream> using namespace std; class Pointers { public: Pointers(){ a = 5; b = NULL; c = 10; } Pointers(int a, int* b){ this->a = a; this->b = b; c = 0; } int* getA(){ return &a; } int* getB() const{ return b; } int getC() const{ return c; } void setB(int* b){ this->b = b; } void setC(){ c = *b; } private: int a; int* b; int c; }; #endif
swiimii/pomegranate
lab9/manip.h
#ifndef MANIP_H #define MANIP_H // Author: <NAME> // Source File: manip.h // Description: A set of functions where you should manipulate // the passed parameters to change the object in a specific way, // so that Pointers_test.h passes all tests. #include "Pointers.h" // A little something to get you going void manip1(Pointers* p){ *(p->getA()) = 10; } void manip2(Pointers* p){ //(p->getA((p->getA()) - 11)); *(p->getB()) = 45; } void manip3(Pointers* p){ *(p->getB()) = *(p->getA()); } void manip4(Pointers* p, int* other){ p->setB(other); } void manip5(Pointers* p, int* other){ *(p->getB()) = 45; p->setC(); } void manip6(Pointers* p){ p->getB()[2] = 10; } void manip7(Pointers* p){ *(p->getB()) = 15; } void manip8(Pointers* p){ /*int k = 199; (*p->getB()) = k; p->setB(&k); p->setC();*/ int k = 199; p->setB(&k); p->setC(); } void manip9(Pointers* p, int* other){ //*other = 10; p->setB(other); } void manip10(Pointers* p){ int k = 199; p[5].setB(&k); p[5].setC(); } #endif
swiimii/pomegranate
lab9B/LList.h
#ifndef LLIST_H #define LLIST_H /* Linked List class that store integers, with [] operator. Uses head pointer. <NAME> September 2015 */ #include <ostream> #include <stdexcept> #define int int using namespace std; struct node_t { int data; node_t* next; }; // This implementation will use a head pointer, // allowing O(1) insertion on the front, // and O(n) on the end. class LList { public: LList(){ head = NULL; } ~LList(){ clear(); } LList(const LList& other){ // Do the same as the default constructor head = NULL; // Check if the other LList is empty if(other.head == NULL){ return; } // Not empty? Iterate through the other list // and push_back on myself. node_t* temp = other.head; while(temp){ push_back(temp->data); temp = temp->next; } } // Similar to copy constructor, but check for self // assignment, if not, clear and copy all data. LList& operator= (const LList& other){ if(this == &other){ return *this; } clear(); if(other.head == NULL){ return *this; } node_t* temp = other.head; while(temp){ push_back(temp->data); temp = temp->next; } return *this; } bool empty() const { if(head == NULL) return true; return false; } unsigned int size() const { int count = 0; node_t* curr = head; if(curr != NULL) while(curr != NULL) { curr = curr->next; count++; } return count; } void push_back(int value){ if(head == NULL){ //Empty List? head = new node_t; head->data = value; head->next = NULL; }else{ // Not empty node_t* curr = head; while(curr->next != NULL) { curr = curr->next; } curr->next = new node_t; curr->next->data = value; curr->next->next = NULL; } } void push_front(int value){ // Empty list? if(head == NULL){ head = new node_t; head->data = value; head->next = NULL; }else{ // Not empty node_t* temp = new node_t; temp->data = value; temp->next = head; head = temp; } } void pop_front(){ if(head == NULL) return; node_t* temp = head; head = head->next; delete temp; } void pop_back(){ node_t* curr = head; while(curr->next != NULL) { curr = curr->next; } delete(curr->next); curr->next = NULL; } // Overload [] operator // Return logic error if index out of bounds int& operator[](unsigned pos) const{ node_t* temp = head; while(temp != NULL && pos > 0){ temp = temp->next; pos--; } // As long as I don't have a null pointer, assign. if(pos == 0 && temp != NULL){ return temp->data; } throw logic_error("Index invalid"); } LList reverse() const { int size = LList().size(); LList myList; node_t *curr = head; if (curr != NULL) while (curr->next != NULL) { myList.push_back(curr->data); curr = curr->next; } return myList; } bool operator==(const LList& other) const { } bool operator!=(const LList& other) const { return !operator==(other); } void clear(){ node_t* last = head; while(head){ head = head->next; delete last; last = head; } // Normally you never want to change head or you'll orphan part // of the list, but in this case we are wiping the list, // so it is ok to so and saves us a variable. head = NULL; } private: node_t* head; }; // Note this function is O(n^2) because getAt is O(n) and we are // doing it n times. ostream& operator<<(ostream& out, const LList &other){ out << "["; for(unsigned int i = 0; i < other.size(); i++){ out << other[i] << ", "; } out << "]"; return out; } #endif
swiimii/pomegranate
Checkers/Game.h
<gh_stars>1-10 // // Created by swiim on 4/14/2018. // #ifndef CHECKERS_GAME_H #define CHECKERS_GAME_H #include "spot.cpp" class Game { }; #endif //CHECKERS_GAME_H
swiimii/pomegranate
Checkers/Spot.h
// // Created by swiim on 4/9/2018. // #ifndef CHECKERS_SPOT_H #define CHECKERS_SPOT_H #include <iostream> #include <vector> #include <string> #include "Piece.cpp" using namespace std; class Spot { public: Spot(); //Spot(int row, int col, Piece p); bool isOccupied(); //void assignPiece(Piece &p); int getRow(); int getColumn(); void display(); private: int row, col; //Piece occupant; }; #endif //CHECKERS_SPOT_H
moslevin/Mark3C
libs/memutil/public/memutil.h
<filename>libs/memutil/public/memutil.h /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file memutil.h \brief String and Memory manipulation module. Utility module implementing common memory and string manipulation functions, without relying on an external standard library implementation which might not be available on some toolchains, may be closed source, or may not be thread-safe. */ #ifndef __MEMUTIL_H__ #define __MEMUTIL_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "kerneldebug.h" //--------------------------------------------------------------------------- /*! \brief Token descriptor struct format */ typedef struct { const K_CHAR *pcToken; //!< Pointer to the beginning of the token string K_UCHAR ucLen; //!< Length of the token (in bytes) } Token_t; //----------------------------------------------------------------------- /*! Convert an 8-bit unsigned binary value as a hexadecimal string. \fn void DecimalToHex( K_UCHAR ucData_, char *szText_ ) \param ucData_ Value to convert into a string \param szText_ Destination string buffer (3 bytes minimum) */ void MemUtil_DecimalToHex8( K_UCHAR ucData_, char *szText_ ); void MemUtil_DecimalToHex16( K_USHORT usData_, char *szText_ ); void MemUtil_DecimalToHex32( K_ULONG ulData_, char *szText_ ); //----------------------------------------------------------------------- /*! Convert an 8-bit unsigned binary value as a decimal string. \fn void DecimalToString( K_UCHAR ucData_, char *szText_ ) \param ucData_ Value to convert into a string \param szText_ Destination string buffer (4 bytes minimum) */ void MemUtil_DecimalToString8( K_UCHAR ucData_, char *szText_ ); void MemUtil_DecimalToString16( K_USHORT usData_, char *szText_ ); void MemUtil_DecimalToString32( K_ULONG ulData_, char *szText_ ); //----------------------------------------------------------------------- /*! Compute the 8-bit addative checksum of a memory buffer. \fn K_USHORT Checksum8( const void *pvSrc_, K_USHORT usLen_ ) \param pvSrc_ Memory buffer to compute a 8-bit checksum of. \param usLen_ Length of the buffer in bytes. \return 8-bit checksum of the memory block. */ K_UCHAR MemUtil_Checksum8( const void *pvSrc_, K_USHORT usLen_ ); //----------------------------------------------------------------------- /*! Compute the 16-bit addative checksum of a memory buffer. \fn K_USHORT Checksum16( const void *pvSrc_, K_USHORT usLen_ ) \param pvSrc_ Memory buffer to compute a 16-bit checksum of. \param usLen_ Length of the buffer in bytes. \return 16-bit checksum of the memory block. */ K_USHORT MemUtil_Checksum16( const void *pvSrc_, K_USHORT usLen_ ); //----------------------------------------------------------------------- /*! Compute the length of a string in bytes. \fn K_USHORT StringLength( const char *szStr_ ) \param szStr_ Pointer to the zero-terminated string to calculate the length of \return length of the string (in bytes), not including the 0-terminator. */ K_USHORT MemUtil_StringLength( const char *szStr_ ); //----------------------------------------------------------------------- /*! Compare the contents of two zero-terminated string buffers to eachother. \fn K_BOOL CompareStrings( const char *szStr1_, const char *szStr2_ ) \param szStr1_ First string to compare \param szStr2_ Second string to compare \return true if strings match, false otherwise. */ K_BOOL MemUtil_CompareStrings( const char *szStr1_, const char *szStr2_ ); //----------------------------------------------------------------------- /*! Copy one buffer in memory into another. \fn void CopyMemory( void *pvDst_, const void *pvSrc_, K_USHORT usLen_ ) \param pvDst_ Pointer to the destination buffer \param pvSrc_ Pointer to the source buffer \param usLen_ Number of bytes to copy from source to destination */ void MemUtil_CopyMemory( void *pvDst_, const void *pvSrc_, K_USHORT usLen_ ); //----------------------------------------------------------------------- /*! Copy a string from one buffer into another. \fn void CopyString( char *szDst_, const char *szSrc_ ) \param szDst_ Pointer to the buffer to copy into \param szSrc_ Pointer to the buffer to copy data from */ void MemUtil_CopyString( char *szDst_, const char *szSrc_ ); //----------------------------------------------------------------------- /*! Search for the presence of one string as a substring within another. \fn K_SHORT StringSearch( const char *szBuffer_, const char *szPattern_ ) \param szBuffer_ Buffer to search for pattern within \param szPattern_ Pattern to search for in the buffer \return Index of the first instance of the pattern in the buffer, or -1 on no match. */ K_SHORT MemUtil_StringSearch( const char *szBuffer_, const char *szPattern_ ); //----------------------------------------------------------------------- /*! Compare the contents of two memory buffers to eachother \fn K_BOOL CompareMemory( void *pvMem1_, void *pvMem2_, K_USHORT usLen_ ) \param pvMem1_ First buffer to compare \param pvMem2_ Second buffer to compare \param usLen_ Length of buffer (in bytes) to compare \return true if the buffers match, false if they do not. */ K_BOOL MemUtil_CompareMemory( const void *pvMem1_, const void *pvMem2_, K_USHORT usLen_ ); //----------------------------------------------------------------------- /*! Initialize a buffer of memory to a specified 8-bit pattern \fn void SetMemory( void *pvDst_, K_UCHAR ucVal_, K_USHORT usLen_ ) \param pvDst_ Destination buffer to set \param ucVal_ 8-bit pattern to initialize each byte of destination with \param usLen_ Length of the buffer (in bytes) to initialize */ void MemUtil_SetMemory( void *pvDst_, K_UCHAR ucVal_, K_USHORT usLen_ ); //----------------------------------------------------------------------- /*! \brief Tokenize Function to tokenize a string based on a space delimeter. This is a non-destructive function, which populates a Token_t descriptor array. \param szBuffer_ String to tokenize \param pastTokens_ Pointer to the array of token descriptors \param ucMaxTokens_ Maximum number of tokens to parse (i.e. size of pastTokens_) \return Count of tokens parsed */ K_UCHAR MemUtil_Tokenize( const char *szBuffer_, Token_t *pastTokens_, K_UCHAR ucMaxTokens_); #endif //__MEMUTIL_H__
moslevin/Mark3C
kernel/timerlist.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file timerlist.cpp \brief Implements timer list processing algorithms, responsible for all timer tick and expiry logic. */ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #include "timerlist.h" #include "kerneltimer.h" #include "threadport.h" #include "kerneldebug.h" #include "quantum.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ TIMERLIST_C //!< File ID used in kernel trace calls #if KERNEL_USE_TIMERS //--------------------------------------------------------------------------- /*! TimerList object - a doubly-linked-list of timer objects. */ // Inherit from DoubleLinkList_t -- must be first!! static DoubleLinkList_t stTimerList; //! The time (in system clock ticks) of the next wakeup event static K_ULONG ulNextWakeup; //! Whether or not the timer is active static K_UCHAR bTimerActive; //--------------------------------------------------------------------------- void TimerList_Init(void) { bTimerActive = 0; ulNextWakeup = 0; LinkList_Init( (LinkList_t*)&stTimerList ); } //--------------------------------------------------------------------------- void TimerList_Add(Timer_t *pstListNode_) { #if KERNEL_TIMERS_TICKLESS K_BOOL bStart = 0; K_LONG lDelta; #endif CS_ENTER(); #if KERNEL_TIMERS_TICKLESS if (LinkList_GetHead( (LinkList_t*)&stTimerList ) == NULL) { bStart = 1; } #endif LinkListNode_Clear( (LinkListNode_t*)pstListNode_ ); DoubleLinkList_Add( (DoubleLinkList_t*)&stTimerList, (LinkListNode_t*)pstListNode_); // Set the initial timer value pstListNode_->ulTimeLeft = pstListNode_->ulInterval; #if KERNEL_TIMERS_TICKLESS if (!bStart) { // If the new interval is less than the amount of time remaining... lDelta = KernelTimer_TimeToExpiry() - pstListNode_->ulInterval; if (lDelta > 0) { // Set the new expiry time on the timer. ulNextWakeup = KernelTimer_SubtractExpiry((K_ULONG)lDelta); } } else { ulNextWakeup = pstListNode_->ulInterval; KernelTimer_SetExpiry(ulNextWakeup); KernelTimer_Start(); } #endif // Set the timer as active. pstListNode_->ucFlags |= TIMERLIST_FLAG_ACTIVE; CS_EXIT(); } //--------------------------------------------------------------------------- void TimerList_Remove(Timer_t *pstLinkListNode_) { CS_ENTER(); DoubleLinkList_Remove( (DoubleLinkList_t*)&stTimerList, (LinkListNode_t*)pstLinkListNode_ ); #if KERNEL_TIMERS_TICKLESS if ( LinkList_GetHead( (LinkList_t*)&stTimerList ) == NULL ) { KernelTimer_Stop(); } #endif CS_EXIT(); } //--------------------------------------------------------------------------- void TimerList_Process(void) { #if KERNEL_TIMERS_TICKLESS K_ULONG ulNewExpiry; K_ULONG ulOvertime; K_BOOL bContinue; #endif Timer_t *pstNode; Timer_t *pstPrev; #if KERNEL_USE_QUANTUM Quantum_SetInTimer(); #endif #if KERNEL_TIMERS_TICKLESS // Clear the timer and its expiry time - keep it running though KernelTimer_ClearExpiry(); do { #endif pstNode = (Timer_t*)LinkList_GetHead( (LinkList_t*)&stTimerList ); pstPrev = NULL; #if KERNEL_TIMERS_TICKLESS bContinue = 0; ulNewExpiry = MAX_TIMER_TICKS; #endif // Subtract the elapsed time interval from each active timer. while (pstNode) { // Active timers only... if (pstNode->ucFlags & TIMERLIST_FLAG_ACTIVE) { // Did the timer expire? #if KERNEL_TIMERS_TICKLESS if (pstNode->ulTimeLeft <= ulNextWakeup) #else pstNode->ulTimeLeft--; if (0 == pstNode->ulTimeLeft) #endif { // Yes - set the "callback" flag - we'll execute the callbacks later pstNode->ucFlags |= TIMERLIST_FLAG_CALLBACK; if (pstNode->ucFlags & TIMERLIST_FLAG_ONE_SHOT) { // If this was a one-shot timer, deactivate the timer. pstNode->ucFlags |= TIMERLIST_FLAG_EXPIRED; pstNode->ucFlags &= ~TIMERLIST_FLAG_ACTIVE; } else { // Reset the interval timer. //!ToDo - figure out if we need to deal with any overtime here. // I think we're good though... pstNode->ulTimeLeft = pstNode->ulInterval; #if KERNEL_TIMERS_TICKLESS // If the time remaining (plus the length of the tolerance interval) // is less than the next expiry interval, set the next expiry interval. K_ULONG ulTmp = pstNode->ulTimeLeft + pstNode->ulTimerTolerance; if (ulTmp < ulNewExpiry) { ulNewExpiry = ulTmp; } #endif } } #if KERNEL_TIMERS_TICKLESS else { // Not expiring, but determine how K_LONG to run the next timer interval for. pstNode->ulTimeLeft -= ulNextWakeup; if (pstNode->ulTimeLeft < ulNewExpiry) { ulNewExpiry = pstNode->ulTimeLeft; } } #endif } pstNode = (Timer_t*)LinkListNode_GetNext( (LinkListNode_t*)pstNode ); } // Process the expired timers callbacks. pstNode = (Timer_t*)LinkList_GetHead( (LinkList_t*)&stTimerList ); while (pstNode) { pstPrev = NULL; // If the timer expired, run the callbacks now. if (pstNode->ucFlags & TIMERLIST_FLAG_CALLBACK) { // Run the callback. these callbacks must be very fast... pstNode->pfCallback( pstNode->pstOwner, pstNode->pvData ); pstNode->ucFlags &= ~TIMERLIST_FLAG_CALLBACK; // If this was a one-shot timer, let's remove it. if (pstNode->ucFlags & TIMERLIST_FLAG_ONE_SHOT) { pstPrev = pstNode; } } pstNode = (Timer_t*)LinkListNode_GetNext( (LinkListNode_t*)pstNode ); // Remove one-shot-timers if (pstPrev) { TimerList_Remove( pstPrev ); } } #if KERNEL_TIMERS_TICKLESS // Check to see how much time has elapsed since the time we // acknowledged the interrupt... ulOvertime = KernelTimer_GetOvertime(); if( ulOvertime >= ulNewExpiry ) { ulNextWakeup = ulOvertime; bContinue = 1; } // If it's taken longer to go through this loop than would take us to // the next expiry, re-run the timing loop } while (bContinue); // This timer elapsed, but there's nothing more to do... // Turn the timer off. if (ulNewExpiry >= MAX_TIMER_TICKS) { KernelTimer_Stop(); } else { // Update the timer with the new "Next Wakeup" value, plus whatever // overtime has accumulated since the last time we called this handler ulNextWakeup = KernelTimer_SetExpiry(ulNewExpiry + ulOvertime); } #endif #if KERNEL_USE_QUANTUM Quantum_ClearInTimer(); #endif } #endif //KERNEL_USE_TIMERS
moslevin/Mark3C
kernel/public/mailbox.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file mailbox.h \brief MailBox + Envelope IPC Mechanism */ #ifndef __MAILBOX_H__ #define __MAILBOX_H__ #include "mark3cfg.h" #include "kerneltypes.h" #include "ksemaphore.h" #if KERNEL_USE_MAILBOX typedef struct { ThreadList_t clBlockList; K_USHORT usHead; //!< Current head index K_USHORT usTail; //!< Current tail index K_USHORT usCount; //!< Count of items in the mailbox volatile K_USHORT usFree; //!< Current number of free slots in the mailbox K_USHORT usElementSize; //!< Size of the objects tracked in this mailbox const void *pvBuffer; //!< Pointer to the data-buffer managed by this mailbox Semaphore_t stRecvSem; //!< Counting semaphore used to synchronize threads on the object #if KERNEL_USE_TIMEOUTS Semaphore_t stSendSem; //!< Binary semaphore for send-blocked threads. #endif } MailBox_t; /*! * \brief Init * * Initialize the mailbox object prior to its use. This must be called before * any calls can be made to the object. * * \param pvBuffer_ Pointer to the static buffer to use for the mailbox * \param usBufferSize_ Size of the mailbox buffer, in bytes * \param usElementSize_ Size of each envelope, in bytes */ void MailBox_Init( MailBox_t *pstMailBox_, void *pvBuffer_, K_USHORT usBufferSize_, K_USHORT usElementSize_ ); /*! * \brief Send * * Send an envelope to the mailbox. This safely copies the data contents of the * datastructure to the previously-initialized mailbox buffer. If there is a * thread already blocking, awaiting delivery to the mailbox, it will be unblocked * at this time. * * This method delivers the envelope at the head of the mailbox. * * \param pvData_ Pointer to the data object to send to the mailbox. * \return true - envelope was delivered, false - mailbox is full. */ bool MailBox_Send( MailBox_t *pstMailBox_, void *pvData_ ); /*! * \brief SendTail * * Send an envelope to the mailbox. This safely copies the data contents of the * datastructure to the previously-initialized mailbox buffer. If there is a * thread already blocking, awaiting delivery to the mailbox, it will be unblocked * at this time. * * This method delivers the envelope at the tail of the mailbox. * * \param pvData_ Pointer to the data object to send to the mailbox. * \return true - envelope was delivered, false - mailbox is full. */ bool MailBox_SendTail( MailBox_t *pstMailBox_, void *pvData_ ); #if KERNEL_USE_TIMEOUTS /*! * \brief Send * * Send an envelope to the mailbox. This safely copies the data contents of the * datastructure to the previously-initialized mailbox buffer. If there is a * thread already blocking, awaiting delivery to the mailbox, it will be unblocked * at this time. * * This method delivers the envelope at the head of the mailbox. * * \param pvData_ Pointer to the data object to send to the mailbox. * \param ulTimeoutMS_ Maximum time to wait for a free transmit slot * \return true - envelope was delivered, false - mailbox is full. */ bool MailBox_TimedSend( MailBox_t *pstMailBox_, void *pvData_, K_ULONG ulTimeoutMS_ ); /*! * \brief SendTail * * Send an envelope to the mailbox. This safely copies the data contents of the * datastructure to the previously-initialized mailbox buffer. If there is a * thread already blocking, awaiting delivery to the mailbox, it will be unblocked * at this time. * * This method delivers the envelope at the tail of the mailbox. * * \param pvData_ Pointer to the data object to send to the mailbox. * \param ulTimeoutMS_ Maximum time to wait for a free transmit slot * \return true - envelope was delivered, false - mailbox is full. */ bool MailBox_TimedSendTail( MailBox_t *pstMailBox_, void *pvData_, K_ULONG ulTimeoutMS_ ); #endif /*! * \brief Receive * * Read one envelope from the head of the mailbox. If the mailbox is currently * empty, the calling thread will block until an envelope is delivered. * * \param pvData_ Pointer to a buffer that will have the envelope's contents * copied into upon delivery. */ void MailBox_Receive( MailBox_t *pstMailBox_, void *pvData_ ); /*! * \brief ReceiveTail * * Read one envelope from the tail of the mailbox. If the mailbox is currently * empty, the calling thread will block until an envelope is delivered. * * \param pvData_ Pointer to a buffer that will have the envelope's contents * copied into upon delivery. */ void MailBox_ReceiveTail( MailBox_t *pstMailBox_, void *pvData_ ); #if KERNEL_USE_TIMEOUTS /*! * \brief Receive * * Read one envelope from the head of the mailbox. If the mailbox is currently * empty, the calling thread will block until an envelope is delivered, or the * specified time has elapsed without delivery. * * \param pvData_ Pointer to a buffer that will have the envelope's contents * copied into upon delivery. * \param ulTimeoutMS_ Maximum time to wait for delivery. * \return true - envelope was delivered, false - delivery timed out. */ bool MailBox_TimedReceive( MailBox_t *pstMailBox_, void *pvData_, K_ULONG ulTimeoutMS_ ); /*! * \brief ReceiveTail * * Read one envelope from the tail of the mailbox. If the mailbox is currently * empty, the calling thread will block until an envelope is delivered, or the * specified time has elapsed without delivery. * * \param pvData_ Pointer to a buffer that will have the envelope's contents * copied into upon delivery. * \param ulTimeoutMS_ Maximum time to wait for delivery. * \return true - envelope was delivered, false - delivery timed out. */ bool MailBox_TimedReceiveTail( MailBox_t *pstMailBox_, void *pvData_, K_ULONG ulTimeoutMS_ ); #endif K_USHORT MailBox_GetFreeSlots( MailBox_t *pstMailBox_ ); bool MailBox_IsFull( MailBox_t *pstMailBox_ ); bool MailBox_IsEmpty( MailBox_t *pstMailBox_ ); #endif #endif
moslevin/Mark3C
kernel/public/thread.h
<filename>kernel/public/thread.h<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file thread.h \brief Platform independent thread object declarations Threads are an atomic unit of execution, and each instance of the thread object represents an instance of a program running of the processor. The Thread_t is the fundmanetal user-facing object in the kernel - it is what makes multiprocessing possible from application code. In Mark3, threads each have their own context - consisting of a stack, and all of the registers required to multiplex a processor between multiple threads. The Thread_t object inherits directly from the LinkListNode_t object to facilitate efficient thread management using Double, or Double-Circular linked lists. */ #ifndef __THREAD_H__ #define __THREAD_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #include "threadlist.h" #include "scheduler.h" #include "threadport.h" #include "quantum.h" #ifdef __cplusplus extern "C" { #endif #ifndef INLINE # define INLINE extern inline #endif //--------------------------------------------------------------------------- /*! * \brief Thread_Init * * Initialize a thread prior to its use. Initialized threads are * placed in the stopped state, and are not scheduled until the * thread's start method has been invoked first. * * \param pstThread_ Pointer to the thread to initialize * \param paucStack_ Pointer to the stack to use for the thread * \param usStackSize_ Size of the stack (in bytes) * \param ucPriority_ Priority of the thread (0 = idle, 7 = max) * \param pfEntryPoint_ This is the function that gets called when the * thread is started * \param pvArg_ Pointer to the argument passed into the thread's * entrypoint function. */ void Thread_Init(Thread_t *pstThread_, K_WORD *paucStack_, K_USHORT usStackSize_, K_UCHAR ucPriority_, ThreadEntry_t pfEntryPoint_, void *pvArg_ ); //--------------------------------------------------------------------------- /*! * \brief Thread_Start * * Start the thread - remove it from the stopped list, add it to the * scheduler's list of threads (at the thread's set priority), and * continue along. * * \param pstThread_ Pointer to the thread to start */ void Thread_Start( Thread_t *pstThread_ ); //--------------------------------------------------------------------------- /*! * \brief Thread_Stop * * Stop a thread that's actively scheduled without destroying its * stacks. Stopped threads can be restarted using the Start() API. * * \param pstThread_ Pointer to the thread to start * */ void Thread_Stop( Thread_t *pstThread_ ); #if KERNEL_USE_THREADNAME //--------------------------------------------------------------------------- /*! * \brief Thread_SetName * * Set the name of the thread - this is purely optional, but can be * useful when identifying issues that come along when multiple threads * are at play in a system. * * \param pstThread_ Pointer to the thread to modify * \param szName_ Char string containing the thread name */ #define Thread_SetName( pstThread_, szName_) ( ((Thread_t*)pstThread_)->szName = szName_ ) //--------------------------------------------------------------------------- /*! * \brief Thread_GetName * * Return back a pointer to the thread's name to the user. * * \param pstThread_ Pointer to the thread to inspect * \return Pointer to the name of the thread. If this is not set, will be NULL. */ #define Thread_GetName( pstThread_ ) ( ((Thread_t*)pstThread_)->szName ) #endif //--------------------------------------------------------------------------- /*! * \brief Thread_GetOwner * * Return the ThreadList_t where the thread belongs when it's in the * active/ready state in the scheduler. * * \param pstThread_ Pointer to the thread to access/modify * \return Pointer to the Thread_t's owner list */ #define Thread_GetOwner( pstThread_ ) ( ((Thread_t*)pstThread_)->pstOwner ) //--------------------------------------------------------------------------- /*! * \brief Thread_GetCurrent * * Return the ThreadList_t where the thread is currently located * * \param pstThread_ Pointer to the thread to access/modify * \return Pointer to the thread's current list */ #define Thread_GetCurrent( pstThread_ ) ( ((Thread_t*)pstThread_)->pstCurrent ) //--------------------------------------------------------------------------- /*! * \brief Thread_GetPriority * * Return the priority of the current thread * * \param pstThread_ Pointer to the thread to access/modify * \return Priority of the current thread */ #define Thread_GetPriority( pstThread_ ) (((Thread_t*)pstThread_)->ucPriority) //--------------------------------------------------------------------------- /*! * \brief Thread_GetCurPriority * * Return the priority of the current thread * * \param pstThread_ Pointer to the thread to access/modify * \return Priority of the current thread */ #define Thread_GetCurPriority( pstThread_ ) (((Thread_t*)pstThread_)->ucCurPriority) #if KERNEL_USE_QUANTUM //--------------------------------------------------------------------------- /*! * \brief Thread_SetQuantum * * Set the thread's round-robin execution quantum. * * \param pstThread_ Pointer to the thread to access/modify * \param usQuantu Thread's execution quantum (in milliseconds) */ #define Thread_SetQuantum( pstThread_, usQuantu ) ( ((Thread_t*)pstThread_)->usQuantum = usQuantu ) //--------------------------------------------------------------------------- /*! * \brief Thread_GetQuantum * * Get the thread's round-robin execution quantum. * * \param pstThread_ Pointer to the thread to access/modify * \return The thread's round-robin timeslice quantum */ #define Thread_GetQuantum( pstThread_ ) ( ((Thread_t*)pstThread_)->usQuantum ) #endif //--------------------------------------------------------------------------- /*! * \brief Thread_SetCurrent * \param pstThread_ Pointer to the thread to access/modify * \param pstNewList_ Pointer to the threadlist to apply thread ownership */ #define Thread_SetCurrent( pstThread_, pstNewList_ ) ( ((Thread_t*)pstThread_)->pstCurrent = pstNewList_) //--------------------------------------------------------------------------- /*! * \brief Thread_SetOwner * * Set the thread's owner to the specified thread list * * \param pstThread_ Pointer to the thread to access/modify * \param pstNewList_ Pointer to the threadlist to apply thread ownership */ #define Thread_SetOwner( pstThread_, pstNewList_ ) ( ((Thread_t*)pstThread_)->pstOwner = pstNewList_ ) //--------------------------------------------------------------------------- /*! * \brief Thread_SetPriority * * Set the priority of the Thread_t (running or otherwise) to a different * level. This activity involves re-scheduling, and must be done so * with due caution, as it may effect the determinism of the system. * * This should *always* be called from within a critical section to * prevent system issues. * * \param pstThread_ Pointer to the thread to access/modify * \param ucPriority_ */ void Thread_SetPriority( Thread_t *pstThread_, K_UCHAR ucPriority_); //--------------------------------------------------------------------------- /*! * \brief Thread_InheritPriority * * Allow the thread to run at a different priority level (temporarily) * for the purpose of avoiding priority inversions. This should * only be called from within the implementation of blocking-objects. * * \param pstThread_ Pointer to the thread to access/modify * \param ucPriority_ New Priority to boost the thread to temporarily */ void Thread_InheritPriority( Thread_t *pstThread_, K_UCHAR ucPriority_); #if KERNEL_USE_DYNAMIC_THREADS //--------------------------------------------------------------------------- /*! * \brief Thread_Exit * * Remove the thread from being scheduled again. The thread is * effectively destroyed when this occurs. This is extremely * useful for cases where a thread encounters an unrecoverable * error and needs to be restarted, or in the context of systems * where threads need to be created and destroyed dynamically. * * This must not be called on the idle thread. * * \param pstThread_ Pointer to the thread to access/modify */ void Thread_Exit( Thread_t *pstThread_ ); #endif #if KERNEL_USE_SLEEP //--------------------------------------------------------------------------- /*! * \brief Thread_Sleep * * Put the thread to sleep for the specified time (in milliseconds). * Actual time slept may be longer (but not less than) the interval specified. * * \param ulTimeMs_ Time to sleep (in ms) */ void Thread_Sleep( K_ULONG ulTimeMs_); //--------------------------------------------------------------------------- /*! * \brief Thread_USleep * * Put the thread to sleep for the specified time (in microseconds). * Actual time slept may be longer (but not less than) the interval specified. * * \param ulTimeUs_ Time to sleep (in microseconds) */ void Thread_USleep( K_ULONG ulTimeUs_); #endif //--------------------------------------------------------------------------- /*! * \brief Thread_Yield * * Yield the thread - this forces the system to call the scheduler and * determine what thread should run next. This is typically used when * threads are moved in and out of the scheduler. */ void Thread_Yield( void ); //--------------------------------------------------------------------------- /*! * \brief Thread_SetID * * Set an 8-bit ID to uniquely identify this thread. * * \param pstThread_ Pointer to the thread to access/modify * \param ucID_ 8-bit Thread_t ID, set by the user */ #define Thread_SetID( pstThread_, ucID_ ) ( ((Thread_t*)pstThread_)->ucThreadID = ucID_ ) //--------------------------------------------------------------------------- /*! * \brief Thread_GetID * * Return the 8-bit ID corresponding to this thread. * * \param pstThread_ Pointer to the thread to access/modify * \return Thread_t's 8-bit ID, set by the user */ #define Thread_GetID( pstThread_ ) ( ((Thread_t*)pstThread_)->ucThreadID ) //--------------------------------------------------------------------------- /*! * \brief Thread_GetStackSlack * * Performs a (somewhat lengthy) check on the thread stack to check the * amount of stack margin (or "slack") remaining on the stack. If you're * having problems with blowing your stack, you can run this function * at points in your code during development to see what operations * cause problems. Also useful during development as a tool to optimally * size thread stacks. * * \param pstThread_ Pointer to the thread to access/modify * \return The amount of slack (unused bytes) on the stack */ K_USHORT Thread_GetStackSlack( Thread_t *pstThread_ ); #if KERNEL_USE_EVENTFLAG //--------------------------------------------------------------------------- /*! * \brief Thread_GetEventFlagMask returns the thread's current event-flag mask, * which is used in conjunction with the EventFlag_t blocking object * type. * \param pstThread_ Pointer to the thread to access/modify * \return A copy of the thread's event flag mask */ #define Thread_GetEventFlagMask( pstThread_ ) (((Thread_t*)pstThread_)->usFlagMask) //--------------------------------------------------------------------------- /*! * \brief Thread_SetEventFlagMask Sets the active event flag bitfield mask * \param pstThread_ Pointer to the thread to access/modify * \param usMask_ Binary mask value to set for this thread */ #define Thread_SetEventFlagMask( pstThread_, usMask_ ) (((Thread_t*)pstThread_)->usFlagMask = usMask_) //--------------------------------------------------------------------------- /*! * \brief Thread_SetEventFlagMode Sets the active event flag operation mode * \param eMode_ Event flag operation mode, defines the logical operator * to apply to the event flag. */ #define Thread_SetEventFlagMode( pstThread_, eMode_ ) (((Thread_t*)pstThread_)->eFlagMode = eMode_ ) //--------------------------------------------------------------------------- /*! * \brief Thread_GetEventFlagMode Returns the thread's event flag's operating mode * \return The thread's event flag mode. */ #define Thread_GetEventFlagMode( pstThread_ ) ( ((Thread_t*)pstThread_)->eFlagMode ) #endif #if KERNEL_USE_TIMEOUTS || KERNEL_USE_SLEEP //--------------------------------------------------------------------------- /*! * \brief Thread_GetTimer * \param pstThread_ Pointer to the thread to access/modify * \return Return a pointer to the thread's timer object */ #define Thread_GetTimer( pstThread_ ) ( &((Thread_t*)pstThread_)->stTimer ) #endif #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- /*! * \brief SetExpired * * Set the status of the current blocking call on the thread. * * \param pstThread_ Pointer to the thread to access/modify * \param bExpired_ true - call expired, false - call did not expire */ #define Thread_SetExpired( pstThread_, bExpired_ ) ( ((Thread_t*)pstThread_)->bExpired = bExpired_ ) //--------------------------------------------------------------------------- /*! * \brief GetExpired * * Return the status of the most-recent blocking call on the thread. * * \param pstThread_ Pointer to the thread to access/modify * \return true - call expired, false - call did not expire */ #define Thread_GetExpired( pstThread_ ) ( ((Thread_t*)pstThread_)->bExpired ) #endif #if KERNEL_USE_IDLE_FUNC //--------------------------------------------------------------------------- /*! * \brief InitIdle Initialize this Thread_t object as the Kernel's idle * thread. There should only be one of these, maximum, in a * given system. * * \param pstThread_ Pointer to the thread to access/modify */ void Thread_InitIdle( Thread_t *pstThread_ ); #endif //--------------------------------------------------------------------------- /*! * \brief Thread_GetState Returns the current state of the thread to the * caller. Can be used to determine whether or not a thread * is ready (or running), stopped, or terminated/exit'd. * \param pstThread_ Pointer to the thread to access/modify * \return ThreadState_t representing the thread's current state */ #define Thread_GetState( pstThread_ ) ( ((Thread_t*)pstThread_)->eState ) //--------------------------------------------------------------------------- /*! * \brief Thread_SetState Set the thread's state to a new value. This * is only to be used by code within the kernel, and is not * indended for use by an end-user. * \param pstThread_ Pointer to the thread to access/modify * \param eState_ New thread state to set. */ #define Thread_SetState( pstThread_, eState_ ) ( ((Thread_t*)pstThread_)->eState = eState_ ) //--------------------------------------------------------------------------- /*! * \brief Thread_ContextSwitchSWI * * This code is used to trigger the context switch interrupt. Called * whenever the kernel decides that it is necessary to swap out the * current thread for the "next" thread. */ void Thread_ContextSwitchSWI( void ); //--------------------------------------------------------------------------- /*! * \brief Thread_SetPriorityBase * \param pstThread_ Pointer to the thread to access/modify * \param ucPriority_ */ void Thread_SetPriorityBase( Thread_t *pstThread_, K_UCHAR ucPriority_); #if KERNEL_USE_IDLE_FUNC //--------------------------------------------------------------------------- /*! If the kernel is set up to use an idle function instead of an idle thread, we use a placeholder data structure to "simulate" the effect of having an idle thread in the system. When cast to a Thread_t, this data structure will still result in GetPriority() calls being valid, which is all that is needed to support the tick-based/tickless times -- while saving a fairly decent chunk of RAM on a small micro. Note that this struct must have the same memory layout as the Thread_t object up to the last item. */ typedef struct { LinkListNode_t *next; LinkListNode_t *prev; //! Pointer to the top of the thread's stack K_WORD *pwStackTop; //! Pointer to the thread's stack K_WORD *pwStack; //! Thread_t ID K_UCHAR ucThreadID; //! Default priority of the thread K_UCHAR ucPriority; //! Current priority of the thread (priority inheritence) K_UCHAR ucCurPriority; //! Enum indicating the thread's current state ThreadState_t eState; #if KERNEL_USE_THREADNAME //! Thread_t name const K_CHAR *szName; #endif } FakeThread_t; #endif #ifdef __cplusplus } #endif #endif
moslevin/Mark3C
kernel/quantum.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file quantum.cpp \brief Thread_t Quantum Implementation for Round-Robin Scheduling */ #include "kerneltypes.h" #include "mark3cfg.h" #include "thread.h" #include "timerlist.h" #include "quantum.h" #include "kerneldebug.h" #include "kernelaware.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ QUANTUM_C //!< File ID used in kernel trace calls #if KERNEL_USE_QUANTUM //--------------------------------------------------------------------------- static volatile K_BOOL bAddQuantumTimer; // Indicates that a timer add is pending //--------------------------------------------------------------------------- static Timer_t stQuantumTimer; // The global timernodelist_t object static K_UCHAR bActive; static K_UCHAR bInTimer; //--------------------------------------------------------------------------- /*! * \brief QuantumCallback * * This is the timer callback that is invoked whenever a thread has exhausted * its current execution quantum and a new thread must be chosen from within * the same priority level. * * \param pstThread_ Pointer to the thread currently executing * \param pvData_ Unused in this context. */ static void QuantumCallback(Thread_t *pstThread_, void *pvData_) { // Validate thread pointer, check that source/destination match (it's // in its real priority list). Also check that this thread was part of // the highest-running priority level. if ( Thread_GetPriority( pstThread_ ) >= Thread_GetPriority( Scheduler_GetCurrentThread() ) ) { ThreadList_t *pstList = Thread_GetCurrent( pstThread_ ); if ( LinkList_GetHead( (LinkList_t*)pstList ) != LinkList_GetTail( (LinkList_t*)pstList ) ) { bAddQuantumTimer = true; CircularLinkList_PivotForward( (CircularLinkList_t*)pstList ); } } } //--------------------------------------------------------------------------- void Quantum_SetTimer(Thread_t *pstThread_) { Timer_SetIntervalMSeconds( &stQuantumTimer, Thread_GetQuantum( pstThread_ ) ); Timer_SetFlags( &stQuantumTimer, TIMERLIST_FLAG_ONE_SHOT ); Timer_SetData( &stQuantumTimer, NULL ); Timer_SetCallback( &stQuantumTimer, (TimerCallback_t)QuantumCallback ); Timer_SetOwner( &stQuantumTimer, pstThread_ ); } //--------------------------------------------------------------------------- void Quantum_AddThread( Thread_t *pstThread_ ) { if (bActive #if KERNEL_USE_IDLE_FUNC || (pstThread_ == Kernel_GetIdleThread()) #endif ) { return; } // If this is called from the timer callback, queue a timer add... if (bInTimer) { bAddQuantumTimer = true; return; } // If this isn't the only thread in the list. ThreadList_t *pstOwner = Thread_GetCurrent( pstThread_ ); if ( LinkList_GetHead( (LinkList_t*)pstOwner ) != LinkList_GetTail( (LinkList_t*)pstOwner ) ) { Quantum_SetTimer( pstThread_ ); TimerScheduler_Add( &stQuantumTimer ); bActive = 1; } } //--------------------------------------------------------------------------- void Quantum_RemoveThread( void ) { if (!bActive) { return; } // Cancel the current timer TimerScheduler_Remove( &stQuantumTimer ); bActive = 0; } //--------------------------------------------------------------------------- void Quantum_UpdateTimer( void ) { // If we have to re-add the quantum timer (more than 2 threads at the // high-priority level...) if (bAddQuantumTimer) { // Trigger a thread yield - this will also re-schedule the // thread *and* reset the round-robin scheduler. Thread_Yield(); bAddQuantumTimer = false; } } //--------------------------------------------------------------------------- void Quantum_SetInTimer( void ) { bInTimer = true; } //--------------------------------------------------------------------------- void Quantum_ClearInTimer(void) { bInTimer = false; } #endif //KERNEL_USE_QUANTUM
moslevin/Mark3C
examples/avr/lab2_idle_function/main.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ #include "mark3.h" /*=========================================================================== Lab Example 2: Initializing the Mark3 RTOS kernel with one thread. The following example code presents a working example of how to initialize the Mark3 RTOS kernel, configured to use an application thread and the special Kernel-Idle function. This example is functionally identical to lab1, although it uses less memory as a result of only requiring one thread. This example also uses the flAVR kernel-aware module to print out messages when run through the flAVR AVR Simulator. Lessons covered in this example include: - Usage of the Kernel_SetIdleFunc() API - Changing an idle thread into an idle function - You can save a thread and a stack by using an idle function instead of a dedicated idle thread. Takeaway: The Kernel-Idle context allows you to run the Mark3 RTOS without running a dedicated idle thread (where supported). This results in a lower overall memory footprint for the application, as you can avoid having to declare a thread object and stack for Idle functionality. ===========================================================================*/ //--------------------------------------------------------------------------- // This block declares the thread data for the main application thread. It // defines a thread object, stack (in word-array form), and the entry-point // function used by the application thread. #define APP_STACK_SIZE (320/sizeof(K_WORD)) static Thread_t stAppThread; static K_WORD awAppStack[APP_STACK_SIZE]; static void AppMain(void *unused_); //--------------------------------------------------------------------------- // This block declares the special function called from with the special // Kernel-Idle context. We use the Kernel_SetIdleFunc() API to ensure that // this function is called to provide our idle context. static void IdleMain(void); //--------------------------------------------------------------------------- int main(void) { // See the annotations in lab1. Kernel_Init(); // Initialize the main application thread, as in lab1. Note that even // though we're using an Idle function and not a dedicated thread, priority // level 0 is still reserved for idle functionality. Application threads // should never be scheduled at priority level 0 when the idle function is // used instead of an idle thread. Thread_Init( &stAppThread, awAppStack, APP_STACK_SIZE, 1, AppMain, 0); Thread_Start( &stAppThread ); // This function is used to install our specified idle function to be called // whenever there are no ready threads in the system. Note that if no // Idle function is specified, a default will be used. Note that this default // function is essentially a null operation. Kernel_SetIdleFunc(IdleMain); Thread_Start( &stAppThread ); return 0; } //--------------------------------------------------------------------------- void AppMain(void *unused_) { // Same as in lab1. while(1) { KernelAware_Print("Hello World!\n"); Thread_Sleep(10); } } //--------------------------------------------------------------------------- void IdleMain(void) { // Low priority task + power management routines go here. // The actions taken in this context must *not* cause a blocking call, // similar to the requirements for an idle thread. // Note that unlike an idle thread, the idle function must run to // completion. As this is also called from a nested interrupt context, // it's worthwhile keeping this function brief, limited to absolutely // necessary functionality, and with minimal stack use. }
moslevin/Mark3C
tests/kernel_profiling/mark3test.c
<filename>tests/kernel_profiling/mark3test.c #include "kerneltypes.h" #include "mark3cfg.h" #include "kernel.h" #include "thread.h" #include "driver.h" #include "drvUART.h" #include "profile.h" #include "kernelprofile.h" #include "ksemaphore.h" #include "mutex.h" #include "message.h" #include "timerlist.h" //--------------------------------------------------------------------------- #include <avr/io.h> #include <avr/interrupt.h> #include <avr/sleep.h> //--------------------------------------------------------------------------- static volatile K_UCHAR ucTestVal; //--------------------------------------------------------------------------- static K_UCHAR aucTxBuf[32]; #define PROFILE_TEST 1 #if PROFILE_TEST //--------------------------------------------------------------------------- #define TEST_STACK1_SIZE (384) #define TEST_STACK2_SIZE (32) #define TEST_STACK3_SIZE (32) #define MAIN_STACK_SIZE (384) #define IDLE_STACK_SIZE (384) //--------------------------------------------------------------------------- static ProfileTimer_t stProfileOverhead; static ProfileTimer_t stSemInitTimer; static ProfileTimer_t stSemPostTimer; static ProfileTimer_t stSemPendTimer; static ProfileTimer_t stMutexInitTimer; static ProfileTimer_t stMutexClaimTimer; static ProfileTimer_t stMutexReleaseTimer; static ProfileTimer_t stThreadInitTimer; static ProfileTimer_t stThreadStartTimer; static ProfileTimer_t stThreadExitTimer; static ProfileTimer_t stContextSwitchTimer; static ProfileTimer_t stSemaphoreFlyback; static ProfileTimer_t stSchedulerTimer; #endif //--------------------------------------------------------------------------- static Thread_t stMainThread; static Thread_t stIdleThread; static Thread_t stTestThread1; //--------------------------------------------------------------------------- static K_UCHAR aucMainStack[MAIN_STACK_SIZE]; static K_UCHAR aucIdleStack[IDLE_STACK_SIZE]; static K_UCHAR aucTestStack1[TEST_STACK1_SIZE]; //--------------------------------------------------------------------------- static void AppMain( void *unused ); static void IdleMain( void *unused ); //--------------------------------------------------------------------------- int main(void) { Kernel_Init(); Thread_Init( &stMainThread, aucMainStack, MAIN_STACK_SIZE, 1, (ThreadEntry_t)AppMain, NULL ); Thread_Init( &stIdleThread, aucIdleStack, MAIN_STACK_SIZE, 0, (ThreadEntry_t)IdleMain, NULL ); Thread_Start( &stMainThread ); Thread_Start( &stIdleThread ); Driver_SetName( (Driver_t*) &stUART, "/dev/tty"); ATMegaUART_Init( &stUART ); DriverList_Add( (Driver_t*)&stUART ); Kernel_Start(); } //--------------------------------------------------------------------------- static void IdleMain( void *unused ) { while(1) { #if 1 // LPM code; set_sleep_mode(SLEEP_MODE_IDLE); cli(); sleep_enable(); sei(); sleep_cpu(); sleep_disable(); sei(); #endif } return 0; } //--------------------------------------------------------------------------- // Basic string routines K_USHORT KUtil_Strlen( const K_CHAR *szStr_ ) { K_CHAR *pcData = (K_CHAR*)szStr_; K_USHORT usLen = 0; while (*pcData++) { usLen++; } return usLen; } //--------------------------------------------------------------------------- void KUtil_Ultoa( K_ULONG ucData_, K_CHAR *szText_ ) { K_ULONG ucMul; K_ULONG ucMax; // Find max index to print... ucMul = 10; ucMax = 1; while (( ucMul < ucData_ ) && (ucMax < 15)) { ucMax++; ucMul *= 10; } szText_[ucMax] = 0; while (ucMax--) { szText_[ucMax] = '0' + (ucData_ % 10); ucData_/=10; } } #if PROFILE_TEST //--------------------------------------------------------------------------- static void ProfileInit() { ProfileTimer_Init( &stProfileOverhead ); ProfileTimer_Init( &stSemInitTimer ); ProfileTimer_Init( &stSemPendTimer ); ProfileTimer_Init( &stSemPostTimer ); ProfileTimer_Init( &stSemaphoreFlyback ); ProfileTimer_Init( &stMutexInitTimer ); ProfileTimer_Init( &stMutexClaimTimer ); ProfileTimer_Init( &stMutexReleaseTimer ); ProfileTimer_Init( &stThreadExitTimer ); ProfileTimer_Init( &stThreadInitTimer ); ProfileTimer_Init( &stThreadStartTimer ); ProfileTimer_Init( &stContextSwitchTimer ); ProfileTimer_Init( &stSchedulerTimer ); } //--------------------------------------------------------------------------- static void ProfileOverhead() { K_USHORT i; for (i = 0; i < 100; i++) { ProfileTimer_Start( &stProfileOverhead ); ProfileTimer_Stop( &stProfileOverhead ); } } //--------------------------------------------------------------------------- static void Semaphore_Flyback( Semaphore_t *pstSe ) { ProfileTimer_Start( &stSemaphoreFlyback ); Semaphore_Pend( pstSe ); ProfileTimer_Stop( &stSemaphoreFlyback ); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- static void Semaphore_Profiling() { Semaphore_t stSem; K_USHORT i; for (i = 0; i < 100; i++) { ProfileTimer_Start( &stSemInitTimer ); Semaphore_Init( &stSem, 0, 1000); ProfileTimer_Stop( &stSemInitTimer ); } for (i = 0; i < 100; i++) { ProfileTimer_Start( &stSemPostTimer ); Semaphore_Post( &stSem ); ProfileTimer_Stop( &stSemPostTimer ); } for (i = 0; i < 100; i++) { ProfileTimer_Start( &stSemPendTimer ); Semaphore_Pend( &stSem ); ProfileTimer_Stop( &stSemPendTimer ); } Semaphore_Init( &stSem, 0, 1); for (i = 0; i < 100; i++) { Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)Semaphore_Flyback, (void*)&stSem); Thread_Start( &stTestThread1 ); Semaphore_Post( &stSem ); } return; } //--------------------------------------------------------------------------- static void Mutex_Profiling() { K_USHORT i; Mutex_t stMutex; for (i = 0; i < 10; i++) { ProfileTimer_Start( &stMutexInitTimer ); Mutex_Init( &stMutex ); Mutex_Init( &stMutex ); Mutex_Init( &stMutex ); Mutex_Init( &stMutex ); Mutex_Init( &stMutex ); Mutex_Init( &stMutex ); Mutex_Init( &stMutex ); Mutex_Init( &stMutex ); Mutex_Init( &stMutex ); Mutex_Init( &stMutex ); ProfileTimer_Stop( &stMutexInitTimer ); } for (i = 0; i < 100; i++) { ProfileTimer_Start( &stMutexClaimTimer ); Mutex_Claim( &stMutex ); ProfileTimer_Stop( &stMutexClaimTimer ); ProfileTimer_Start( &stMutexReleaseTimer ); Mutex_Release( &stMutex ); ProfileTimer_Stop( &stMutexReleaseTimer ); } } //--------------------------------------------------------------------------- static void Thread_ProfilingThread() { // Stop the "Thread_t start" profiling timer, which was started from the // main app Thread_t ProfileTimer_Stop( &stThreadStartTimer ); // Start the "Thread_t exit" profiling timer, which will be stopped after // returning back to the main app Thread_t ProfileTimer_Start( &stThreadExitTimer ); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- static void Thread_Profiling() { K_USHORT i; for (i = 0; i < 100; i++) { // Profile the amount of time it takes to initialize a representative // test Thread_t, simulating an "average" system Thread_t. Create the // Thread_t at a higher priority than the current Thread_t. ProfileTimer_Start( &stThreadInitTimer ); Thread_Init( &stTestThread1, aucTestStack1, TEST_STACK1_SIZE, 2, (ThreadEntry_t)Thread_ProfilingThread, NULL); ProfileTimer_Stop( &stThreadInitTimer ); // Profile the time it takes from calling "start" to the time when the // Thread_t becomes active ProfileTimer_Start( &stThreadStartTimer ); Thread_Start( &stTestThread1 ); //-- Switch to the test Thread_t -- // Stop the Thread_t-exit profiling timer, which was started from the // test Thread_t ProfileTimer_Stop( &stThreadExitTimer ); } Scheduler_SetScheduler(0); for (i = 0; i < 100; i++) { // Context switch profiling - this is equivalent to what's actually // done within the AVR-implementation. ProfileTimer_Start( &stContextSwitchTimer ); { Thread_SaveContext(); g_pstNext = g_pstCurrent; Thread_RestoreContext(); } ProfileTimer_Stop( &stContextSwitchTimer ); } Scheduler_SetScheduler(1); } //--------------------------------------------------------------------------- void Scheduler_Profiling() { K_USHORT i; for (i = 0; i < 100; i++) { // Profile the scheduler. Running at priority 1, we'll get // the worst-case scheduling time (not necessarily true of all // schedulers, but true of ours). ProfileTimer_Start( &stSchedulerTimer ); Scheduler_Schedule(); ProfileTimer_Stop( &stSchedulerTimer ); } } //--------------------------------------------------------------------------- static void PrintWait( Driver_t *pstDriver_, K_USHORT usSize_, const K_CHAR *data ) { K_USHORT usWritten = 0; while (usWritten < usSize_) { usWritten += Driver_Write( pstDriver_, (usSize_ - usWritten), (K_UCHAR*)(&data[usWritten])); if (usWritten != usSize_) { Thread_Sleep(5); } } } //--------------------------------------------------------------------------- void ProfilePrint( ProfileTimer_t *pstProfile, const K_CHAR *szName_ ) { Driver_t *pstUART = DriverList_FindByPath("/dev/tty"); K_CHAR szBuf[16]; K_ULONG ulVal = ProfileTimer_GetAverage( pstProfile ) - ProfileTimer_GetAverage( &stProfileOverhead ); ulVal *= 8; int i; for( i = 0; i < 16; i++ ) { szBuf[i] = 0; } szBuf[0] = '0'; PrintWait( pstUART, KUtil_Strlen(szName_), szName_ ); PrintWait( pstUART, 2, ": " ); KUtil_Ultoa(ulVal, szBuf); PrintWait( pstUART, KUtil_Strlen(szBuf), szBuf ); PrintWait( pstUART, 1, "\n" ); } //--------------------------------------------------------------------------- void ProfilePrintResults() { ProfilePrint( &stMutexInitTimer, "MI"); ProfilePrint( &stMutexClaimTimer, "MC"); ProfilePrint( &stMutexReleaseTimer, "MR"); ProfilePrint( &stSemInitTimer, "SI"); ProfilePrint( &stSemPendTimer, "SPo"); ProfilePrint( &stSemPostTimer, "SPe"); ProfilePrint( &stSemaphoreFlyback, "SF"); ProfilePrint( &stThreadExitTimer, "TE"); ProfilePrint( &stThreadInitTimer, "TI"); ProfilePrint( &stThreadStartTimer, "TS"); ProfilePrint( &stContextSwitchTimer, "CS"); ProfilePrint( &stSchedulerTimer, "SC"); } #endif //--------------------------------------------------------------------------- static void AppMain( void *unused ) { Driver_t *pstUART = DriverList_FindByPath("/dev/tty"); #if UNIT_TEST UT_Init(); #endif #if PROFILE_TEST ProfileInit(); #endif Driver_Control( pstUART, CMD_SET_BUFFERS, 0, NULL, 32, aucTxBuf ); { K_ULONG ulBaudRate = 57600; Driver_Control( pstUART, CMD_SET_BAUDRATE, 0, &ulBaudRate, 0, 0 ); Driver_Control( pstUART, CMD_SET_RX_DISABLE, 0, 0, 0, 0); } Driver_Open( pstUART ); Driver_Write( pstUART, 6,(K_UCHAR*)"START\n"); while(1) { #if PROFILE_TEST //---[ API Profiling ]----------------------------- Profiler_Start(); ProfileOverhead(); Semaphore_Profiling(); Mutex_Profiling(); Thread_Profiling(); Scheduler_Profiling(); Profiler_Stop(); ProfilePrintResults(); Thread_Sleep(500); #endif } }
moslevin/Mark3C
kernel/ksemaphore.c
<reponame>moslevin/Mark3C<filename>kernel/ksemaphore.c /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file ksemaphore.cpp \brief Semaphore_t Blocking-Object Implemenation */ #include "kerneltypes.h" #include "mark3cfg.h" #include "ksemaphore.h" #include "blocking.h" #include "kerneldebug.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ SEMAPHORE_C //!< File ID used in kernel trace calls #if KERNEL_USE_SEMAPHORE #if KERNEL_USE_TIMEOUTS #include "timerlist.h" /*! \fn K_UCHAR WakeNext(); Wake the next thread waiting on the Semaphore_t. */ static K_UCHAR Semaphore_WakeNext( Semaphore_t *pstSe ); #if KERNEL_USE_TIMEOUTS /*! \fn void WakeMe(Thread_t *pstChosenOne_) Wake a thread blocked on the Semaphore_t. This is an internal function used for implementing timed semaphores relying on timer callbacks. Since these do not have access to the private data of the Semaphore_t and its base classes, we have to wrap this as a public method - do not use this for any other purposes. */ static void Semaphore_WakeMe( Semaphore_t *pstSe, Thread_t *pstChosenOne_); /*! * \brief Pend_i * * Internal function used to abstract timed and untimed Semaphore_t pend operations. * * \param ulWaitTimeMS_ Time in MS to wait * \return true on success, false on failure. */ static K_BOOL Semaphore_Pend_i( Semaphore_t *pstSe, K_ULONG ulWaitTimeMS_ ); #else /*! * \brief Pend_i * * Internal function used to abstract timed and untimed Semaphore_t pend operations. * */ static void Semaphore_Pend_i( Semaphore_t *pstSe ); #endif //--------------------------------------------------------------------------- /*! * \brief TimedSemaphore_Callback * * This function is called from the timer-expired context to trigger a timeout * on this semphore. This results in the waking of the thread that generated * the Semaphore_t pend call that was not completed in time. * * \param pstOwner_ Pointer to the thread to wake * \param pvData_ Pointer to the Semaphore_t object that the thread is blocked on */ void TimedSemaphore_Callback( Thread_t *pstOwner_, void *pvData_) { Semaphore_t *pstSemaphore = (Semaphore_t*)(pvData_); // Indicate that the Semaphore_t has expired on the thread Thread_SetExpired( pstOwner_, true ); // Wake up the thread that was blocked on this Semaphore_t. Semaphore_WakeMe( pstSemaphore, pstOwner_ ); if ( Thread_GetCurPriority( pstOwner_ ) >= Thread_GetCurPriority( Scheduler_GetCurrentThread() ) ) { Thread_Yield(); } } //--------------------------------------------------------------------------- void Semaphore_WakeMe( Semaphore_t *pstSe, Thread_t *pstChosenOne_ ) { // Remove from the Semaphore_t waitlist and back to its ready list. BlockingObject_UnBlock( pstChosenOne_ ); } #endif // KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- K_UCHAR Semaphore_WakeNext( Semaphore_t *pstSe ) { Thread_t *pstChosenOne; pstChosenOne = ThreadList_HighestWaiter( (ThreadList_t*)pstSe ); // Remove from the Semaphore_t waitlist and back to its ready list. BlockingObject_UnBlock( pstChosenOne ); // Call a task switch if higher or equal priority thread if ( Thread_GetCurPriority( pstChosenOne ) >= Thread_GetCurPriority( Scheduler_GetCurrentThread() ) ) { return 1; } return 0; } //--------------------------------------------------------------------------- void Semaphore_Init( Semaphore_t *pstSe, K_USHORT usInitVal_, K_USHORT usMaxVal_) { // Copy the paramters into the object - set the maximum value for this // Semaphore_t to implement either binary or counting semaphores, and set // the initial count. Clear the wait list for this object. pstSe->usValue = usInitVal_; pstSe->usMaxValue = usMaxVal_; ThreadList_Init( (ThreadList_t*)pstSe ); } //--------------------------------------------------------------------------- K_BOOL Semaphore_Post( Semaphore_t *pstSe ) { KERNEL_TRACE_1( STR_SEMAPHORE_POST_1, (K_USHORT)Thread_GetID( g_pstCurrent )); K_BOOL bThreadWake = 0; K_BOOL bBail = false; // Increment the Semaphore_t count - we can mess with threads so ensure this // is in a critical section. We don't just disable the scheudler since // we want to be able to do this from within an interrupt context as well. CS_ENTER(); // If nothing is waiting for the Semaphore_t if ( LinkList_GetHead( (LinkList_t*)pstSe ) == NULL) { // Check so see if we've reached the maximum value in the Semaphore_t if (pstSe->usValue < pstSe->usMaxValue) { // Increment the count value pstSe->usValue++; } else { // Maximum value has been reached, bail out. bBail = true; } } else { // Otherwise, there are threads waiting for the Semaphore_t to be // posted, so wake the next one (highest priority goes first). bThreadWake = Semaphore_WakeNext( pstSe ); } CS_EXIT(); // If we weren't able to increment the Semaphore_t count, fail out. if (bBail) { return false; } // if bThreadWake was set, it means that a higher-priority thread was // woken. Trigger a context switch to ensure that this thread gets // to execute next. if (bThreadWake) { Thread_Yield(); } return true; } //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS K_BOOL Semaphore_Pend_i( Semaphore_t *pstSe, K_ULONG ulWaitTimeMS_ ) #else void Semaphore_Pend_i( void ) #endif { KERNEL_TRACE_1( STR_SEMAPHORE_PEND_1, (K_USHORT)Thread_GetID( g_pstCurrent ) ); #if KERNEL_USE_TIMEOUTS Timer_t stSemTimer; K_BOOL bUseTimer = false; #endif // Once again, messing with thread data - ensure // we're doing all of these operations from within a thread-safe context. CS_ENTER(); // Check to see if we need to take any action based on the Semaphore_t count if (pstSe->usValue != 0) { // The Semaphore_t count is non-zero, we can just decrement the count // and go along our merry way. pstSe->usValue--; } else { // The Semaphore_t count is zero - we need to block the current thread // and wait until the Semaphore_t is posted from elsewhere. #if KERNEL_USE_TIMEOUTS if (ulWaitTimeMS_) { Thread_SetExpired( g_pstCurrent, false ); Timer_Init( &stSemTimer ); Timer_Start( &stSemTimer, false, ulWaitTimeMS_, TimedSemaphore_Callback, (void*)pstSe ); bUseTimer = true; } #endif BlockingObject_Block( (ThreadList_t*)pstSe, g_pstCurrent ); // Switch Threads immediately Thread_Yield(); } CS_EXIT(); #if KERNEL_USE_TIMEOUTS if (bUseTimer) { Timer_Stop( &stSemTimer ); return ( Thread_GetExpired( g_pstCurrent ) == 0); } return true; #endif } //--------------------------------------------------------------------------- // Redirect the untimed pend API to the timed pend, with a null timeout. void Semaphore_Pend( Semaphore_t *pstSe ) { #if KERNEL_USE_TIMEOUTS Semaphore_Pend_i( pstSe, 0); #else Semaphore_Pend_i( pstSe ); #endif } #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- K_BOOL Semaphore_TimedPend( Semaphore_t *pstSe, K_ULONG ulWaitTimeMS_ ) { return Semaphore_Pend_i( pstSe, ulWaitTimeMS_ ); } #endif //--------------------------------------------------------------------------- K_USHORT Semaphore_GetCount( Semaphore_t *pstSe ) { K_USHORT usRet; CS_ENTER(); usRet = pstSe->usValue; CS_EXIT(); return usRet; } #endif
moslevin/Mark3C
kernel/mailbox.c
<reponame>moslevin/Mark3C<filename>kernel/mailbox.c<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file mailbox.cpp \brief MailBox + Envelope IPC mechanism */ #include "mark3cfg.h" #include "kerneltypes.h" #include "ksemaphore.h" #include "kerneldebug.h" #include "mailbox.h" #if KERNEL_USE_MAILBOX //--------------------------------------------------------------------------- /*! * \brief GetHeadPointer * * Return a pointer to the current head of the mailbox's internal * circular buffer. * * \return pointer to the head element in the mailbox */ static void *MailBox_GetHeadPointer( MailBox_t *pstMailBox_ ) { K_ADDR uAddr = (K_ADDR)pstMailBox_->pvBuffer; uAddr += pstMailBox_->usElementSize * pstMailBox_->usHead; return (void*)uAddr; } //--------------------------------------------------------------------------- /*! * \brief GetTailPointer * * Return a pointer to the current tail of the mailbox's internal * circular buffer. * * \return pointer to the tail element in the mailbox */ static void *MailBox_GetTailPointer( MailBox_t *pstMailBox_ ) { K_ADDR uAddr = (K_ADDR)pstMailBox_->pvBuffer; uAddr += (K_ADDR)(pstMailBox_->usElementSize * pstMailBox_->usTail); return (void*)uAddr; } //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS /*! * \brief Send_i * * Internal method which implements all Send() methods in the class. * * \param pvData_ Pointer to the envelope data * \param bTail_ true - write to tail, false - write to head * \param ulWaitTimeMS_ Time to wait before timeout (in ms). * \return true - data successfully written, false - buffer full */ static bool MailBox_Send_i( MailBox_t *pstMailBox_, const void *pvData_, bool bTail_, K_ULONG ulWaitTimeMS_ ); #else /*! * \brief Send_i * * Internal method which implements all Send() methods in the class. * * \param pvData_ Pointer to the envelope data * \param bTail_ true - write to tail, false - write to head * \return true - data successfully written, false - buffer full */ static bool MailBox_Send_i( MailBox_t *pstMailBox_, const void *pvData_, bool bTail_ ); #endif //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS /*! * \brief Receive_i * * Internal method which implements all Read() methods in the class. * * \param pvData_ Pointer to the envelope data * \param bTail_ true - read from tail, false - read from head * \param ulWaitTimeMS_ Time to wait before timeout (in ms). * \return true - read successfully, false - timeout. */ static bool MailBox_Receive_i( MailBox_t *pstMailBox_, const void *pvData_, bool bTail_, K_ULONG ulWaitTimeMS_ ); #else /*! * \brief Receive_i * * Internal method which implements all Read() methods in the class. * * \param pvData_ Pointer to the envelope data * \param bTail_ true - read from tail, false - read from head */ static void MailBox_Receive_i( MailBox_t *pstMailBox_, const void *pvData_, bool bTail_ ); #endif //--------------------------------------------------------------------------- /*! * \brief CopyData * * Perform a direct byte-copy from a source to a destination object. * * \param src_ Pointer to an object to read from * \param dst_ Pointer to an object to write to * \param len_ Length to copy (in bytes) */ static void MailBox_CopyData( const void *src_, const void *dst_, K_USHORT len_ ) { uint8_t *u8Src = (uint8_t*)src_; uint8_t *u8Dst = (uint8_t*)dst_; while (len_--) { *u8Dst++ = *u8Src++; } } //--------------------------------------------------------------------------- /*! * \brief MoveTailForward * * Move the tail index forward one element */ static void MailBox_MoveTailForward( MailBox_t *pstMailBox_ ) { pstMailBox_->usTail++; if (pstMailBox_->usTail == pstMailBox_->usCount) { pstMailBox_->usTail = 0; } } //--------------------------------------------------------------------------- /*! * \brief MoveHeadForward * * Move the head index forward one element */ static void MailBox_MoveHeadForward( MailBox_t *pstMailBox_ ) { pstMailBox_->usHead++; if (pstMailBox_->usHead == pstMailBox_->usCount) { pstMailBox_->usHead = 0; } } //--------------------------------------------------------------------------- /*! * \brief MoveTailBackward * * Move the tail index backward one element */ static void MailBox_MoveTailBackward(MailBox_t *pstMailBox_ ) { if (pstMailBox_->usTail == 0) { pstMailBox_->usTail = pstMailBox_->usCount; } pstMailBox_->usTail--; } //--------------------------------------------------------------------------- /*! * \brief MoveHeadBackward * * Move the head index backward one element */ static void MailBox_MoveHeadBackward(MailBox_t *pstMailBox_ ) { if (pstMailBox_->usHead == 0) { pstMailBox_->usHead = pstMailBox_->usCount; } pstMailBox_->usHead--; } //--------------------------------------------------------------------------- void MailBox_Init( MailBox_t *pstMailBox_, void *pvBuffer_, K_USHORT usBufferSize_, K_USHORT usElementSize_ ) { KERNEL_ASSERT(usBufferSize_); KERNEL_ASSERT(usElementSize_); KERNEL_ASSERT(pvBuffer_); pstMailBox_->pvBuffer = pvBuffer_; pstMailBox_->usElementSize = usElementSize_; pstMailBox_->usCount = (usBufferSize_ / usElementSize_); pstMailBox_->usFree = pstMailBox_->usCount; pstMailBox_->usHead = 0; pstMailBox_->usTail = 0; // We use the counting semaphore to implement blocking - with one element // in the mailbox corresponding to a post/pend operation in the semaphore. Semaphore_Init( &pstMailBox_->stRecvSem, 0, pstMailBox_->usFree ); #if KERNEL_USE_TIMEOUTS // Binary semaphore is used to track any threads that are blocked on a // "send" due to lack of free slots. Semaphore_Init( &pstMailBox_->stSendSem, 0, 1 ); #endif } //--------------------------------------------------------------------------- void MailBox_Receive( MailBox_t *pstMailBox_, void *pvData_ ) { KERNEL_ASSERT( pvData_ ); #if KERNEL_USE_TIMEOUTS MailBox_Receive_i( pstMailBox_, pvData_, false, 0 ); #else MailBox_Receive_i( pstMailBox_, pvData_, false ); #endif } #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- bool MailBox_TimedReceive( MailBox_t *pstMailBox_, void *pvData_, K_ULONG ulTimeoutMS_ ) { KERNEL_ASSERT( pvData_ ); return MailBox_Receive_i( pstMailBox_, pvData_, false, ulTimeoutMS_ ); } #endif //--------------------------------------------------------------------------- void MailBox_ReceiveTail( MailBox_t *pstMailBox_, void *pvData_ ) { KERNEL_ASSERT( pvData_ ); #if KERNEL_USE_TIMEOUTS MailBox_Receive_i( pstMailBox_, pvData_, true, 0 ); #else MailBox_Receive_i( pstMailBox_, pvData_, true ); #endif } #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- bool MailBox_TimedReceiveTail( MailBox_t *pstMailBox_, void *pvData_, K_ULONG ulTimeoutMS_ ) { KERNEL_ASSERT( pvData_ ); return MailBox_Receive_i( pstMailBox_, pvData_, true, ulTimeoutMS_ ); } #endif //--------------------------------------------------------------------------- bool MailBox_Send( MailBox_t *pstMailBox_, void *pvData_ ) { KERNEL_ASSERT( pvData_ ); #if KERNEL_USE_TIMEOUTS return MailBox_Send_i( pstMailBox_, pvData_, false, 0 ); #else return MailBox_Send_i( pstMailBox_, pvData_, false ); #endif } //--------------------------------------------------------------------------- bool MailBox_SendTail( MailBox_t *pstMailBox_, void *pvData_ ) { KERNEL_ASSERT( pvData_ ); #if KERNEL_USE_TIMEOUTS return MailBox_Send_i( pstMailBox_, pvData_, true, 0 ); #else return MailBox_Send_i( pstMailBox_, pvData_, true ); #endif } #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- bool MailBox_TimedSend( MailBox_t *pstMailBox_, void *pvData_, K_ULONG ulTimeoutMS_ ) { KERNEL_ASSERT( pvData_ ); return MailBox_Send_i( pstMailBox_, pvData_, false, ulTimeoutMS_ ); } //--------------------------------------------------------------------------- bool MailBox_TimedSendTail( MailBox_t *pstMailBox_, void *pvData_, K_ULONG ulTimeoutMS_ ) { KERNEL_ASSERT( pvData_ ); return MailBox_Send_i( pstMailBox_, pvData_, true, ulTimeoutMS_ ); } #endif //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS bool MailBox_Send_i( MailBox_t *pstMailBox_, const void *pvData_, bool bTail_, K_ULONG ulTimeoutMS_) #else bool MailBox_Send_i( MailBox_t *pstMailBox_, const void *pvData_, bool bTail_) #endif { const void *pvDst; bool bRet = false; bool bSchedState = Scheduler_SetScheduler( false ); #if KERNEL_USE_TIMEOUTS bool bBlock = false; bool bDone = false; while (!bDone) { // Try to claim a slot first before resorting to blocking. if (bBlock) { bDone = true; Scheduler_SetScheduler( bSchedState ); Semaphore_TimedPend( &pstMailBox_->stSendSem, ulTimeoutMS_ ); Scheduler_SetScheduler( false ); } #endif CS_ENTER(); // Ensure we have a free slot before we attempt to write data if (pstMailBox_->usFree) { pstMailBox_->usFree--; if (bTail_) { pvDst = MailBox_GetTailPointer( pstMailBox_ ); MailBox_MoveTailBackward( pstMailBox_ ); } else { MailBox_MoveHeadForward( pstMailBox_ ); pvDst = MailBox_GetHeadPointer( pstMailBox_ ); } bRet = true; #if KERNEL_USE_TIMEOUTS bDone = true; #endif } #if KERNEL_USE_TIMEOUTS else if (ulTimeoutMS_) { bBlock = true; } else { bDone = true; } #endif CS_EXIT(); #if KERNEL_USE_TIMEOUTS } #endif // Copy data to the claimed slot, and post the counting semaphore if (bRet) { MailBox_CopyData( pvData_, pvDst, pstMailBox_->usElementSize ); } Scheduler_SetScheduler( bSchedState ); if (bRet) { Semaphore_Post( &pstMailBox_->stRecvSem ); } return bRet; } //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS bool MailBox_Receive_i( MailBox_t *pstMailBox_, const void *pvData_, bool bTail_, K_ULONG ulWaitTimeMS_ ) #else void MailBox_Receive_i( MailBox_t *pstMailBox_, const void *pvData_, bool bTail_ ) #endif { const void *pvSrc; #if KERNEL_USE_TIMEOUTS if (!Semaphore_TimedPend( &pstMailBox_->stRecvSem, ulWaitTimeMS_ )) { // Failed to get the notification from the counting semaphore in the // time allotted. Bail. return false; } #else Semaphore_Pend( &pstMailBox_->stRecvSem ); #endif // Disable the scheduler while we do this -- this ensures we don't have // multiple concurrent readers off the same queue, which could be problematic // if multiple writes occur during reads, etc. bool bSchedState = Scheduler_SetScheduler( false ); // Update the head/tail indexes, and get the associated data pointer for // the read operation. CS_ENTER(); pstMailBox_->usFree++; if (bTail_) { MailBox_MoveTailForward( pstMailBox_ ); pvSrc = MailBox_GetTailPointer( pstMailBox_ ); } else { pvSrc = MailBox_GetHeadPointer( pstMailBox_ ); MailBox_MoveHeadBackward( pstMailBox_ ); } CS_EXIT(); MailBox_CopyData( pvSrc, pvData_, pstMailBox_->usElementSize ); Scheduler_SetScheduler( bSchedState ); // Unblock a thread waiting for a free slot to send to Semaphore_Post( &pstMailBox_->stSendSem ); #if KERNEL_USE_TIMEOUTS return true; #endif } K_USHORT MailBox_GetFreeSlots( MailBox_t *pstMailBox_ ) { K_USHORT rc; CS_ENTER(); rc = pstMailBox_->usFree; CS_EXIT(); return rc; } bool MailBox_IsFull( MailBox_t *pstMailBox_ ) { return (MailBox_GetFreeSlots(pstMailBox_) == 0); } bool MailBox_IsEmpty( MailBox_t *pstMailBox_ ) { return (MailBox_GetFreeSlots(pstMailBox_) == pstMailBox_->usCount); } #endif
moslevin/Mark3C
tests/unit/ut_eventflag/ut_eventflag.c
<gh_stars>0 /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ //--------------------------------------------------------------------------- #include "kerneltypes.h" #include "kernel.h" #include "../ut_platform.h" #include "eventflag.h" #include "thread.h" #include "memutil.h" #include "driver.h" //=========================================================================== // Local Defines //=========================================================================== Thread_t stThread1; Thread_t stThread2; #define THREAD1_STACK_SIZE (256) K_WORD aucThreadStack1[THREAD1_STACK_SIZE]; #define THREAD2_STACK_SIZE (160) K_WORD aucThreadStack2[THREAD2_STACK_SIZE]; EventFlag_t stFlagGroup; volatile K_UCHAR ucFlagCount = 0; volatile K_UCHAR ucTimeoutCount = 0; //--------------------------------------------------------------------------- void WaitOnFlag1Any(void *unused_) { EventFlag_Wait( &stFlagGroup, 0x0001, EVENT_FLAG_ANY); ucFlagCount++; Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- void WaitOnMultiAny(void *unused_) { EventFlag_Wait( &stFlagGroup, 0x5555, EVENT_FLAG_ANY); ucFlagCount++; Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- void WaitOnMultiAll(void *unused_) { EventFlag_Wait( &stFlagGroup, 0x5555, EVENT_FLAG_ALL); ucFlagCount++; Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- void WaitOnAny(void *mask_) { K_USHORT usMask = *((K_USHORT*)mask_); while(1) { EventFlag_Wait( &stFlagGroup, usMask, EVENT_FLAG_ANY); ucFlagCount++; EventFlag_Clear( &stFlagGroup, usMask); } } //--------------------------------------------------------------------------- void WaitOnAll(void *mask_) { K_USHORT usMask = *((K_USHORT*)mask_); while(1) { EventFlag_Wait( &stFlagGroup, usMask, EVENT_FLAG_ALL); ucFlagCount++; EventFlag_Clear( &stFlagGroup, usMask); } } //--------------------------------------------------------------------------- void TimedWait(void *time_) { K_USHORT usRet; K_USHORT usTime = *((K_USHORT*)time_); usRet = EventFlag_TimedWait( &stFlagGroup, 0x0001, EVENT_FLAG_ALL, usTime); if (usRet == 0x0001) { ucFlagCount++; } else if (usRet == 0x0000) { ucTimeoutCount++; } EventFlag_Clear( &stFlagGroup, 0x0001); Thread_Exit( Scheduler_GetCurrentThread() ); } //--------------------------------------------------------------------------- void TimedWaitAll(void *time_) { K_USHORT usRet; K_USHORT usTime = *((K_USHORT*)time_); while(1) { usRet = EventFlag_TimedWait( &stFlagGroup, 0x0001, EVENT_FLAG_ALL, usTime ); if (usRet == 0x0001) { ucFlagCount++; } else if (usRet == 0x0000) { Thread_SetExpired( Scheduler_GetCurrentThread(), false ); ucTimeoutCount++; } EventFlag_Clear( &stFlagGroup, 0x0001); } Thread_Exit( Scheduler_GetCurrentThread() ); } //=========================================================================== // Define Test Cases Here //=========================================================================== TEST(ut_waitany) { // Test - ensure that threads can block using the "waitany" mechanism, and // only wake up when bits from its pattern are encountered. K_USHORT i; K_USHORT usMask = 0x8000; EventFlag_Init( &stFlagGroup ); ucFlagCount = 0; Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, WaitOnAny, (void*)(&usMask)); Thread_Start( &stThread1 ); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); usMask = 0x0001; while(usMask) { EventFlag_Set( &stFlagGroup, usMask); Thread_Sleep(100); if (usMask != 0x8000) { EXPECT_EQUALS(ucFlagCount, 0); } else { EXPECT_EQUALS(ucFlagCount, 1); } usMask <<= 1; } Thread_Exit( &stThread1 ); // Okay, that was a single bit-flag test. Now let's try using a multi-bit flag // and verify that any matching pattern will cause a wakeup EventFlag_Init( &stFlagGroup ); ucFlagCount = 0; usMask = 0xAAAA; Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, WaitOnAny, (void*)(&usMask)); Thread_Start( &stThread1 ); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); // Test point - the flag set should kick the test thread on even-indexed // counters indexes. for (i = 0; i < 16; i++) { K_UCHAR ucLastFlagCount = ucFlagCount; EventFlag_Set( &stFlagGroup, (K_USHORT)(1 << i)); Thread_Sleep(100); if ((i & 1) == 0) { EXPECT_EQUALS(ucFlagCount, ucLastFlagCount); } else { EXPECT_EQUALS(ucFlagCount, ucLastFlagCount+1); } } Thread_Exit( &stThread1 ); } TEST_END //=========================================================================== TEST(ut_waitall) { // Test - ensure that threads can block using the "waitany" mechanism, and // only wake up when bits from its pattern are encountered. K_USHORT i; K_USHORT usMask = 0x8000; EventFlag_Init( &stFlagGroup ); ucFlagCount = 0; Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, WaitOnAll, (void*)(&usMask)); Thread_Start( &stThread1 ); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); usMask = 0x0001; while(usMask) { EventFlag_Set( &stFlagGroup, usMask); Thread_Sleep(100); if (usMask != 0x8000) { EXPECT_EQUALS(ucFlagCount, 0); } else { EXPECT_EQUALS(ucFlagCount, 1); } usMask <<= 1; } Thread_Exit( &stThread1 ); // Okay, that was a single bit-flag test. Now let's try using a multi-bit flag // and verify that any matching pattern will cause a wakeup EventFlag_Init( &stFlagGroup ); ucFlagCount = 0; usMask = 0xAAAA; Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, WaitOnAll, (void*)(&usMask)); Thread_Start( &stThread1 ); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); // Test point - the flag set should kick the test thread on even-indexed // counters indexes. for (i = 0; i < 16; i++) { K_UCHAR ucLastFlagCount = ucFlagCount; EventFlag_Set( &stFlagGroup, (K_USHORT)(1 << i)); Thread_Sleep(100); if (i != 15) { EXPECT_EQUALS(ucFlagCount, ucLastFlagCount); } else { EXPECT_EQUALS(ucFlagCount, ucLastFlagCount+1); } } Thread_Exit( &stThread1 ); } TEST_END //--------------------------------------------------------------------------- TEST(ut_flag_multiwait) { // Test - ensure that all forms of event-flag unblocking work when there // are multiple threads blocked on the same flag. EventFlag_Init( &stFlagGroup ); // Test point - 2 threads blocking on an event flag, bit 1. Wait on these // threads until this thread sets bit 0x0001. When that bit is set, the // threads should wake up, incrementing the "ucFlagCount" variable. ucFlagCount = 0; EventFlag_Clear( &stFlagGroup, 0xFFFF); Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, WaitOnFlag1Any, 0); Thread_Init( &stThread2, aucThreadStack2, THREAD2_STACK_SIZE, 7, WaitOnFlag1Any, 0); Thread_Start( &stThread1 ); Thread_Start( &stThread2 ); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0x0001); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 2); ucFlagCount = 0; EventFlag_Clear( &stFlagGroup, 0xFFFF); // Test point - 2 threads blocking on an event flag, bits 0x5555. Block // on these threads, and verify that only bits in the pattern will cause // the threads to awaken Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, WaitOnMultiAny, 0); Thread_Init( &stThread2, aucThreadStack2, THREAD2_STACK_SIZE, 7, WaitOnMultiAny, 0); Thread_Start( &stThread1 ); Thread_Start( &stThread2 ); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0xAAAA); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0x5555); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 2); ucFlagCount = 0; EventFlag_Clear( &stFlagGroup, 0xFFFF); Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, WaitOnMultiAny, 0); Thread_Init( &stThread2, aucThreadStack2, THREAD2_STACK_SIZE, 7, WaitOnMultiAny, 0); Thread_Start( &stThread1 ); Thread_Start( &stThread2 ); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0xA000); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0x0005); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 2); // Test point - same thing as above, but with the "ALL" flags set. ucFlagCount = 0; EventFlag_Clear( &stFlagGroup, 0xFFFF); Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, WaitOnMultiAll, 0); Thread_Init( &stThread2, aucThreadStack2, THREAD2_STACK_SIZE, 7, WaitOnMultiAll, 0); Thread_Start( &stThread1 ); Thread_Start( &stThread2 ); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0xAAAA); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0x5555); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 2); ucFlagCount = 0; EventFlag_Clear( &stFlagGroup, 0xFFFF); // "All" mode - each flag must be set in order to ensure that the threads // unblock. Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, WaitOnMultiAll, 0); Thread_Init( &stThread2, aucThreadStack2, THREAD2_STACK_SIZE, 7, WaitOnMultiAll, 0); Thread_Start( &stThread1 ); Thread_Start( &stThread2 ); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0xAAAA); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0x5500); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0x0055); Thread_Sleep(100); EXPECT_EQUALS(ucFlagCount, 2); } TEST_END //=========================================================================== TEST(ut_timedwait) { K_USHORT usInterval; // Test point - verify positive test case (no timeout, no premature // unblocking) ucTimeoutCount = 0; ucFlagCount = 0; usInterval = 200; EventFlag_Init( &stFlagGroup ); Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, TimedWait, (void*)&usInterval); Thread_Start( &stThread1 ); Thread_Sleep(100); EXPECT_EQUALS(ucTimeoutCount, 0); EXPECT_EQUALS(ucFlagCount, 0); EventFlag_Set( &stFlagGroup, 0x0001); EXPECT_EQUALS(ucTimeoutCount, 0); EXPECT_EQUALS(ucFlagCount, 1); // Test point - verify negative test case (timeouts), followed by a // positive test result. ucTimeoutCount = 0; ucFlagCount = 0; usInterval = 200; EventFlag_Init( &stFlagGroup ); EventFlag_Clear( &stFlagGroup, 0xFFFF); Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, TimedWait, (void*)&usInterval); Thread_Start( &stThread1 ); Thread_Sleep(100); EXPECT_EQUALS(ucTimeoutCount, 0); EXPECT_EQUALS(ucFlagCount, 0); Thread_Sleep(200); EXPECT_EQUALS(ucTimeoutCount, 1); EXPECT_EQUALS(ucFlagCount, 0); // Test point - verify negative test case (timeouts), followed by a // positive test result. ucTimeoutCount = 0; ucFlagCount = 0; usInterval = 200; EventFlag_Init( &stFlagGroup ); EventFlag_Clear( &stFlagGroup, 0xFFFF); Thread_Init( &stThread1, aucThreadStack1, THREAD1_STACK_SIZE, 7, TimedWaitAll, (void*)&usInterval); Thread_Start( &stThread1 ); Thread_Sleep(210); EXPECT_EQUALS(ucTimeoutCount, 1); EXPECT_EQUALS(ucFlagCount, 0); Thread_Sleep(210); EXPECT_EQUALS(ucTimeoutCount, 2); EXPECT_EQUALS(ucFlagCount, 0); Thread_Sleep(210); EXPECT_EQUALS(ucTimeoutCount, 3); EXPECT_EQUALS(ucFlagCount, 0); Thread_Sleep(210); EXPECT_EQUALS(ucTimeoutCount, 4); EXPECT_EQUALS(ucFlagCount, 0); Thread_Sleep(210); EXPECT_EQUALS(ucTimeoutCount, 5); EXPECT_EQUALS(ucFlagCount, 0); Thread_Sleep(80); EventFlag_Set( &stFlagGroup, 0x0001); EXPECT_EQUALS(ucTimeoutCount, 5); EXPECT_EQUALS(ucFlagCount, 1); Thread_Sleep(80); EventFlag_Set( &stFlagGroup, 0x0001); EXPECT_EQUALS(ucTimeoutCount, 5); EXPECT_EQUALS(ucFlagCount, 2); Thread_Sleep(80); EventFlag_Set( &stFlagGroup, 0x0001); EXPECT_EQUALS(ucTimeoutCount, 5); EXPECT_EQUALS(ucFlagCount, 3); Thread_Sleep(80); EventFlag_Set( &stFlagGroup, 0x0001); EXPECT_EQUALS(ucTimeoutCount, 5); EXPECT_EQUALS(ucFlagCount, 4); Thread_Sleep(80); EventFlag_Set( &stFlagGroup, 0x0001); EXPECT_EQUALS(ucTimeoutCount, 5); EXPECT_EQUALS(ucFlagCount, 5); } TEST_END //=========================================================================== // Test Whitelist Goes Here //=========================================================================== TEST_CASE_START TEST_CASE(ut_waitany), TEST_CASE(ut_waitall), TEST_CASE(ut_flag_multiwait), TEST_CASE(ut_timedwait), TEST_CASE_END
moslevin/Mark3C
kernel/message.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file message.cpp \brief Inter-thread communications via message passing */ #include "kerneltypes.h" #include "mark3cfg.h" #include "message.h" #include "threadport.h" #include "kerneldebug.h" //--------------------------------------------------------------------------- #if defined __FILE_ID__ #undef __FILE_ID__ #endif #define __FILE_ID__ MESSAGE_C //!< File ID used in kernel trace calls #if KERNEL_USE_MESSAGE #if KERNEL_USE_TIMEOUTS #include "timerlist.h" #endif static Message_t aclMessagePool[GLOBAL_MESSAGE_POOL_SIZE]; static DoubleLinkList_t stList; #if KERNEL_USE_TIMEOUTS /*! * \brief Receive_i * * Internal function used to abstract timed and un-timed Receive calls. * * \param ulTimeWaitMS_ Time (in ms) to block, 0 for un-timed call. * * \return Pointer to a message, or 0 on timeout. */ static Message_t *MessageQueue_Receive_i( MessageQueue_t *pstMsgQ_, K_ULONG ulTimeWaitMS_ ); #else /*! * \brief Receive_i * * Internal function used to abstract Receive calls. * * \return Pointer to a message. */ static Message_t *MessageQueue_Receive_i( MessageQueue_t *pstMsgQ_ ); #endif //--------------------------------------------------------------------------- void Message_Init( Message_t* pstMsg_ ) { LinkListNode_Clear( (LinkListNode_t*)pstMsg_ ); pstMsg_->pvData = NULL; pstMsg_->usCode = 0; } //--------------------------------------------------------------------------- void Message_SetData( Message_t* pstMsg_, void *pvData_ ) { pstMsg_->pvData = pvData_; } //--------------------------------------------------------------------------- void *Message_GetData( Message_t* pstMsg_ ) { return pstMsg_->pvData; } //--------------------------------------------------------------------------- void Message_SetCode( Message_t* pstMsg_, K_USHORT usCode_ ) { pstMsg_->usCode = usCode_; } //--------------------------------------------------------------------------- K_USHORT Message_GetCode( Message_t* pstMsg_ ) { return pstMsg_->usCode; } //--------------------------------------------------------------------------- void GlobalMessagePool_Init( void ) { K_UCHAR i; DoubleLinkList_Init( &stList ); for (i = 0; i < GLOBAL_MESSAGE_POOL_SIZE; i++) { Message_Init( &aclMessagePool[i] ); DoubleLinkList_Add( &stList, (LinkListNode_t*)&aclMessagePool[i]); } } //--------------------------------------------------------------------------- void GlobalMessagePool_Push( Message_t *pstMessage_ ) { KERNEL_ASSERT( pstMessage_ ); CS_ENTER(); DoubleLinkList_Add( &stList, (LinkListNode_t*)pstMessage_ ); CS_EXIT(); } //--------------------------------------------------------------------------- Message_t *GlobalMessagePool_Pop( void ) { Message_t *pstRet; CS_ENTER(); pstRet = (Message_t*)( LinkList_GetHead( (LinkList_t*)&stList ) ); if (0 != pstRet) { DoubleLinkList_Remove( &stList, (LinkListNode_t*)pstRet ); } CS_EXIT(); return pstRet; } //--------------------------------------------------------------------------- void MessageQueue_Init( MessageQueue_t *pstMsgQ_ ) { Semaphore_Init( &(pstMsgQ_->stSemaphore), 0, GLOBAL_MESSAGE_POOL_SIZE); DoubleLinkList_Init( &(pstMsgQ_->stLinkList) ); } //--------------------------------------------------------------------------- Message_t *MessageQueue_Receive( MessageQueue_t *pstMsgQ_ ) { #if KERNEL_USE_TIMEOUTS return MessageQueue_Receive_i( pstMsgQ_, 0 ); #else return MessageQueue_Receive_i( pstMsgQ_ ); #endif } //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS Message_t *MessageQueue_TimedReceive( MessageQueue_t *pstMsgQ_, K_ULONG ulTimeWaitMS_) { return MessageQueue_Receive_i( pstMsgQ_, ulTimeWaitMS_ ); } #endif //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS Message_t *MessageQueue_Receive_i( MessageQueue_t *pstMsgQ_, K_ULONG ulTimeWaitMS_ ) #else Message_t *MessageQueue_Receive_i( MessageQueue_t *pstMsgQ_ ) #endif { Message_t *pstRet; // Block the current thread on the counting Semaphore_t #if KERNEL_USE_TIMEOUTS if ( 0 == Semaphore_TimedPend( &(pstMsgQ_->stSemaphore), ulTimeWaitMS_ ) ) { return NULL; } #else Semaphore_Pend( &(pstMsgQ_->stSemaphore) ); #endif CS_ENTER(); // Pop the head of the message queue and return it pstRet = (Message_t*)LinkList_GetHead( (LinkList_t*)&(pstMsgQ_->stLinkList) ); DoubleLinkList_Remove( (DoubleLinkList_t*)&(pstMsgQ_->stLinkList), (LinkListNode_t*)pstRet ); CS_EXIT(); return pstRet; } //--------------------------------------------------------------------------- void MessageQueue_Send( MessageQueue_t *pstMsgQ_, Message_t *pstSrc_ ) { KERNEL_ASSERT( pstSrc_ ); CS_ENTER(); // Add the message to the head of the linked list DoubleLinkList_Add( (DoubleLinkList_t*)&(pstMsgQ_->stLinkList), (LinkListNode_t*)pstSrc_ ); // Post the Semaphore_t, waking the blocking thread for the queue. Semaphore_Post( &(pstMsgQ_->stSemaphore) ); CS_EXIT(); } //--------------------------------------------------------------------------- K_USHORT MessageQueue_GetCount( MessageQueue_t *pstMsgQ_ ) { return Semaphore_GetCount( &(pstMsgQ_->stSemaphore) ); } #endif //KERNEL_USE_MESSAGE
moslevin/Mark3C
stage/src/kernelprofile.h
<reponame>moslevin/Mark3C /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file kernelprofile.h \brief Profiling timer hardware interface */ #include "kerneltypes.h" #include "mark3cfg.h" #include "ll.h" #ifndef __KPROFILE_H__ #define __KPROFILE_H__ #if KERNEL_USE_PROFILER #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- #define TICKS_PER_OVERFLOW (256) #define CLOCK_DIVIDE (8) //--------------------------------------------------------------------------- /*! System profiling timer interface */ /*! \fn void Init() Initialize the global system profiler. Must be called prior to use. */ void Profiler_Init( void ); /*! \fn void Start() Start the global profiling timer service. */ void Profiler_Start( void ); /*! \fn void Stop() Stop the global profiling timer service */ void Profiler_Stop( void ); /*! \fn K_USHORT Read() Read the current tick count in the timer. */ K_USHORT Profiler_Read( void ); /*! Process the profiling counters from ISR. */ void Profiler_Process( void ); /*! Return the current timer epoch */ K_ULONG Profiler_GetEpoch( void ); #ifdef __cplusplus } #endif #endif //KERNEL_USE_PROFILER #endif
moslevin/Mark3C
kernel/public/tracebuffer.h
<filename>kernel/public/tracebuffer.h /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file tracebuffer.h \brief Kernel trace buffer object declaration Global kernel trace-buffer. Used to instrument the kernel with lightweight encoded print statements. If something goes wrong, the tracebuffer can be examined for debugging purposes. Also, subsets of kernel trace information can be extracted and analyzed to provide information about runtime performance, thread-scheduling, and other nifty things in real-time. */ #ifndef __TRACEBUFFER_H__ #define __TRACEBUFFER_H__ #include "kerneltypes.h" #include "mark3cfg.h" #include "writebuf16.h" #if KERNEL_USE_DEBUG && !KERNEL_AWARE_SIMULATION #ifdef __cplusplus extern "C" { #endif #define TRACE_BUFFER_SIZE (16) //--------------------------------------------------------------------------- /*! \fn void TraceBuffer_Init(); Initialize the tracebuffer before use. */ void TraceBuffer_Init(); //--------------------------------------------------------------------------- /*! \fn K_USHORT TraceBuffer_Increment(); Increment the tracebuffer's atomically-incrementing index. \return a 16-bit index */ K_USHORT TraceBuffer_Increment(); //--------------------------------------------------------------------------- /*! \fn void TraceBuffer_Write( K_USHORT *pusData_, K_USHORT usSize_ ) Write a packet of data to the global tracebuffer. \param pusData_ Pointer to the source data buffer to copy to the trace buffer \param usSize_ Size of the source data buffer in 16-bit words. */ void TraceBuffer_Write( K_USHORT *pusData_, K_USHORT usSize_ ); //--------------------------------------------------------------------------- /*! \fn void TraceBuffer_SetCallback( WriteBufferCallback pfCallback_ ) Set a callback function to be triggered whenever the tracebuffer hits the 50% point, or rolls over. \param pfCallback_ Callback to assign */ void TraceBuffer_SetCallback( WriteBufferCallback pfCallback_ ); #ifdef __cplusplus } #endif #endif //KERNEL_USE_DEBUG #endif
moslevin/Mark3C
libs/memutil/memutil.c
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file memutil.cpp \brief Implementation of memory, string, and conversion routines */ #include "kerneltypes.h" #include "mark3cfg.h" #include "kerneldebug.h" #include "memutil.h" //--------------------------------------------------------------------------- void MemUtil_DecimalToHex8( K_UCHAR ucData_, char *szText_ ) { K_UCHAR ucTmp = ucData_; K_UCHAR ucMax; KERNEL_ASSERT( szText_ ); if (ucTmp >= 0x10) { ucMax = 2; } else { ucMax = 1; } ucTmp = ucData_; szText_[ucMax] = 0; while (ucMax--) { if ((ucTmp & 0x0F) <= 9) { szText_[ucMax] = '0' + (ucTmp & 0x0F); } else { szText_[ucMax] = 'A' + ((ucTmp & 0x0F) - 10); } ucTmp>>=4; } } //--------------------------------------------------------------------------- void MemUtil_DecimalToHex16( K_USHORT usData_, char *szText_ ) { K_USHORT usTmp = usData_; K_USHORT usMax = 1; K_USHORT usCompare = 0x0010; KERNEL_ASSERT( szText_ ); while (usData_ > usCompare && usMax < 4) { usMax++; usCompare <<= 4; } usTmp = usData_; szText_[usMax] = 0; while (usMax--) { if ((usTmp & 0x0F) <= 9) { szText_[usMax] = '0' + (usTmp & 0x0F); } else { szText_[usMax] = 'A' + ((usTmp & 0x0F) - 10); } usTmp>>=4; } } //--------------------------------------------------------------------------- void MemUtil_DecimalToHex32( K_ULONG ulData_, char *szText_ ) { K_ULONG ulTmp = ulData_; K_ULONG ulMax = 1; K_ULONG ulCompare = 0x0010; KERNEL_ASSERT( szText_ ); while (ulData_ > ulCompare && ulMax < 8) { ulMax++; ulCompare <<= 4; } ulTmp = ulData_; szText_[ulMax] = 0; while (ulMax--) { if ((ulTmp & 0x0F) <= 9) { szText_[ulMax] = '0' + (ulTmp & 0x0F); } else { szText_[ulMax] = 'A' + ((ulTmp & 0x0F) - 10); } ulTmp>>=4; } } //--------------------------------------------------------------------------- void MemUtil_DecimalToString8( K_UCHAR ucData_, char *szText_ ) { K_UCHAR ucTmp = ucData_; K_UCHAR ucMax; KERNEL_ASSERT(szText_); // Find max index to print... if (ucData_ >= 100) { ucMax = 3; } else if (ucData_ >= 10) { ucMax = 2; } else { ucMax = 1; } szText_[ucMax] = 0; while (ucMax--) { szText_[ucMax] = '0' + (ucTmp % 10); ucTmp/=10; } } //--------------------------------------------------------------------------- void MemUtil_DecimalToString16( K_USHORT usData_, char *szText_ ) { K_USHORT usTmp = usData_; K_USHORT usMax = 1; K_USHORT usCompare = 10; KERNEL_ASSERT(szText_); while (usData_ >= usCompare && usMax < 5) { usCompare *= 10; usMax++; } szText_[usMax] = 0; while (usMax--) { szText_[usMax] = '0' + (usTmp % 10); usTmp/=10; } } //--------------------------------------------------------------------------- void MemUtil_DecimalToString32( K_ULONG ulData_, char *szText_ ) { K_ULONG ulTmp = ulData_; K_ULONG ulMax = 1; K_ULONG ulCompare = 10; KERNEL_ASSERT(szText_); while (ulData_ >= ulCompare && ulMax < 12) { ulCompare *= 10; ulMax++; } szText_[ulMax] = 0; while (ulMax--) { szText_[ulMax] = '0' + (ulTmp % 10); ulTmp/=10; } } //--------------------------------------------------------------------------- // Basic checksum routines K_UCHAR MemUtil_Checksum8( const void *pvSrc_, K_USHORT usLen_ ) { K_UCHAR ucRet = 0; K_UCHAR *pcData = (K_UCHAR*)pvSrc_; KERNEL_ASSERT(pvSrc_); // 8-bit CRC, computed byte at a time while (usLen_--) { ucRet += *pcData++; } return ucRet; } //--------------------------------------------------------------------------- K_USHORT MemUtil_Checksum16( const void *pvSrc_, K_USHORT usLen_ ) { K_USHORT usRet = 0; K_UCHAR *pcData = (K_UCHAR*)pvSrc_; KERNEL_ASSERT(pvSrc_); // 16-bit CRC, computed byte at a time while (usLen_--) { usRet += *pcData++; } return usRet; } //--------------------------------------------------------------------------- // Basic string routines K_USHORT MemUtil_StringLength( const char *szStr_ ) { K_UCHAR *pcData = (K_UCHAR*)szStr_; K_USHORT usLen = 0; KERNEL_ASSERT(szStr_); while (*pcData++) { usLen++; } return usLen; } //--------------------------------------------------------------------------- K_BOOL MemUtil_CompareStrings( const char *szStr1_, const char *szStr2_ ) { char *szTmp1 = (char*) szStr1_; char *szTmp2 = (char*) szStr2_; KERNEL_ASSERT(szStr1_); KERNEL_ASSERT(szStr2_); while (*szTmp1 && *szTmp2) { if (*szTmp1++ != *szTmp2++) { return false; } } // Both terminate at the same length if (!(*szTmp1) && !(*szTmp2)) { return true; } return false; } //--------------------------------------------------------------------------- void MemUtil_CopyMemory( void *pvDst_, const void *pvSrc_, K_USHORT usLen_ ) { char *szDst = (char*) pvDst_; char *szSrc = (char*) pvSrc_; KERNEL_ASSERT(pvDst_); KERNEL_ASSERT(pvSrc_); // Run through the strings verifying that each character matches // and the lengths are the same. while (usLen_--) { *szDst++ = *szSrc++; } } //--------------------------------------------------------------------------- void MemUtil_CopyString( char *szDst_, const char *szSrc_ ) { char *szDst = (char*) szDst_; char *szSrc = (char*) szSrc_; KERNEL_ASSERT(szDst_); KERNEL_ASSERT(szSrc_); // Run through the strings verifying that each character matches // and the lengths are the same. while (*szSrc) { *szDst++ = *szSrc++; } } //--------------------------------------------------------------------------- K_SHORT MemUtil_StringSearch( const char *szBuffer_, const char *szPattern_ ) { char *szTmpPat = (char*)szPattern_; K_SHORT i16Idx = 0; K_SHORT i16Start; KERNEL_ASSERT( szBuffer_ ); KERNEL_ASSERT( szPattern_ ); // Run through the big buffer looking for a match of the pattern while (szBuffer_[i16Idx]) { // Reload the pattern i16Start = i16Idx; szTmpPat = (char*)szPattern_; while (*szTmpPat && szBuffer_[i16Idx]) { if (*szTmpPat != szBuffer_[i16Idx]) { break; } szTmpPat++; i16Idx++; } // Made it to the end of the pattern, it's a match. if (*szTmpPat == '\0') { return i16Start; } i16Idx++; } return -1; } //--------------------------------------------------------------------------- K_BOOL MemUtil_CompareMemory( const void *pvMem1_, const void *pvMem2_, K_USHORT usLen_ ) { char *szTmp1 = (char*) pvMem1_; char *szTmp2 = (char*) pvMem2_; KERNEL_ASSERT(pvMem1_); KERNEL_ASSERT(pvMem2_); // Run through the strings verifying that each character matches // and the lengths are the same. while (usLen_--) { if (*szTmp1++ != *szTmp2++) { return false; } } return true; } //--------------------------------------------------------------------------- void MemUtil_SetMemory( void *pvDst_, K_UCHAR ucVal_, K_USHORT usLen_ ) { char *szDst = (char*)pvDst_; KERNEL_ASSERT(pvDst_); while (usLen_--) { *szDst++ = ucVal_; } } //--------------------------------------------------------------------------- K_UCHAR MemUtil_Tokenize( const K_CHAR *szBuffer_, Token_t *pastTokens_, K_UCHAR ucMaxTokens_) { K_UCHAR ucCurrArg = 0; K_UCHAR ucLastArg = 0; K_UCHAR i = 0; K_BOOL bEscape = false; KERNEL_ASSERT(szBuffer_); KERNEL_ASSERT(pastTokens_); while (szBuffer_[i]) { //-- Handle unescaped quotes if (szBuffer_[i] == '\"') { if (bEscape) { bEscape = false; } else { bEscape = true; } i++; continue; } //-- Handle all escaped chars - by ignoring them if (szBuffer_[i] == '\\') { i++; if (szBuffer_[i]) { i++; } continue; } //-- Process chars based on current escape characters if (bEscape) { // Everything within the quote is treated as literal, but escaped chars are still treated the same i++; continue; } //-- Non-escaped case if (szBuffer_[i] != ' ' ) { i++; continue; } pastTokens_[ucCurrArg].pcToken = &(szBuffer_[ucLastArg]); pastTokens_[ucCurrArg].ucLen = i - ucLastArg; ucCurrArg++; if (ucCurrArg >= ucMaxTokens_) { return ucMaxTokens_; } i++; while (szBuffer_[i] && szBuffer_[i] == ' ') { i++; } ucLastArg = i; } if (i && !szBuffer_[i] && (i - ucLastArg)) { pastTokens_[ucCurrArg].pcToken = &(szBuffer_[ucLastArg]); pastTokens_[ucCurrArg].ucLen = i - ucLastArg; ucCurrArg++; } return ucCurrArg; }
moslevin/Mark3C
kernel/public/mutex.h
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2015 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file mutex.h \brief Mutual exclusion object declaration Resource locks are implemented using mutual exclusion semaphores (Mutex_t). Protected blocks can be placed around any resource that may only be accessed by one thread at a time. If additional threads attempt to access the protected resource, they will be placed in a wait queue until the resource becomes available. When the resource becomes available, the thread with the highest original priority claims the resource and is activated. Priority inheritance is included in the implementation to prevent priority inversion. Always ensure that you claim and release your Mutex_t objects consistently, otherwise you may end up with a deadlock scenario that's hard to debug. \section MInit Initializing Initializing a Mutex_t object by calling: \code stMutex.Init(); \endcode \section MUsage Resource protection example \code stMutex.Claim(); ... <resource protected block> ... stMutex.Release(); \endcode */ #ifndef __MUTEX_H_ #define __MUTEX_H_ #include "kerneltypes.h" #include "mark3cfg.h" #include "blocking.h" #if KERNEL_USE_MUTEX #if KERNEL_USE_TIMEOUTS #include "timerlist.h" #endif #ifdef __cplusplus extern "C" { #endif //--------------------------------------------------------------------------- /*! Mutual-exclusion locks, based on BlockingObject. */ typedef struct { // Inherit from BlockingObject -- must go first. ThreadList_t stList; K_UCHAR ucRecurse; //!< The recursive lock-count when a Mutex_t is claimed multiple times by the same owner K_UCHAR bReady; //!< State of the Mutex_t - true = ready, false = claimed K_UCHAR ucMaxPri; //!< Maximum priority of thread in queue, used for priority inheritence Thread_t *pstOwner; //!< Pointer to the thread that owns the Mutex_t (when claimed) } Mutex_t; //--------------------------------------------------------------------------- /*! \brief Mutex_Init Initialize a Mutex_t object for use - must call this function before using the object. */ void Mutex_Init( Mutex_t *pstMutex_ ); //--------------------------------------------------------------------------- /*! \brief Mutex_Claim Claim the Mutex_t. When the Mutex_t is claimed, no other thread can claim a region protected by the object. */ void Mutex_Claim( Mutex_t *pstMutex_ ); #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- /*! \brief Mutex_TimedClaim Claim the Mutex_t. When the Mutex_t is claimed, no other thread can claim a region protected by the object. This function enforces a maximum time (ms- resolution) for which the thread will wait before giving up and returning a timeout. \param ulWaitTimeMS_ \return true - Mutex_t was claimed within the time period specified false - Mutex_t operation timed-out before the claim operation. */ K_BOOL Mutex_TimedClaim( Mutex_t *pstMutex_, K_ULONG ulWaitTimeMS_ ); #endif //--------------------------------------------------------------------------- /*! \brief Mutex_Release Release the Mutex_t. When the Mutex_t is released, another object can enter the Mutex_t-protected region. */ void Mutex_Release( Mutex_t *pstMutex_ ); #ifdef __cplusplus } #endif #endif #endif //__MUTEX_H_