text
stringlengths
54
60.6k
<commit_before>// ---------------------------------------------------------------------------- // PSP Player Emulation Suite // Copyright (C) 2006 Ben Vanik (noxa) // Licensed under the LGPL - see License.txt in the project root for details // ---------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ // A lot of the following code has been either taken from or modified from the PSPGL code at ps2dev.org // Specifically, most comes from the following (pspgl_texobj.c): // http://svn.ps2dev.org/filedetails.php?repname=psp&path=%2Ftrunk%2Fpspgl%2Fpspgl_texobj.c&sc=1 // ------------------------------------------------------------------------------------------------------ #include "Stdafx.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <assert.h> #include <cmath> #include <string> #pragma unmanaged #include <gl/gl.h> #include <gl/glu.h> #include <gl/glext.h> #include <gl/wglext.h> #pragma managed #include "OglDriver.h" #include "OglContext.h" #include "OglTextures.h" using namespace Noxa::Emulation::Psp; using namespace Noxa::Emulation::Psp::Video; //using namespace Noxa::Emulation::Psp::Video::Native; #pragma unmanaged bool Noxa::Emulation::Psp::Video::IsTextureValid( OglTexture* texture ) { if( ( texture->Address == 0x0 ) || ( texture->LineWidth == 0 ) || ( texture->Width == 0 ) || ( texture->Height == 0 ) ) return false; #if 1 // This is a special case - something to do with the framebuffer being set as the texture? if( ( texture->Address == 0x04000000 ) && ( texture->LineWidth == 0x4 ) && ( texture->Width == 0x2 ) && ( texture->Height == 0x2 ) ) return false; #endif return true; } __inline uint lg2( uint x ) { switch( x ) { case 1: return 0; case 2: return 1; case 4: return 2; case 8: return 3; case 16: return 4; case 32: return 5; case 64: return 6; case 128: return 7; case 256: return 8; case 512: return 9; case 1024: return 10; case 2048: return 11; case 4096: return 12; case 8192: return 13; case 16384: return 14; case 32768: return 15; case 65536: return 16; } uint ret = -1; do { ret++; x >>= 1; } while( x != 0 ); return ret; } static void CopyPixel( const TextureFormat* format, void* dest, const void* source, const uint width ) { memcpy( dest, source, width * format->Size ); } static void CopyPixelIndexed4( const TextureFormat* format, void* dest, const void* source, const uint width ) { // 2 pixels/byte memcpy( dest, source, width / 2 ); } const TextureFormat __formats[] = { // Format Size Copier Flags GL format { TPSBGR5650, 2, CopyPixel, 0, GL_UNSIGNED_SHORT_5_6_5_REV, }, { TPSABGR5551, 2, CopyPixel, TFAlpha, GL_UNSIGNED_SHORT_1_5_5_5_REV, }, { TPSABGR4444, 2, CopyPixel, TFAlpha, GL_UNSIGNED_SHORT_4_4_4_4_REV, }, { TPSABGR8888, 4, CopyPixel, TFAlpha, GL_UNSIGNED_BYTE, }, { TPSIndexed4, 0, CopyPixelIndexed4, TFAlpha, GL_UNSIGNED_BYTE, }, { TPSIndexed8, 1, CopyPixel, TFAlpha, GL_UNSIGNED_BYTE, }, { TPSIndexed16, 2, CopyPixel, TFAlpha, GL_UNSIGNED_SHORT, }, { TPSIndexed32, 4, CopyPixel, TFAlpha, GL_UNSIGNED_INT, }, { TPSDXT1, 4, CopyPixel, TFAlpha, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, }, { TPSDXT3, 4, CopyPixel, TFAlpha, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, }, { TPSDXT5, 4, CopyPixel, TFAlpha, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, }, }; void Unswizzle1( const TextureFormat* format, const byte* in, byte* out, const uint width, const uint height ) { unsigned int blockx, blocky; unsigned int j; unsigned int width_blocks = (width / 16); unsigned int height_blocks = (height / 8); unsigned int src_pitch = (width-16)/4; unsigned int src_row = width * 8; const byte* ysrc = in; uint* dst = (uint*)out; for (blocky = 0; blocky < height_blocks; ++blocky) { const byte* xsrc = ysrc; for (blockx = 0; blockx < width_blocks; ++blockx) { const uint* src = (uint*)xsrc; for (j = 0; j < 8; ++j) { *(dst++) = *(src++); *(dst++) = *(src++); *(dst++) = *(src++); *(dst++) = *(src++); src += src_pitch; } xsrc += 16; } ysrc += src_row; } } __inline uint UnswizzleInner( uint offset, uint log2_w ) { unsigned w_mask = ( 1 << log2_w ) - 1; unsigned fixed = offset & ( ( ~7 << log2_w ) | 0xf ); unsigned bx = offset & ( ( w_mask & 0xF ) << 7 ); // 1F? unsigned my = offset & 0x70; return fixed | ( bx >> 3 ) | ( my << ( log2_w - 4 ) ); } void Unswizzle( const TextureFormat* format, const byte* in, byte* out, const uint width, const uint height ) { unsigned src_bytewidth = width * format->Size; unsigned lg2_w = lg2( src_bytewidth ); unsigned src_chunk = 16; unsigned pix_per_chunk = src_chunk / format->Size; unsigned src_size = width * height * format->Size; for( uint src_off = 0; src_off < src_size; src_off += src_chunk ) { unsigned swizoff = UnswizzleInner( src_off, lg2_w ); (*format->Copy)( format, out + swizoff, in + src_off, pix_per_chunk ); } } bool Noxa::Emulation::Psp::Video::GenerateTexture( OglContext* context, OglTexture* texture ) { uint textureId; glGenTextures( 1, &textureId ); //glBindTexture( GL_TEXTURE_2D, textureId ); texture->TextureID = textureId; byte* address; if( ( texture->Address & FrameBufferBase ) != 0 ) address = context->VideoMemoryPointer + ( texture->Address - FrameBufferBase ); else address = context->MainMemoryPointer + ( texture->Address - MainMemoryBase ); TextureFormat* format = ( TextureFormat* )&__formats[ texture->PixelStorage ]; int size = texture->LineWidth * texture->Height * format->Size; byte* buffer = address; if( context->TexturesSwizzled == true ) { buffer = ( byte* )malloc( size ); Unswizzle( format, address, buffer, texture->Width, texture->Height ); } if( format->Format != TPSABGR8888 ) { // Special handling... Nasty! if( format->Format == TPSABGR5551 ) { assert( context->TexturesSwizzled == false ); int oldSize = size; short* input = ( short* )buffer; size = texture->Width * texture->Height * 4; buffer = ( byte* )malloc( size ); format = ( TextureFormat *)&__formats[ 3 ]; // Copy 1555 to 8888 uint* output = ( uint* )buffer; for( int n = 0; n < texture->Width * texture->Height; n++ ) { short spixel = *input; /* RRRRRGGGGGBBBBBA <- GL ABBBBBGGGGGRRRRR <- PSP */ unsigned short r = ( (spixel & 0xf800) >> 11 ) * 8; unsigned short g = ( (spixel & 0x07c0) >> 6 ) * 8; unsigned short b = ( (spixel & 0x003E) >> 1 ) * 8; unsigned short a = (spixel & 0x0001); uint dpixel = a ? 0x000000FF : 0x0; dpixel |= ( r << 24 ) | ( g << 16 ) | ( b << 8 ); /*dpixel |= ( 8 * ( spixel & 0x1F ) ) | ( 8 * ( spixel >> 5 ) & 0x1F ) | ( 8 * ( spixel >> 10 ) & 0x1F );*/ *output = dpixel; input++; output++; } } } glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glPixelStorei( GL_UNPACK_ROW_LENGTH, texture->LineWidth ); /*HANDLE f = CreateFileA( "test.raw", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL ); int dummy1; WriteFile( f, ( void* )buffer, size, ( LPDWORD )&dummy1, NULL ); CloseHandle( f );*/ glTexImage2D( GL_TEXTURE_2D, 0, format->Size, texture->Width, texture->Height, 0, ( format->Flags & TFAlpha ) ? GL_RGBA : GL_RGB, format->GLFormat, ( void* )buffer ); if( context->TexturesSwizzled == true ) SAFEFREE( buffer ); return true; } #pragma managed <commit_msg>The One Unswizzle Function to Rule Them All.... I think. Unlike the previous code and the stuff out on the net, this code works with textures of all sizes. NeHe samples, PSPTris, and others work. So text now shows up in PSPTris as well as blocks and such. Besides the speed issue (possibly a input problem), thinks work! I may post a screenshot just because it's so awesome :)<commit_after>// ---------------------------------------------------------------------------- // PSP Player Emulation Suite // Copyright (C) 2006 Ben Vanik (noxa) // Licensed under the LGPL - see License.txt in the project root for details // ---------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------ // A lot of the following code has been either taken from or modified from the PSPGL code at ps2dev.org // Specifically, most comes from the following (pspgl_texobj.c): // http://svn.ps2dev.org/filedetails.php?repname=psp&path=%2Ftrunk%2Fpspgl%2Fpspgl_texobj.c&sc=1 // ------------------------------------------------------------------------------------------------------ #include "Stdafx.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <assert.h> #include <cmath> #include <string> #pragma unmanaged #include <gl/gl.h> #include <gl/glu.h> #include <gl/glext.h> #include <gl/wglext.h> #pragma managed #include "OglDriver.h" #include "OglContext.h" #include "OglTextures.h" using namespace Noxa::Emulation::Psp; using namespace Noxa::Emulation::Psp::Video; //using namespace Noxa::Emulation::Psp::Video::Native; #pragma unmanaged bool Noxa::Emulation::Psp::Video::IsTextureValid( OglTexture* texture ) { if( ( texture->Address == 0x0 ) || ( texture->LineWidth == 0 ) || ( texture->Width == 0 ) || ( texture->Height == 0 ) ) return false; #if 1 // This is a special case - something to do with the framebuffer being set as the texture? if( ( texture->Address == 0x04000000 ) && ( texture->LineWidth == 0x4 ) && ( texture->Width == 0x2 ) && ( texture->Height == 0x2 ) ) return false; #endif return true; } __inline uint lg2( uint x ) { switch( x ) { case 1: return 0; case 2: return 1; case 4: return 2; case 8: return 3; case 16: return 4; case 32: return 5; case 64: return 6; case 128: return 7; case 256: return 8; case 512: return 9; case 1024: return 10; case 2048: return 11; case 4096: return 12; case 8192: return 13; case 16384: return 14; case 32768: return 15; case 65536: return 16; } uint ret = -1; do { ret++; x >>= 1; } while( x != 0 ); return ret; } static void CopyPixel( const TextureFormat* format, void* dest, const void* source, const uint width ) { memcpy( dest, source, width * format->Size ); } static void CopyPixelIndexed4( const TextureFormat* format, void* dest, const void* source, const uint width ) { // 2 pixels/byte memcpy( dest, source, width / 2 ); } const TextureFormat __formats[] = { // Format Size Copier Flags GL format { TPSBGR5650, 2, CopyPixel, 0, GL_UNSIGNED_SHORT_5_6_5_REV, }, { TPSABGR5551, 2, CopyPixel, TFAlpha, GL_UNSIGNED_SHORT_1_5_5_5_REV, }, { TPSABGR4444, 2, CopyPixel, TFAlpha, GL_UNSIGNED_SHORT_4_4_4_4_REV, }, { TPSABGR8888, 4, CopyPixel, TFAlpha, GL_UNSIGNED_BYTE, }, { TPSIndexed4, 0, CopyPixelIndexed4, TFAlpha, GL_UNSIGNED_BYTE, }, { TPSIndexed8, 1, CopyPixel, TFAlpha, GL_UNSIGNED_BYTE, }, { TPSIndexed16, 2, CopyPixel, TFAlpha, GL_UNSIGNED_SHORT, }, { TPSIndexed32, 4, CopyPixel, TFAlpha, GL_UNSIGNED_INT, }, { TPSDXT1, 4, CopyPixel, TFAlpha, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, }, { TPSDXT3, 4, CopyPixel, TFAlpha, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, }, { TPSDXT5, 4, CopyPixel, TFAlpha, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, }, }; void Unswizzle( const TextureFormat* format, const byte* in, byte* out, const uint width, const uint height ) { int rowWidth = width * format->Size; int pitch = ( rowWidth - 16 ) / 4; int bxc = rowWidth / 16; int byc = height / 8; uint* src = ( uint* )in; const byte* ydest = out; for( int by = 0; by < byc; by++ ) { const byte* xdest = ydest; for( int bx = 0; bx < bxc; bx++ ) { uint* dest = ( uint* )xdest; for( int n = 0; n < 8; n++ ) { *( dest++ ) = *( src++ ); *( dest++ ) = *( src++ ); *( dest++ ) = *( src++ ); *( dest++ ) = *( src++ ); dest += pitch; } xdest += 16; } ydest += rowWidth * 8; } } bool Noxa::Emulation::Psp::Video::GenerateTexture( OglContext* context, OglTexture* texture ) { uint textureId; glGenTextures( 1, &textureId ); //glBindTexture( GL_TEXTURE_2D, textureId ); texture->TextureID = textureId; byte* address; if( ( texture->Address & FrameBufferBase ) != 0 ) address = context->VideoMemoryPointer + ( texture->Address - FrameBufferBase ); else address = context->MainMemoryPointer + ( texture->Address - MainMemoryBase ); TextureFormat* format = ( TextureFormat* )&__formats[ texture->PixelStorage ]; int size = texture->LineWidth * texture->Height * format->Size; byte* buffer = address; if( context->TexturesSwizzled == true ) { buffer = ( byte* )malloc( size ); Unswizzle( format, address, buffer, texture->Width, texture->Height ); } if( format->Format != TPSABGR8888 ) { // Special handling... Nasty! if( format->Format == TPSABGR5551 ) { assert( context->TexturesSwizzled == false ); int oldSize = size; short* input = ( short* )buffer; size = texture->Width * texture->Height * 4; buffer = ( byte* )malloc( size ); format = ( TextureFormat *)&__formats[ 3 ]; // Copy 1555 to 8888 uint* output = ( uint* )buffer; for( int n = 0; n < texture->Width * texture->Height; n++ ) { short spixel = *input; /* RRRRRGGGGGBBBBBA <- GL ABBBBBGGGGGRRRRR <- PSP */ unsigned short r = ( (spixel & 0xf800) >> 11 ) * 8; unsigned short g = ( (spixel & 0x07c0) >> 6 ) * 8; unsigned short b = ( (spixel & 0x003E) >> 1 ) * 8; unsigned short a = (spixel & 0x0001); uint dpixel = a ? 0x000000FF : 0x0; dpixel |= ( r << 24 ) | ( g << 16 ) | ( b << 8 ); /*dpixel |= ( 8 * ( spixel & 0x1F ) ) | ( 8 * ( spixel >> 5 ) & 0x1F ) | ( 8 * ( spixel >> 10 ) & 0x1F );*/ *output = dpixel; input++; output++; } } } glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glPixelStorei( GL_UNPACK_ROW_LENGTH, texture->LineWidth ); /*HANDLE f = CreateFileA( "test.raw", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL ); int dummy1; WriteFile( f, ( void* )buffer, size, ( LPDWORD )&dummy1, NULL ); CloseHandle( f );*/ glTexImage2D( GL_TEXTURE_2D, 0, format->Size, texture->Width, texture->Height, 0, ( format->Flags & TFAlpha ) ? GL_RGBA : GL_RGB, format->GLFormat, ( void* )buffer ); if( context->TexturesSwizzled == true ) SAFEFREE( buffer ); return true; } #pragma managed <|endoftext|>
<commit_before>#include "StdAfx.h" #include "Controller.h" #include "ControllerManager.h" #include "ControllerFilters.h" #include "ObstacleContext.h" #include "RigidDynamic.h" #include "Shape.h" #include "ControllerState.h" #include "ControllerStats.h" using namespace System::Linq; Controller::Controller(PxController* controller, PhysX::ControllerManager^ owner) { ThrowIfNull(controller, "controller"); ThrowIfNullOrDisposed(owner, "owner"); _controller = controller; _controllerManager = owner; ObjectTable::Add((intptr_t)controller, this, owner); // The Actor class holds the PxActor, but should not dispose of it, as it is owned entirely // by the PxController instance PxRigidDynamic* actor = controller->getActor(); _actor = gcnew PhysX::RigidDynamic(actor, nullptr); _actor->UnmanagedOwner = false; // The Shape class holds the PxShape, but should not dispose of it, as it is owned entirely // by the PxActor of the PxController instance _shape = _actor->GetShape(0); _shape->UnmanagedOwner = false; } Controller::~Controller() { this->!Controller(); } Controller::!Controller() { OnDisposing(this, nullptr); if (this->Disposed) return; _controller->release(); _controller = NULL; UserData = nullptr; OnDisposed(this, nullptr); } bool Controller::Disposed::get() { return (_controller == NULL); } ControllerCollisionFlag Controller::Move(Vector3 displacement, TimeSpan elapsedTime) { auto filter = gcnew ControllerFilters(); filter->ActiveGroups = 0xFFFFFFFF; filter->FilterFlags = QueryFlag::Static | QueryFlag::Dynamic; return Move(displacement, elapsedTime, 0.001f, filter, nullptr); } ControllerCollisionFlag Controller::Move(Vector3 displacement, TimeSpan elapsedTime, float minimumDistance, ControllerFilters^ filters, [Optional] ObstacleContext^ obstacles) { auto disp = MathUtil::Vector3ToPxVec3(displacement); auto et = (float)elapsedTime.TotalSeconds; auto f = ControllerFilters::ToUnmanaged(filters); auto oc = (obstacles == nullptr ? NULL : obstacles->UnmanagedPointer); PxU32 returnFlags = _controller->move(disp, minimumDistance, et, f, oc); // TODO: Not the cleanest way of cleaning up the memory that ControllerFilter allocates if (f.mFilterData != NULL) { delete f.mFilterData; } return (ControllerCollisionFlag)returnFlags; } ControllerState^ Controller::GetState() { PxControllerState state; _controller->getState(state); auto managedState = ControllerState::ToManaged(state); return managedState; } void Controller::InvalidateCache() { _controller->invalidateCache(); } ControllerStats Controller::GetStats() { PxControllerStats s; _controller->getStats(s); return ControllerStats::ToManaged(s); } void Controller::Resize(float height) { _controller->resize(height); } PhysX::ControllerManager^ Controller::ControllerManager::get() { return _controllerManager; } PhysX::RigidDynamic^ Controller::Actor::get() { return _actor; } PhysX::Shape^ Controller::Shape::get() { return _shape; } Vector3 Controller::Position::get() { PxExtendedVec3 p = _controller->getPosition(); return MathUtil::PxExtendedVec3ToVector3(p); } void Controller::Position::set(Vector3 value) { PxExtendedVec3 p = MathUtil::Vector3ToPxExtendedVec3(value); _controller->setPosition(p); } Vector3 Controller::FootPosition::get() { PxExtendedVec3 p = _controller->getFootPosition(); return MathUtil::PxExtendedVec3ToVector3(p); } void Controller::FootPosition::set(Vector3 value) { PxExtendedVec3 p = MathUtil::Vector3ToPxExtendedVec3(value); _controller->setFootPosition(p); } float Controller::StepOffset::get() { return _controller->getStepOffset(); } void Controller::StepOffset::set(float value) { _controller->setStepOffset(value); } ControllerNonWalkableMode Controller::NonWalkableMode::get() { return ToManagedEnum(ControllerNonWalkableMode, _controller->getNonWalkableMode()); } void Controller::NonWalkableMode::set(ControllerNonWalkableMode value) { _controller->setNonWalkableMode(ToUnmanagedEnum(PxControllerNonWalkableMode, value)); } //CCTInteractionMode Controller::Interaction::get() //{ // return ToManagedEnum(CCTInteractionMode, _controller->getInteraction()); //} //void Controller::Interaction::set(CCTInteractionMode value) //{ // _controller->setInteraction(ToUnmanagedEnum(PxCCTInteractionMode, value)); //} float Controller::ContactOffset::get() { return _controller->getContactOffset(); } Vector3 Controller::UpDirection::get() { return MathUtil::PxVec3ToVector3(_controller->getUpDirection()); } void Controller::UpDirection::set(Vector3 value) { _controller->setUpDirection(MathUtil::Vector3ToPxVec3(value)); } float Controller::SlopeLimit::get() { return _controller->getSlopeLimit(); } void Controller::SlopeLimit::set(float value) { _controller->setSlopeLimit(value); } ControllerShapeType Controller::Type::get() { return ToManagedEnum(ControllerShapeType, _controller->getType()); } PxController* Controller::UnmanagedPointer::get() { return _controller; }<commit_msg>Clean<commit_after>#include "StdAfx.h" #include "Controller.h" #include "ControllerManager.h" #include "ControllerFilters.h" #include "ObstacleContext.h" #include "RigidDynamic.h" #include "Shape.h" #include "ControllerState.h" #include "ControllerStats.h" using namespace System::Linq; Controller::Controller(PxController* controller, PhysX::ControllerManager^ owner) { ThrowIfNull(controller, "controller"); ThrowIfNullOrDisposed(owner, "owner"); _controller = controller; _controllerManager = owner; ObjectTable::Add((intptr_t)controller, this, owner); // The Actor class holds the PxActor, but should not dispose of it, as it is owned entirely // by the PxController instance PxRigidDynamic* actor = controller->getActor(); _actor = gcnew PhysX::RigidDynamic(actor, nullptr); _actor->UnmanagedOwner = false; // The Shape class holds the PxShape, but should not dispose of it, as it is owned entirely // by the PxActor of the PxController instance _shape = _actor->GetShape(0); _shape->UnmanagedOwner = false; } Controller::~Controller() { this->!Controller(); } Controller::!Controller() { OnDisposing(this, nullptr); if (this->Disposed) return; _controller->release(); _controller = NULL; UserData = nullptr; OnDisposed(this, nullptr); } bool Controller::Disposed::get() { return (_controller == NULL); } ControllerCollisionFlag Controller::Move(Vector3 displacement, TimeSpan elapsedTime) { auto filter = gcnew ControllerFilters(); filter->ActiveGroups = 0xFFFFFFFF; filter->FilterFlags = QueryFlag::Static | QueryFlag::Dynamic; return Move(displacement, elapsedTime, 0.001f, filter, nullptr); } ControllerCollisionFlag Controller::Move(Vector3 displacement, TimeSpan elapsedTime, float minimumDistance, ControllerFilters^ filters, [Optional] ObstacleContext^ obstacles) { auto disp = MathUtil::Vector3ToPxVec3(displacement); auto et = (float)elapsedTime.TotalSeconds; auto f = ControllerFilters::ToUnmanaged(filters); auto oc = (obstacles == nullptr ? NULL : obstacles->UnmanagedPointer); PxU32 returnFlags = _controller->move(disp, minimumDistance, et, f, oc); // TODO: Not the cleanest way of cleaning up the memory that ControllerFilter allocates if (f.mFilterData != NULL) { delete f.mFilterData; } return (ControllerCollisionFlag)returnFlags; } ControllerState^ Controller::GetState() { PxControllerState state; _controller->getState(state); return ControllerState::ToManaged(state); } void Controller::InvalidateCache() { _controller->invalidateCache(); } ControllerStats Controller::GetStats() { PxControllerStats s; _controller->getStats(s); return ControllerStats::ToManaged(s); } void Controller::Resize(float height) { _controller->resize(height); } PhysX::ControllerManager^ Controller::ControllerManager::get() { return _controllerManager; } PhysX::RigidDynamic^ Controller::Actor::get() { return _actor; } PhysX::Shape^ Controller::Shape::get() { return _shape; } Vector3 Controller::Position::get() { PxExtendedVec3 p = _controller->getPosition(); return MathUtil::PxExtendedVec3ToVector3(p); } void Controller::Position::set(Vector3 value) { PxExtendedVec3 p = MathUtil::Vector3ToPxExtendedVec3(value); _controller->setPosition(p); } Vector3 Controller::FootPosition::get() { PxExtendedVec3 p = _controller->getFootPosition(); return MathUtil::PxExtendedVec3ToVector3(p); } void Controller::FootPosition::set(Vector3 value) { PxExtendedVec3 p = MathUtil::Vector3ToPxExtendedVec3(value); _controller->setFootPosition(p); } float Controller::StepOffset::get() { return _controller->getStepOffset(); } void Controller::StepOffset::set(float value) { _controller->setStepOffset(value); } ControllerNonWalkableMode Controller::NonWalkableMode::get() { return ToManagedEnum(ControllerNonWalkableMode, _controller->getNonWalkableMode()); } void Controller::NonWalkableMode::set(ControllerNonWalkableMode value) { _controller->setNonWalkableMode(ToUnmanagedEnum(PxControllerNonWalkableMode, value)); } //CCTInteractionMode Controller::Interaction::get() //{ // return ToManagedEnum(CCTInteractionMode, _controller->getInteraction()); //} //void Controller::Interaction::set(CCTInteractionMode value) //{ // _controller->setInteraction(ToUnmanagedEnum(PxCCTInteractionMode, value)); //} float Controller::ContactOffset::get() { return _controller->getContactOffset(); } Vector3 Controller::UpDirection::get() { return MathUtil::PxVec3ToVector3(_controller->getUpDirection()); } void Controller::UpDirection::set(Vector3 value) { _controller->setUpDirection(MathUtil::Vector3ToPxVec3(value)); } float Controller::SlopeLimit::get() { return _controller->getSlopeLimit(); } void Controller::SlopeLimit::set(float value) { _controller->setSlopeLimit(value); } ControllerShapeType Controller::Type::get() { return ToManagedEnum(ControllerShapeType, _controller->getType()); } PxController* Controller::UnmanagedPointer::get() { return _controller; }<|endoftext|>
<commit_before>/** * Author: Denis Anisimov 2015 * * Slap bot written in C++ * */ #include "trout_slap_bot.h" int main(int argc, char** argv) { TroutSlapBot bot("abcd"); TroutSlapBot.Run(); return 0; }<commit_msg>Add usage message<commit_after>/** * Author: Denis Anisimov 2015 * * Slap bot written in C++ * */ #include <iostream> #include "trout_slap_bot.h" int main(int argc, char** argv) { if (argc < 2) { std::cout << "Usage: slap <bot_token>" << std::endl; exit(1); } std::string token(argv[1]); TroutSlapBot bot(token); bot.Run(); return 0; }<|endoftext|>
<commit_before>//===- InlineCost.cpp - Cost analysis for inliner -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements inline cost analysis. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/InlineCost.h" #include "llvm/Support/CallSite.h" #include "llvm/CallingConv.h" #include "llvm/IntrinsicInst.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; // CountCodeReductionForConstant - Figure out an approximation for how many // instructions will be constant folded if the specified value is constant. // unsigned InlineCostAnalyzer::FunctionInfo:: CountCodeReductionForConstant(Value *V) { unsigned Reduction = 0; for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) if (isa<BranchInst>(*UI)) Reduction += 40; // Eliminating a conditional branch is a big win else if (SwitchInst *SI = dyn_cast<SwitchInst>(*UI)) // Eliminating a switch is a big win, proportional to the number of edges // deleted. Reduction += (SI->getNumSuccessors()-1) * 40; else if (CallInst *CI = dyn_cast<CallInst>(*UI)) { // Turning an indirect call into a direct call is a BIG win Reduction += CI->getCalledValue() == V ? 500 : 0; } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) { // Turning an indirect call into a direct call is a BIG win Reduction += II->getCalledValue() == V ? 500 : 0; } else { // Figure out if this instruction will be removed due to simple constant // propagation. Instruction &Inst = cast<Instruction>(**UI); // We can't constant propagate instructions which have effects or // read memory. // // FIXME: It would be nice to capture the fact that a load from a // pointer-to-constant-global is actually a *really* good thing to zap. // Unfortunately, we don't know the pointer that may get propagated here, // so we can't make this decision. if (Inst.mayReadFromMemory() || Inst.mayHaveSideEffects() || isa<AllocaInst>(Inst)) continue; bool AllOperandsConstant = true; for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) { AllOperandsConstant = false; break; } if (AllOperandsConstant) { // We will get to remove this instruction... Reduction += 7; // And any other instructions that use it which become constants // themselves. Reduction += CountCodeReductionForConstant(&Inst); } } return Reduction; } // CountCodeReductionForAlloca - Figure out an approximation of how much smaller // the function will be if it is inlined into a context where an argument // becomes an alloca. // unsigned InlineCostAnalyzer::FunctionInfo:: CountCodeReductionForAlloca(Value *V) { if (!isa<PointerType>(V->getType())) return 0; // Not a pointer unsigned Reduction = 0; for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){ Instruction *I = cast<Instruction>(*UI); if (isa<LoadInst>(I) || isa<StoreInst>(I)) Reduction += 10; else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) { // If the GEP has variable indices, we won't be able to do much with it. if (!GEP->hasAllConstantIndices()) Reduction += CountCodeReductionForAlloca(GEP)+15; } else { // If there is some other strange instruction, we're not going to be able // to do much if we inline this. return 0; } } return Reduction; } // callIsSmall - If a call is likely to lower to a single target instruction, or // is otherwise deemed small return true. // TODO: Perhaps calls like memcpy, strcpy, etc? static bool callIsSmall(const Function *F) { if (!F) return false; if (F->hasLocalLinkage()) return false; if (!F->hasName()) return false; StringRef Name = F->getName(); // These will all likely lower to a single selection DAG node. if (Name == "copysign" || Name == "copysignf" || Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" || Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" || Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl" ) return true; // These are all likely to be optimized into something smaller. if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" || Name == "exp2l" || Name == "exp2f" || Name == "floor" || Name == "floorf" || Name == "ceil" || Name == "round" || Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" || Name == "llabs") return true; return false; } /// analyzeBasicBlock - Fill in the current structure with information gleaned /// from the specified block. void CodeMetrics::analyzeBasicBlock(const BasicBlock *BB) { ++NumBlocks; for (BasicBlock::const_iterator II = BB->begin(), E = BB->end(); II != E; ++II) { if (isa<PHINode>(II)) continue; // PHI nodes don't count. // Special handling for calls. if (isa<CallInst>(II) || isa<InvokeInst>(II)) { if (isa<DbgInfoIntrinsic>(II)) continue; // Debug intrinsics don't count as size. CallSite CS = CallSite::get(const_cast<Instruction*>(&*II)); // If this function contains a call to setjmp or _setjmp, never inline // it. This is a hack because we depend on the user marking their local // variables as volatile if they are live across a setjmp call, and they // probably won't do this in callers. if (Function *F = CS.getCalledFunction()) if (F->isDeclaration() && (F->getName() == "setjmp" || F->getName() == "_setjmp")) NeverInline = true; // Calls often compile into many machine instructions. Bump up their // cost to reflect this. if (!isa<IntrinsicInst>(II) && !callIsSmall(CS.getCalledFunction())) NumInsts += InlineConstants::CallPenalty; } if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { if (!AI->isStaticAlloca()) this->usesDynamicAlloca = true; } if (isa<ExtractElementInst>(II) || isa<VectorType>(II->getType())) ++NumVectorInsts; if (const CastInst *CI = dyn_cast<CastInst>(II)) { // Noop casts, including ptr <-> int, don't count. if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) || isa<PtrToIntInst>(CI)) continue; // Result of a cmp instruction is often extended (to be used by other // cmp instructions, logical or return instructions). These are usually // nop on most sane targets. if (isa<CmpInst>(CI->getOperand(0))) continue; } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(II)){ // If a GEP has all constant indices, it will probably be folded with // a load/store. if (GEPI->hasAllConstantIndices()) continue; } ++NumInsts; } if (isa<ReturnInst>(BB->getTerminator())) ++NumRets; // We never want to inline functions that contain an indirectbr. This is // incorrect because all the blockaddress's (in static global initializers // for example) would be referring to the original function, and this indirect // jump would jump from the inlined copy of the function into the original // function which is extremely undefined behavior. if (isa<IndirectBrInst>(BB->getTerminator())) NeverInline = true; } /// analyzeFunction - Fill in the current structure with information gleaned /// from the specified function. void CodeMetrics::analyzeFunction(Function *F) { // Look at the size of the callee. for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) analyzeBasicBlock(&*BB); } /// analyzeFunction - Fill in the current structure with information gleaned /// from the specified function. void InlineCostAnalyzer::FunctionInfo::analyzeFunction(Function *F) { Metrics.analyzeFunction(F); // A function with exactly one return has it removed during the inlining // process (see InlineFunction), so don't count it. // FIXME: This knowledge should really be encoded outside of FunctionInfo. if (Metrics.NumRets==1) --Metrics.NumInsts; // Don't bother calculating argument weights if we are never going to inline // the function anyway. if (Metrics.NeverInline) return; // Check out all of the arguments to the function, figuring out how much // code can be eliminated if one of the arguments is a constant. ArgumentWeights.reserve(F->arg_size()); for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I), CountCodeReductionForAlloca(I))); } // getInlineCost - The heuristic used to determine if we should inline the // function call or not. // InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, SmallPtrSet<const Function *, 16> &NeverInline) { Instruction *TheCall = CS.getInstruction(); Function *Callee = CS.getCalledFunction(); Function *Caller = TheCall->getParent()->getParent(); // Don't inline functions which can be redefined at link-time to mean // something else. Don't inline functions marked noinline. if (Callee->mayBeOverridden() || Callee->hasFnAttr(Attribute::NoInline) || NeverInline.count(Callee)) return llvm::InlineCost::getNever(); // InlineCost - This value measures how good of an inline candidate this call // site is to inline. A lower inline cost make is more likely for the call to // be inlined. This value may go negative. // int InlineCost = 0; // If there is only one call of the function, and it has internal linkage, // make it almost guaranteed to be inlined. // if (Callee->hasLocalLinkage() && Callee->hasOneUse()) InlineCost += InlineConstants::LastCallToStaticBonus; // If this function uses the coldcc calling convention, prefer not to inline // it. if (Callee->getCallingConv() == CallingConv::Cold) InlineCost += InlineConstants::ColdccPenalty; // If the instruction after the call, or if the normal destination of the // invoke is an unreachable instruction, the function is noreturn. As such, // there is little point in inlining this. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) { if (isa<UnreachableInst>(II->getNormalDest()->begin())) InlineCost += InlineConstants::NoreturnPenalty; } else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall))) InlineCost += InlineConstants::NoreturnPenalty; // Get information about the callee... FunctionInfo &CalleeFI = CachedFunctionInfo[Callee]; // If we haven't calculated this information yet, do so now. if (CalleeFI.Metrics.NumBlocks == 0) CalleeFI.analyzeFunction(Callee); // If we should never inline this, return a huge cost. if (CalleeFI.Metrics.NeverInline) return InlineCost::getNever(); // FIXME: It would be nice to kill off CalleeFI.NeverInline. Then we // could move this up and avoid computing the FunctionInfo for // things we are going to just return always inline for. This // requires handling setjmp somewhere else, however. if (!Callee->isDeclaration() && Callee->hasFnAttr(Attribute::AlwaysInline)) return InlineCost::getAlways(); if (CalleeFI.Metrics.usesDynamicAlloca) { // Get infomation about the caller... FunctionInfo &CallerFI = CachedFunctionInfo[Caller]; // If we haven't calculated this information yet, do so now. if (CallerFI.Metrics.NumBlocks == 0) CallerFI.analyzeFunction(Caller); // Don't inline a callee with dynamic alloca into a caller without them. // Functions containing dynamic alloca's are inefficient in various ways; // don't create more inefficiency. if (!CallerFI.Metrics.usesDynamicAlloca) return InlineCost::getNever(); } // Add to the inline quality for properties that make the call valuable to // inline. This includes factors that indicate that the result of inlining // the function will be optimizable. Currently this just looks at arguments // passed into the function. // unsigned ArgNo = 0; for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I, ++ArgNo) { // Each argument passed in has a cost at both the caller and the callee // sides. This favors functions that take many arguments over functions // that take few arguments. InlineCost -= 20; // If this is a function being passed in, it is very likely that we will be // able to turn an indirect function call into a direct function call. if (isa<Function>(I)) InlineCost -= 100; // If an alloca is passed in, inlining this function is likely to allow // significant future optimization possibilities (like scalar promotion, and // scalarization), so encourage the inlining of the function. // else if (isa<AllocaInst>(I)) { if (ArgNo < CalleeFI.ArgumentWeights.size()) InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight; // If this is a constant being passed into the function, use the argument // weights calculated for the callee to determine how much will be folded // away with this information. } else if (isa<Constant>(I)) { if (ArgNo < CalleeFI.ArgumentWeights.size()) InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight; } } // Now that we have considered all of the factors that make the call site more // likely to be inlined, look at factors that make us not want to inline it. // Don't inline into something too big, which would make it bigger. // "size" here is the number of basic blocks, not instructions. // InlineCost += Caller->size()/15; // Look at the size of the callee. Each instruction counts as 5. InlineCost += CalleeFI.Metrics.NumInsts*5; return llvm::InlineCost::get(InlineCost); } // getInlineFudgeFactor - Return a > 1.0 factor if the inliner should use a // higher threshold to determine if the function call should be inlined. float InlineCostAnalyzer::getInlineFudgeFactor(CallSite CS) { Function *Callee = CS.getCalledFunction(); // Get information about the callee... FunctionInfo &CalleeFI = CachedFunctionInfo[Callee]; // If we haven't calculated this information yet, do so now. if (CalleeFI.Metrics.NumBlocks == 0) CalleeFI.analyzeFunction(Callee); float Factor = 1.0f; // Single BB functions are often written to be inlined. if (CalleeFI.Metrics.NumBlocks == 1) Factor += 0.5f; // Be more aggressive if the function contains a good chunk (if it mades up // at least 10% of the instructions) of vector instructions. if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/2) Factor += 2.0f; else if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/10) Factor += 1.5f; return Factor; } <commit_msg>Revert test polarity to match comment and desired outcome. Remove undeserved bonus.<commit_after>//===- InlineCost.cpp - Cost analysis for inliner -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements inline cost analysis. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/InlineCost.h" #include "llvm/Support/CallSite.h" #include "llvm/CallingConv.h" #include "llvm/IntrinsicInst.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; // CountCodeReductionForConstant - Figure out an approximation for how many // instructions will be constant folded if the specified value is constant. // unsigned InlineCostAnalyzer::FunctionInfo:: CountCodeReductionForConstant(Value *V) { unsigned Reduction = 0; for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI) if (isa<BranchInst>(*UI)) Reduction += 40; // Eliminating a conditional branch is a big win else if (SwitchInst *SI = dyn_cast<SwitchInst>(*UI)) // Eliminating a switch is a big win, proportional to the number of edges // deleted. Reduction += (SI->getNumSuccessors()-1) * 40; else if (CallInst *CI = dyn_cast<CallInst>(*UI)) { // Turning an indirect call into a direct call is a BIG win Reduction += CI->getCalledValue() == V ? 500 : 0; } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) { // Turning an indirect call into a direct call is a BIG win Reduction += II->getCalledValue() == V ? 500 : 0; } else { // Figure out if this instruction will be removed due to simple constant // propagation. Instruction &Inst = cast<Instruction>(**UI); // We can't constant propagate instructions which have effects or // read memory. // // FIXME: It would be nice to capture the fact that a load from a // pointer-to-constant-global is actually a *really* good thing to zap. // Unfortunately, we don't know the pointer that may get propagated here, // so we can't make this decision. if (Inst.mayReadFromMemory() || Inst.mayHaveSideEffects() || isa<AllocaInst>(Inst)) continue; bool AllOperandsConstant = true; for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) { AllOperandsConstant = false; break; } if (AllOperandsConstant) { // We will get to remove this instruction... Reduction += 7; // And any other instructions that use it which become constants // themselves. Reduction += CountCodeReductionForConstant(&Inst); } } return Reduction; } // CountCodeReductionForAlloca - Figure out an approximation of how much smaller // the function will be if it is inlined into a context where an argument // becomes an alloca. // unsigned InlineCostAnalyzer::FunctionInfo:: CountCodeReductionForAlloca(Value *V) { if (!isa<PointerType>(V->getType())) return 0; // Not a pointer unsigned Reduction = 0; for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){ Instruction *I = cast<Instruction>(*UI); if (isa<LoadInst>(I) || isa<StoreInst>(I)) Reduction += 10; else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) { // If the GEP has variable indices, we won't be able to do much with it. if (GEP->hasAllConstantIndices()) Reduction += CountCodeReductionForAlloca(GEP); } else { // If there is some other strange instruction, we're not going to be able // to do much if we inline this. return 0; } } return Reduction; } // callIsSmall - If a call is likely to lower to a single target instruction, or // is otherwise deemed small return true. // TODO: Perhaps calls like memcpy, strcpy, etc? static bool callIsSmall(const Function *F) { if (!F) return false; if (F->hasLocalLinkage()) return false; if (!F->hasName()) return false; StringRef Name = F->getName(); // These will all likely lower to a single selection DAG node. if (Name == "copysign" || Name == "copysignf" || Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" || Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" || Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl" ) return true; // These are all likely to be optimized into something smaller. if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" || Name == "exp2l" || Name == "exp2f" || Name == "floor" || Name == "floorf" || Name == "ceil" || Name == "round" || Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" || Name == "llabs") return true; return false; } /// analyzeBasicBlock - Fill in the current structure with information gleaned /// from the specified block. void CodeMetrics::analyzeBasicBlock(const BasicBlock *BB) { ++NumBlocks; for (BasicBlock::const_iterator II = BB->begin(), E = BB->end(); II != E; ++II) { if (isa<PHINode>(II)) continue; // PHI nodes don't count. // Special handling for calls. if (isa<CallInst>(II) || isa<InvokeInst>(II)) { if (isa<DbgInfoIntrinsic>(II)) continue; // Debug intrinsics don't count as size. CallSite CS = CallSite::get(const_cast<Instruction*>(&*II)); // If this function contains a call to setjmp or _setjmp, never inline // it. This is a hack because we depend on the user marking their local // variables as volatile if they are live across a setjmp call, and they // probably won't do this in callers. if (Function *F = CS.getCalledFunction()) if (F->isDeclaration() && (F->getName() == "setjmp" || F->getName() == "_setjmp")) NeverInline = true; // Calls often compile into many machine instructions. Bump up their // cost to reflect this. if (!isa<IntrinsicInst>(II) && !callIsSmall(CS.getCalledFunction())) NumInsts += InlineConstants::CallPenalty; } if (const AllocaInst *AI = dyn_cast<AllocaInst>(II)) { if (!AI->isStaticAlloca()) this->usesDynamicAlloca = true; } if (isa<ExtractElementInst>(II) || isa<VectorType>(II->getType())) ++NumVectorInsts; if (const CastInst *CI = dyn_cast<CastInst>(II)) { // Noop casts, including ptr <-> int, don't count. if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) || isa<PtrToIntInst>(CI)) continue; // Result of a cmp instruction is often extended (to be used by other // cmp instructions, logical or return instructions). These are usually // nop on most sane targets. if (isa<CmpInst>(CI->getOperand(0))) continue; } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(II)){ // If a GEP has all constant indices, it will probably be folded with // a load/store. if (GEPI->hasAllConstantIndices()) continue; } ++NumInsts; } if (isa<ReturnInst>(BB->getTerminator())) ++NumRets; // We never want to inline functions that contain an indirectbr. This is // incorrect because all the blockaddress's (in static global initializers // for example) would be referring to the original function, and this indirect // jump would jump from the inlined copy of the function into the original // function which is extremely undefined behavior. if (isa<IndirectBrInst>(BB->getTerminator())) NeverInline = true; } /// analyzeFunction - Fill in the current structure with information gleaned /// from the specified function. void CodeMetrics::analyzeFunction(Function *F) { // Look at the size of the callee. for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) analyzeBasicBlock(&*BB); } /// analyzeFunction - Fill in the current structure with information gleaned /// from the specified function. void InlineCostAnalyzer::FunctionInfo::analyzeFunction(Function *F) { Metrics.analyzeFunction(F); // A function with exactly one return has it removed during the inlining // process (see InlineFunction), so don't count it. // FIXME: This knowledge should really be encoded outside of FunctionInfo. if (Metrics.NumRets==1) --Metrics.NumInsts; // Don't bother calculating argument weights if we are never going to inline // the function anyway. if (Metrics.NeverInline) return; // Check out all of the arguments to the function, figuring out how much // code can be eliminated if one of the arguments is a constant. ArgumentWeights.reserve(F->arg_size()); for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I), CountCodeReductionForAlloca(I))); } // getInlineCost - The heuristic used to determine if we should inline the // function call or not. // InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, SmallPtrSet<const Function *, 16> &NeverInline) { Instruction *TheCall = CS.getInstruction(); Function *Callee = CS.getCalledFunction(); Function *Caller = TheCall->getParent()->getParent(); // Don't inline functions which can be redefined at link-time to mean // something else. Don't inline functions marked noinline. if (Callee->mayBeOverridden() || Callee->hasFnAttr(Attribute::NoInline) || NeverInline.count(Callee)) return llvm::InlineCost::getNever(); // InlineCost - This value measures how good of an inline candidate this call // site is to inline. A lower inline cost make is more likely for the call to // be inlined. This value may go negative. // int InlineCost = 0; // If there is only one call of the function, and it has internal linkage, // make it almost guaranteed to be inlined. // if (Callee->hasLocalLinkage() && Callee->hasOneUse()) InlineCost += InlineConstants::LastCallToStaticBonus; // If this function uses the coldcc calling convention, prefer not to inline // it. if (Callee->getCallingConv() == CallingConv::Cold) InlineCost += InlineConstants::ColdccPenalty; // If the instruction after the call, or if the normal destination of the // invoke is an unreachable instruction, the function is noreturn. As such, // there is little point in inlining this. if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) { if (isa<UnreachableInst>(II->getNormalDest()->begin())) InlineCost += InlineConstants::NoreturnPenalty; } else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall))) InlineCost += InlineConstants::NoreturnPenalty; // Get information about the callee... FunctionInfo &CalleeFI = CachedFunctionInfo[Callee]; // If we haven't calculated this information yet, do so now. if (CalleeFI.Metrics.NumBlocks == 0) CalleeFI.analyzeFunction(Callee); // If we should never inline this, return a huge cost. if (CalleeFI.Metrics.NeverInline) return InlineCost::getNever(); // FIXME: It would be nice to kill off CalleeFI.NeverInline. Then we // could move this up and avoid computing the FunctionInfo for // things we are going to just return always inline for. This // requires handling setjmp somewhere else, however. if (!Callee->isDeclaration() && Callee->hasFnAttr(Attribute::AlwaysInline)) return InlineCost::getAlways(); if (CalleeFI.Metrics.usesDynamicAlloca) { // Get infomation about the caller... FunctionInfo &CallerFI = CachedFunctionInfo[Caller]; // If we haven't calculated this information yet, do so now. if (CallerFI.Metrics.NumBlocks == 0) CallerFI.analyzeFunction(Caller); // Don't inline a callee with dynamic alloca into a caller without them. // Functions containing dynamic alloca's are inefficient in various ways; // don't create more inefficiency. if (!CallerFI.Metrics.usesDynamicAlloca) return InlineCost::getNever(); } // Add to the inline quality for properties that make the call valuable to // inline. This includes factors that indicate that the result of inlining // the function will be optimizable. Currently this just looks at arguments // passed into the function. // unsigned ArgNo = 0; for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I, ++ArgNo) { // Each argument passed in has a cost at both the caller and the callee // sides. This favors functions that take many arguments over functions // that take few arguments. InlineCost -= 20; // If this is a function being passed in, it is very likely that we will be // able to turn an indirect function call into a direct function call. if (isa<Function>(I)) InlineCost -= 100; // If an alloca is passed in, inlining this function is likely to allow // significant future optimization possibilities (like scalar promotion, and // scalarization), so encourage the inlining of the function. // else if (isa<AllocaInst>(I)) { if (ArgNo < CalleeFI.ArgumentWeights.size()) InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight; // If this is a constant being passed into the function, use the argument // weights calculated for the callee to determine how much will be folded // away with this information. } else if (isa<Constant>(I)) { if (ArgNo < CalleeFI.ArgumentWeights.size()) InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight; } } // Now that we have considered all of the factors that make the call site more // likely to be inlined, look at factors that make us not want to inline it. // Don't inline into something too big, which would make it bigger. // "size" here is the number of basic blocks, not instructions. // InlineCost += Caller->size()/15; // Look at the size of the callee. Each instruction counts as 5. InlineCost += CalleeFI.Metrics.NumInsts*5; return llvm::InlineCost::get(InlineCost); } // getInlineFudgeFactor - Return a > 1.0 factor if the inliner should use a // higher threshold to determine if the function call should be inlined. float InlineCostAnalyzer::getInlineFudgeFactor(CallSite CS) { Function *Callee = CS.getCalledFunction(); // Get information about the callee... FunctionInfo &CalleeFI = CachedFunctionInfo[Callee]; // If we haven't calculated this information yet, do so now. if (CalleeFI.Metrics.NumBlocks == 0) CalleeFI.analyzeFunction(Callee); float Factor = 1.0f; // Single BB functions are often written to be inlined. if (CalleeFI.Metrics.NumBlocks == 1) Factor += 0.5f; // Be more aggressive if the function contains a good chunk (if it mades up // at least 10% of the instructions) of vector instructions. if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/2) Factor += 2.0f; else if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/10) Factor += 1.5f; return Factor; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This webpage shows layout of YV12 and other YUV formats // http://www.fourcc.org/yuv.php // The actual conversion is best described here // http://en.wikipedia.org/wiki/YUV // An article on optimizing YUV conversion using tables instead of multiplies // http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf // // YV12 is a full plane of Y and a half height, half width chroma planes // YV16 is a full plane of Y and a full height, half width chroma planes // // ARGB pixel format is output, which on little endian is stored as BGRA. // The alpha is set to 255, allowing the application to use RGBA or RGB32. #include "media/base/yuv_convert.h" // Header for low level row functions. #include "media/base/yuv_row.h" #if USE_MMX #if defined(_MSC_VER) #include <intrin.h> #else #include <mmintrin.h> #endif #endif #if USE_SSE || USE_MMX #include <emmintrin.h> #endif namespace media { // 16.16 fixed point arithmetic. const int kFractionBits = 16; const int kFractionMax = 1 << kFractionBits; // Convert a frame of YUV to 32 bit ARGB. void ConvertYUVToRGB32(const uint8* y_buf, const uint8* u_buf, const uint8* v_buf, uint8* rgb_buf, int width, int height, int y_pitch, int uv_pitch, int rgb_pitch, YUVType yuv_type) { unsigned int y_shift = yuv_type; for (int y = 0; y < height; ++y) { uint8* rgb_row = rgb_buf + y * rgb_pitch; const uint8* y_ptr = y_buf + y * y_pitch; const uint8* u_ptr = u_buf + (y >> y_shift) * uv_pitch; const uint8* v_ptr = v_buf + (y >> y_shift) * uv_pitch; FastConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr, rgb_row, width); } // MMX used for FastConvertYUVToRGB32Row requires emms instruction. EMMS(); } #if USE_MMX #if USE_SSE // FilterRows combines two rows of the image using linear interpolation. // SSE2 version blends 8 pixels at a time. static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr, int width, int scaled_y_fraction) { __m128i zero = _mm_setzero_si128(); __m128i y1_fraction = _mm_set1_epi16( static_cast<uint16>(scaled_y_fraction >> 8)); __m128i y0_fraction = _mm_set1_epi16( static_cast<uint16>((scaled_y_fraction >> 8) ^ 255)); uint8* end = ybuf + width; if (ybuf < end) { do { __m128i y0 = _mm_loadl_epi64(reinterpret_cast<__m128i const*>(y0_ptr)); __m128i y1 = _mm_loadl_epi64(reinterpret_cast<__m128i const*>(y1_ptr)); y0 = _mm_unpacklo_epi8(y0, zero); y1 = _mm_unpacklo_epi8(y1, zero); y0 = _mm_mullo_epi16(y0, y0_fraction); y1 = _mm_mullo_epi16(y1, y1_fraction); y0 = _mm_add_epi16(y0, y1); // 8.8 fixed point result y0 = _mm_srli_epi16(y0, 8); y0 = _mm_packus_epi16(y0, y0); _mm_storel_epi64(reinterpret_cast<__m128i *>(ybuf), y0); y0_ptr += 8; y1_ptr += 8; ybuf += 8; } while (ybuf < end); } } #else // MMX version blends 4 pixels at a time. static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr, int width, int scaled_y_fraction) { __m64 zero = _mm_setzero_si64(); __m64 y1_fraction = _mm_set1_pi16( static_cast<int16>(scaled_y_fraction >> 8)); __m64 y0_fraction = _mm_set1_pi16( static_cast<int16>((scaled_y_fraction >> 8) ^ 255)); uint8* end = ybuf + width; if (ybuf < end) { do { __m64 y0 = _mm_cvtsi32_si64(*reinterpret_cast<const int *>(y0_ptr)); __m64 y1 = _mm_cvtsi32_si64(*reinterpret_cast<const int *>(y1_ptr)); y0 = _mm_unpacklo_pi8(y0, zero); y1 = _mm_unpacklo_pi8(y1, zero); y0 = _mm_mullo_pi16(y0, y0_fraction); y1 = _mm_mullo_pi16(y1, y1_fraction); y0 = _mm_add_pi16(y0, y1); // 8.8 fixed point result y0 = _mm_srli_pi16(y0, 8); y0 = _mm_packs_pu16(y0, y0); *reinterpret_cast<int *>(ybuf) = _mm_cvtsi64_si32(y0); y0_ptr += 4; y1_ptr += 4; ybuf += 4; } while (ybuf < end); } } #endif // USE_SSE #else // no MMX or SSE // C version blends 4 pixels at a time. static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr, int width, int scaled_y_fraction) { int y0_fraction = 65535 - scaled_y_fraction; int y1_fraction = scaled_y_fraction; uint8* end = ybuf + width; if (ybuf < end) { do { ybuf[0] = (y0_ptr[0] * (y0_fraction) + y1_ptr[0] * (y1_fraction)) >> 16; ybuf[1] = (y0_ptr[1] * (y0_fraction) + y1_ptr[1] * (y1_fraction)) >> 16; ybuf[2] = (y0_ptr[2] * (y0_fraction) + y1_ptr[2] * (y1_fraction)) >> 16; ybuf[3] = (y0_ptr[3] * (y0_fraction) + y1_ptr[3] * (y1_fraction)) >> 16; y0_ptr += 4; y1_ptr += 4; ybuf += 4; } while (ybuf < end); } } #endif // USE_MMX // Scale a frame of YUV to 32 bit ARGB. void ScaleYUVToRGB32(const uint8* y_buf, const uint8* u_buf, const uint8* v_buf, uint8* rgb_buf, int width, int height, int scaled_width, int scaled_height, int y_pitch, int uv_pitch, int rgb_pitch, YUVType yuv_type, Rotate view_rotate, ScaleFilter filter) { const int kFilterBufferSize = 8192; // Disable filtering if the screen is too big (to avoid buffer overflows). // This should never happen to regular users: they don't have monitors // wider than 8192 pixels. if (width > kFilterBufferSize) filter = FILTER_NONE; unsigned int y_shift = yuv_type; // Diagram showing origin and direction of source sampling. // ->0 4<- // 7 3 // // 6 5 // ->1 2<- // Rotations that start at right side of image. if ((view_rotate == ROTATE_180) || (view_rotate == ROTATE_270) || (view_rotate == MIRROR_ROTATE_0) || (view_rotate == MIRROR_ROTATE_90)) { y_buf += width - 1; u_buf += width / 2 - 1; v_buf += width / 2 - 1; width = -width; } // Rotations that start at bottom of image. if ((view_rotate == ROTATE_90) || (view_rotate == ROTATE_180) || (view_rotate == MIRROR_ROTATE_90) || (view_rotate == MIRROR_ROTATE_180)) { y_buf += (height - 1) * y_pitch; u_buf += ((height >> y_shift) - 1) * uv_pitch; v_buf += ((height >> y_shift) - 1) * uv_pitch; height = -height; } // Handle zero sized destination. if (scaled_width == 0 || scaled_height == 0) return; int scaled_dx = width * kFractionMax / scaled_width; int scaled_dy = height * kFractionMax / scaled_height; int scaled_dx_uv = scaled_dx; if ((view_rotate == ROTATE_90) || (view_rotate == ROTATE_270)) { int tmp = scaled_height; scaled_height = scaled_width; scaled_width = tmp; tmp = height; height = width; width = tmp; int original_dx = scaled_dx; int original_dy = scaled_dy; scaled_dx = ((original_dy >> kFractionBits) * y_pitch) << kFractionBits; scaled_dx_uv = ((original_dy >> kFractionBits) * uv_pitch) << kFractionBits; scaled_dy = original_dx; if (view_rotate == ROTATE_90) { y_pitch = -1; uv_pitch = -1; height = -height; } else { y_pitch = 1; uv_pitch = 1; } } // Need padding because FilterRows() may write up to 15 extra pixels // after the end for SSE2 version. uint8 ybuf[kFilterBufferSize + 16]; uint8 ubuf[kFilterBufferSize / 2 + 16]; uint8 vbuf[kFilterBufferSize / 2 + 16]; int yscale_fixed = (height << kFractionBits) / scaled_height; for (int y = 0; y < scaled_height; ++y) { uint8* dest_pixel = rgb_buf + y * rgb_pitch; int scaled_y = (y * yscale_fixed); const uint8* y0_ptr = y_buf + (scaled_y >> kFractionBits) * y_pitch; const uint8* y1_ptr = y0_ptr + y_pitch; const uint8* u0_ptr = u_buf + ((scaled_y >> kFractionBits) >> y_shift) * uv_pitch; const uint8* u1_ptr = u0_ptr + uv_pitch; const uint8* v0_ptr = v_buf + ((scaled_y >> kFractionBits) >> y_shift) * uv_pitch; const uint8* v1_ptr = v0_ptr + uv_pitch; int scaled_y_fraction = scaled_y & (kFractionMax - 1); int scaled_uv_fraction = (scaled_y >> y_shift) & (kFractionMax - 1); const uint8* y_ptr = y0_ptr; const uint8* u_ptr = u0_ptr; const uint8* v_ptr = v0_ptr; // Apply vertical filtering if necessary. if (filter == media::FILTER_BILINEAR && yscale_fixed != kFractionMax) { if (scaled_y_fraction && ((y + 1) < scaled_height)) { FilterRows(ybuf, y0_ptr, y1_ptr, width, scaled_y_fraction); y_ptr = ybuf; } if (scaled_uv_fraction && (((y >> y_shift) + 1) < (scaled_height >> y_shift))) { FilterRows(ubuf, u0_ptr, u1_ptr, (width + 1) / 2, scaled_uv_fraction); u_ptr = ubuf; FilterRows(vbuf, v0_ptr, v1_ptr, (width + 1) / 2, scaled_uv_fraction); v_ptr = vbuf; } } if (scaled_dx == kFractionMax) { // Not scaled FastConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, scaled_width); } else { if (filter == FILTER_BILINEAR) LinearScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, scaled_width, scaled_dx); else ScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, scaled_width, scaled_dx); } } // MMX used for FastConvertYUVToRGB32Row requires emms instruction. EMMS(); } } // namespace media <commit_msg>YUV scale clamp horizontal pixels when filtering BUG=19113 TEST=scale up by 4x and watch right edge for texel wrap.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This webpage shows layout of YV12 and other YUV formats // http://www.fourcc.org/yuv.php // The actual conversion is best described here // http://en.wikipedia.org/wiki/YUV // An article on optimizing YUV conversion using tables instead of multiplies // http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf // // YV12 is a full plane of Y and a half height, half width chroma planes // YV16 is a full plane of Y and a full height, half width chroma planes // // ARGB pixel format is output, which on little endian is stored as BGRA. // The alpha is set to 255, allowing the application to use RGBA or RGB32. #include "media/base/yuv_convert.h" // Header for low level row functions. #include "media/base/yuv_row.h" #if USE_MMX #if defined(_MSC_VER) #include <intrin.h> #else #include <mmintrin.h> #endif #endif #if USE_SSE || USE_MMX #include <emmintrin.h> #endif namespace media { // 16.16 fixed point arithmetic. const int kFractionBits = 16; const int kFractionMax = 1 << kFractionBits; // Convert a frame of YUV to 32 bit ARGB. void ConvertYUVToRGB32(const uint8* y_buf, const uint8* u_buf, const uint8* v_buf, uint8* rgb_buf, int width, int height, int y_pitch, int uv_pitch, int rgb_pitch, YUVType yuv_type) { unsigned int y_shift = yuv_type; for (int y = 0; y < height; ++y) { uint8* rgb_row = rgb_buf + y * rgb_pitch; const uint8* y_ptr = y_buf + y * y_pitch; const uint8* u_ptr = u_buf + (y >> y_shift) * uv_pitch; const uint8* v_ptr = v_buf + (y >> y_shift) * uv_pitch; FastConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr, rgb_row, width); } // MMX used for FastConvertYUVToRGB32Row requires emms instruction. EMMS(); } #if USE_MMX #if USE_SSE // FilterRows combines two rows of the image using linear interpolation. // SSE2 version blends 8 pixels at a time. static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr, int width, int scaled_y_fraction) { __m128i zero = _mm_setzero_si128(); __m128i y1_fraction = _mm_set1_epi16( static_cast<uint16>(scaled_y_fraction >> 8)); __m128i y0_fraction = _mm_set1_epi16( static_cast<uint16>((scaled_y_fraction >> 8) ^ 255)); uint8* end = ybuf + width; if (ybuf < end) { do { __m128i y0 = _mm_loadl_epi64(reinterpret_cast<__m128i const*>(y0_ptr)); __m128i y1 = _mm_loadl_epi64(reinterpret_cast<__m128i const*>(y1_ptr)); y0 = _mm_unpacklo_epi8(y0, zero); y1 = _mm_unpacklo_epi8(y1, zero); y0 = _mm_mullo_epi16(y0, y0_fraction); y1 = _mm_mullo_epi16(y1, y1_fraction); y0 = _mm_add_epi16(y0, y1); // 8.8 fixed point result y0 = _mm_srli_epi16(y0, 8); y0 = _mm_packus_epi16(y0, y0); _mm_storel_epi64(reinterpret_cast<__m128i *>(ybuf), y0); y0_ptr += 8; y1_ptr += 8; ybuf += 8; } while (ybuf < end); } } #else // MMX version blends 4 pixels at a time. static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr, int width, int scaled_y_fraction) { __m64 zero = _mm_setzero_si64(); __m64 y1_fraction = _mm_set1_pi16( static_cast<int16>(scaled_y_fraction >> 8)); __m64 y0_fraction = _mm_set1_pi16( static_cast<int16>((scaled_y_fraction >> 8) ^ 255)); uint8* end = ybuf + width; if (ybuf < end) { do { __m64 y0 = _mm_cvtsi32_si64(*reinterpret_cast<const int *>(y0_ptr)); __m64 y1 = _mm_cvtsi32_si64(*reinterpret_cast<const int *>(y1_ptr)); y0 = _mm_unpacklo_pi8(y0, zero); y1 = _mm_unpacklo_pi8(y1, zero); y0 = _mm_mullo_pi16(y0, y0_fraction); y1 = _mm_mullo_pi16(y1, y1_fraction); y0 = _mm_add_pi16(y0, y1); // 8.8 fixed point result y0 = _mm_srli_pi16(y0, 8); y0 = _mm_packs_pu16(y0, y0); *reinterpret_cast<int *>(ybuf) = _mm_cvtsi64_si32(y0); y0_ptr += 4; y1_ptr += 4; ybuf += 4; } while (ybuf < end); } } #endif // USE_SSE #else // no MMX or SSE // C version blends 4 pixels at a time. static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr, int width, int scaled_y_fraction) { int y0_fraction = 65536 - scaled_y_fraction; int y1_fraction = scaled_y_fraction; uint8* end = ybuf + width; if (ybuf < end) { do { ybuf[0] = (y0_ptr[0] * (y0_fraction) + y1_ptr[0] * (y1_fraction)) >> 16; ybuf[1] = (y0_ptr[1] * (y0_fraction) + y1_ptr[1] * (y1_fraction)) >> 16; ybuf[2] = (y0_ptr[2] * (y0_fraction) + y1_ptr[2] * (y1_fraction)) >> 16; ybuf[3] = (y0_ptr[3] * (y0_fraction) + y1_ptr[3] * (y1_fraction)) >> 16; y0_ptr += 4; y1_ptr += 4; ybuf += 4; } while (ybuf < end); } } #endif // USE_MMX // Scale a frame of YUV to 32 bit ARGB. void ScaleYUVToRGB32(const uint8* y_buf, const uint8* u_buf, const uint8* v_buf, uint8* rgb_buf, int width, int height, int scaled_width, int scaled_height, int y_pitch, int uv_pitch, int rgb_pitch, YUVType yuv_type, Rotate view_rotate, ScaleFilter filter) { const int kFilterBufferSize = 8192; // Disable filtering if the screen is too big (to avoid buffer overflows). // This should never happen to regular users: they don't have monitors // wider than 8192 pixels. if (width > kFilterBufferSize) filter = FILTER_NONE; unsigned int y_shift = yuv_type; // Diagram showing origin and direction of source sampling. // ->0 4<- // 7 3 // // 6 5 // ->1 2<- // Rotations that start at right side of image. if ((view_rotate == ROTATE_180) || (view_rotate == ROTATE_270) || (view_rotate == MIRROR_ROTATE_0) || (view_rotate == MIRROR_ROTATE_90)) { y_buf += width - 1; u_buf += width / 2 - 1; v_buf += width / 2 - 1; width = -width; } // Rotations that start at bottom of image. if ((view_rotate == ROTATE_90) || (view_rotate == ROTATE_180) || (view_rotate == MIRROR_ROTATE_90) || (view_rotate == MIRROR_ROTATE_180)) { y_buf += (height - 1) * y_pitch; u_buf += ((height >> y_shift) - 1) * uv_pitch; v_buf += ((height >> y_shift) - 1) * uv_pitch; height = -height; } // Handle zero sized destination. if (scaled_width == 0 || scaled_height == 0) return; int scaled_dx = width * kFractionMax / scaled_width; int scaled_dy = height * kFractionMax / scaled_height; int scaled_dx_uv = scaled_dx; if ((view_rotate == ROTATE_90) || (view_rotate == ROTATE_270)) { int tmp = scaled_height; scaled_height = scaled_width; scaled_width = tmp; tmp = height; height = width; width = tmp; int original_dx = scaled_dx; int original_dy = scaled_dy; scaled_dx = ((original_dy >> kFractionBits) * y_pitch) << kFractionBits; scaled_dx_uv = ((original_dy >> kFractionBits) * uv_pitch) << kFractionBits; scaled_dy = original_dx; if (view_rotate == ROTATE_90) { y_pitch = -1; uv_pitch = -1; height = -height; } else { y_pitch = 1; uv_pitch = 1; } } // Need padding because FilterRows() may write up to 15 extra pixels // after the end for SSE2 version. uint8 ybuf[kFilterBufferSize + 16]; uint8 ubuf[kFilterBufferSize / 2 + 16]; uint8 vbuf[kFilterBufferSize / 2 + 16]; int yscale_fixed = (height << kFractionBits) / scaled_height; for (int y = 0; y < scaled_height; ++y) { uint8* dest_pixel = rgb_buf + y * rgb_pitch; int scaled_y = (y * yscale_fixed); const uint8* y0_ptr = y_buf + (scaled_y >> kFractionBits) * y_pitch; const uint8* y1_ptr = y0_ptr + y_pitch; const uint8* u0_ptr = u_buf + ((scaled_y >> kFractionBits) >> y_shift) * uv_pitch; const uint8* u1_ptr = u0_ptr + uv_pitch; const uint8* v0_ptr = v_buf + ((scaled_y >> kFractionBits) >> y_shift) * uv_pitch; const uint8* v1_ptr = v0_ptr + uv_pitch; int scaled_y_fraction = scaled_y & (kFractionMax - 1); int scaled_uv_fraction = (scaled_y >> y_shift) & (kFractionMax - 1); const uint8* y_ptr = y0_ptr; const uint8* u_ptr = u0_ptr; const uint8* v_ptr = v0_ptr; // Apply vertical filtering if necessary. // TODO(fbarchard): Remove memcpy when not necessary. if (filter == media::FILTER_BILINEAR) { if (yscale_fixed != kFractionMax && scaled_y_fraction && ((y + 1) < scaled_height)) { FilterRows(ybuf, y0_ptr, y1_ptr, width, scaled_y_fraction); } else { memcpy(ybuf, y0_ptr, width); } y_ptr = ybuf; ybuf[width] = ybuf[width-1]; int uv_width = (width + 1) / 2; if (yscale_fixed != kFractionMax && scaled_uv_fraction && (((y >> y_shift) + 1) < (scaled_height >> y_shift))) { FilterRows(ubuf, u0_ptr, u1_ptr, uv_width, scaled_uv_fraction); FilterRows(vbuf, v0_ptr, v1_ptr, uv_width, scaled_uv_fraction); } else { memcpy(ubuf, u0_ptr, uv_width); memcpy(vbuf, v0_ptr, uv_width); } u_ptr = ubuf; v_ptr = vbuf; ubuf[(width + 1) / 2] = ybuf[(width + 1) / 2 -1]; vbuf[(width + 1) / 2] = vbuf[(width + 1) / 2 -1]; } if (scaled_dx == kFractionMax) { // Not scaled FastConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, scaled_width); } else { if (filter == FILTER_BILINEAR) LinearScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, scaled_width, scaled_dx); else ScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr, dest_pixel, scaled_width, scaled_dx); } } // MMX used for FastConvertYUVToRGB32Row requires emms instruction. EMMS(); } } // namespace media <|endoftext|>
<commit_before>//===--- Immediate.cpp - the swift immediate mode -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the implementation of the swift interpreter, which takes a // source file and JITs it. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "swift-immediate" #include "swift/Immediate/Immediate.h" #include "ImmediateImpl.h" #include "swift/Subsystems.h" #include "swift/AST/ASTContext.h" #include "swift/AST/DiagnosticsFrontend.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/Module.h" #include "swift/Frontend/Frontend.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/Basic/LLVM.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/config.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Linker/Linker.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Support/Path.h" #include <dlfcn.h> using namespace swift; using namespace swift::immediate; static bool loadRuntimeLib(StringRef sharedLibName, StringRef runtimeLibPath) { // FIXME: Need error-checking. llvm::SmallString<128> Path = runtimeLibPath; llvm::sys::path::append(Path, sharedLibName); return dlopen(Path.c_str(), RTLD_LAZY | RTLD_GLOBAL); } bool swift::immediate::loadSwiftRuntime(StringRef runtimeLibPath) { return loadRuntimeLib("libswiftCore" LTDL_SHLIB_EXT, runtimeLibPath); } static bool tryLoadLibrary(LinkLibrary linkLib, SearchPathOptions searchPathOpts) { llvm::SmallString<128> path = linkLib.getName(); // If we have an absolute or relative path, just try to load it now. if (llvm::sys::path::has_parent_path(path.str())) { return dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL); } bool success = false; switch (linkLib.getKind()) { case LibraryKind::Library: { llvm::SmallString<32> stem; if (llvm::sys::path::has_extension(path.str())) { stem = std::move(path); } else { // FIXME: Try the appropriate extension for the current platform? stem = "lib"; stem += path; stem += LTDL_SHLIB_EXT; } // Try user-provided library search paths first. for (auto &libDir : searchPathOpts.LibrarySearchPaths) { path = libDir; llvm::sys::path::append(path, stem.str()); success = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (success) break; } // Let dlopen determine the best search paths. if (!success) success = dlopen(stem.c_str(), RTLD_LAZY | RTLD_GLOBAL); // If that fails, try our runtime library path. if (!success) success = loadRuntimeLib(stem, searchPathOpts.RuntimeLibraryPath); break; } case LibraryKind::Framework: { // If we have a framework, mangle the name to point to the framework // binary. llvm::SmallString<64> frameworkPart{std::move(path)}; frameworkPart += ".framework"; llvm::sys::path::append(frameworkPart, linkLib.getName()); // Try user-provided framework search paths first; frameworks contain // binaries as well as modules. for (auto &frameworkDir : searchPathOpts.FrameworkSearchPaths) { path = frameworkDir; llvm::sys::path::append(path, frameworkPart.str()); success = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (success) break; } // If that fails, let dlopen search for system frameworks. if (!success) success = dlopen(frameworkPart.c_str(), RTLD_LAZY | RTLD_GLOBAL); break; } } return success; } bool swift::immediate::tryLoadLibraries(ArrayRef<LinkLibrary> LinkLibraries, SearchPathOptions SearchPathOpts, DiagnosticEngine &Diags) { SmallVector<bool, 4> LoadedLibraries; LoadedLibraries.append(LinkLibraries.size(), false); // Libraries are not sorted in the topological order of dependencies, and we // don't know the dependencies in advance. Try to load all libraries until // we stop making progress. bool HadProgress; do { HadProgress = false; for (unsigned i = 0; i != LinkLibraries.size(); ++i) { if (!LoadedLibraries[i] && tryLoadLibrary(LinkLibraries[i], SearchPathOpts)) { LoadedLibraries[i] = true; HadProgress = true; } } } while (HadProgress); return std::all_of(LoadedLibraries.begin(), LoadedLibraries.end(), [](bool Value) { return Value; }); } static void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI, void *Context) { // This assert self documents our precondition that Context is always // nullptr. It seems that parts of LLVM are using the flexibility of having a // context. We don't really care about this. assert(Context == nullptr && "We assume Context is always a nullptr"); if (DI.getSeverity() != llvm::DS_Error) return; std::string MsgStorage; { llvm::raw_string_ostream Stream(MsgStorage); llvm::DiagnosticPrinterRawOStream DP(Stream); DI.print(DP); } llvm::errs() << "Error linking swift modules\n"; llvm::errs() << MsgStorage << "\n"; } bool swift::immediate::linkLLVMModules(llvm::Module *Module, llvm::Module *SubModule // TODO: reactivate the linker mode if it is // supported in llvm again. Otherwise remove the // commented code completely. /*, llvm::Linker::LinkerMode LinkerMode */) { llvm::LLVMContext &Ctx = SubModule->getContext(); auto OldHandler = Ctx.getDiagnosticHandler(); void *OldDiagnosticContext = Ctx.getDiagnosticContext(); Ctx.setDiagnosticHandler(linkerDiagnosticHandler, nullptr); // TODO: reactivate the linker mode if it is // supported in llvm again. Otherwise remove the // commented code completely. bool Failed = llvm::Linker::LinkModules(Module, SubModule /*, LinkerMode*/); Ctx.setDiagnosticHandler(OldHandler, OldDiagnosticContext); return !Failed; } bool swift::immediate::IRGenImportedModules( CompilerInstance &CI, llvm::Module &Module, llvm::SmallPtrSet<swift::Module *, 8> &ImportedModules, SmallVectorImpl<llvm::Function*> &InitFns, IRGenOptions &IRGenOpts, const SILOptions &SILOpts) { swift::Module *M = CI.getMainModule(); // Perform autolinking. SmallVector<LinkLibrary, 4> AllLinkLibraries(IRGenOpts.LinkLibraries); auto addLinkLibrary = [&](LinkLibrary linkLib) { AllLinkLibraries.push_back(linkLib); }; M->forAllVisibleModules({}, /*includePrivateTopLevel=*/true, [&](Module::ImportedModule import) { import.second->collectLinkLibraries(addLinkLibrary); }); // Hack to handle thunks eagerly synthesized by the Clang importer. swift::Module *prev = nullptr; for (auto external : CI.getASTContext().ExternalDefinitions) { swift::Module *next = external->getModuleContext(); if (next == prev) continue; next->collectLinkLibraries(addLinkLibrary); prev = next; } tryLoadLibraries(AllLinkLibraries, CI.getASTContext().SearchPathOpts, CI.getDiags()); ImportedModules.insert(M); if (!CI.hasSourceImport()) return false; // IRGen the modules this module depends on. This is only really necessary // for imported source, but that's a very convenient thing to do in -i mode. // FIXME: Crawling all loaded modules is a hack. // FIXME: And re-doing SILGen, SIL-linking, SIL diagnostics, and IRGen is // expensive, because it's not properly being limited to new things right now. bool hadError = false; for (auto &entry : CI.getASTContext().LoadedModules) { swift::Module *import = entry.second; if (!ImportedModules.insert(import).second) continue; std::unique_ptr<SILModule> SILMod = performSILGeneration(import, CI.getSILOptions()); performSILLinking(SILMod.get()); if (runSILDiagnosticPasses(*SILMod)) { hadError = true; break; } // FIXME: We shouldn't need to use the global context here, but // something is persisting across calls to performIRGeneration. auto SubModule = performIRGeneration(IRGenOpts, import, SILMod.get(), import->getName().str(), llvm::getGlobalContext()); if (CI.getASTContext().hadError()) { hadError = true; break; } if (!linkLLVMModules(&Module, SubModule.get() // TODO: reactivate the linker mode if it is // supported in llvm again. Otherwise remove the // commented code completely. /*, llvm::Linker::DestroySource */)) { hadError = true; break; } // FIXME: This is an ugly hack; need to figure out how this should // actually work. SmallVector<char, 20> NameBuf; StringRef InitFnName = (import->getName().str() + ".init").toStringRef(NameBuf); llvm::Function *InitFn = Module.getFunction(InitFnName); if (InitFn) InitFns.push_back(InitFn); } return hadError; } int swift::RunImmediately(CompilerInstance &CI, const ProcessCmdLine &CmdLine, IRGenOptions &IRGenOpts, const SILOptions &SILOpts) { ASTContext &Context = CI.getASTContext(); // IRGen the main module. auto *swiftModule = CI.getMainModule(); // FIXME: We shouldn't need to use the global context here, but // something is persisting across calls to performIRGeneration. auto ModuleOwner = performIRGeneration( IRGenOpts, swiftModule, CI.getSILModule(), swiftModule->getName().str(), llvm::getGlobalContext()); auto *Module = ModuleOwner.get(); if (Context.hadError()) return -1; SmallVector<llvm::Function*, 8> InitFns; llvm::SmallPtrSet<swift::Module *, 8> ImportedModules; if (IRGenImportedModules(CI, *Module, ImportedModules, InitFns, IRGenOpts, SILOpts)) return -1; llvm::PassManagerBuilder PMBuilder; PMBuilder.OptLevel = 2; PMBuilder.Inliner = llvm::createFunctionInliningPass(200); if (!loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPath)) { CI.getDiags().diagnose(SourceLoc(), diag::error_immediate_mode_missing_stdlib); return -1; } // Build the ExecutionEngine. llvm::EngineBuilder builder(std::move(ModuleOwner)); std::string ErrorMsg; llvm::TargetOptions TargetOpt; std::string CPU; std::vector<std::string> Features; std::tie(TargetOpt, CPU, Features) = getIRTargetOptions(IRGenOpts, swiftModule->getASTContext()); builder.setRelocationModel(llvm::Reloc::PIC_); builder.setTargetOptions(TargetOpt); builder.setMCPU(CPU); builder.setMAttrs(Features); builder.setErrorStr(&ErrorMsg); builder.setEngineKind(llvm::EngineKind::JIT); llvm::ExecutionEngine *EE = builder.create(); if (!EE) { llvm::errs() << "Error loading JIT: " << ErrorMsg; return -1; } DEBUG(llvm::dbgs() << "Module to be executed:\n"; Module->dump()); EE->finalizeObject(); // Run the generated program. for (auto InitFn : InitFns) { DEBUG(llvm::dbgs() << "Running initialization function " << InitFn->getName() << '\n'); EE->runFunctionAsMain(InitFn, CmdLine, 0); } DEBUG(llvm::dbgs() << "Running static constructors\n"); EE->runStaticConstructorsDestructors(false); DEBUG(llvm::dbgs() << "Running main\n"); llvm::Function *EntryFn = Module->getFunction("main"); return EE->runFunctionAsMain(EntryFn, CmdLine, 0); } <commit_msg>Update for upstream linker changes.<commit_after>//===--- Immediate.cpp - the swift immediate mode -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the implementation of the swift interpreter, which takes a // source file and JITs it. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "swift-immediate" #include "swift/Immediate/Immediate.h" #include "ImmediateImpl.h" #include "swift/Subsystems.h" #include "swift/AST/ASTContext.h" #include "swift/AST/DiagnosticsFrontend.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/Module.h" #include "swift/Frontend/Frontend.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/Basic/LLVM.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/config.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Linker/Linker.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Support/Path.h" #include <dlfcn.h> using namespace swift; using namespace swift::immediate; static bool loadRuntimeLib(StringRef sharedLibName, StringRef runtimeLibPath) { // FIXME: Need error-checking. llvm::SmallString<128> Path = runtimeLibPath; llvm::sys::path::append(Path, sharedLibName); return dlopen(Path.c_str(), RTLD_LAZY | RTLD_GLOBAL); } bool swift::immediate::loadSwiftRuntime(StringRef runtimeLibPath) { return loadRuntimeLib("libswiftCore" LTDL_SHLIB_EXT, runtimeLibPath); } static bool tryLoadLibrary(LinkLibrary linkLib, SearchPathOptions searchPathOpts) { llvm::SmallString<128> path = linkLib.getName(); // If we have an absolute or relative path, just try to load it now. if (llvm::sys::path::has_parent_path(path.str())) { return dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL); } bool success = false; switch (linkLib.getKind()) { case LibraryKind::Library: { llvm::SmallString<32> stem; if (llvm::sys::path::has_extension(path.str())) { stem = std::move(path); } else { // FIXME: Try the appropriate extension for the current platform? stem = "lib"; stem += path; stem += LTDL_SHLIB_EXT; } // Try user-provided library search paths first. for (auto &libDir : searchPathOpts.LibrarySearchPaths) { path = libDir; llvm::sys::path::append(path, stem.str()); success = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (success) break; } // Let dlopen determine the best search paths. if (!success) success = dlopen(stem.c_str(), RTLD_LAZY | RTLD_GLOBAL); // If that fails, try our runtime library path. if (!success) success = loadRuntimeLib(stem, searchPathOpts.RuntimeLibraryPath); break; } case LibraryKind::Framework: { // If we have a framework, mangle the name to point to the framework // binary. llvm::SmallString<64> frameworkPart{std::move(path)}; frameworkPart += ".framework"; llvm::sys::path::append(frameworkPart, linkLib.getName()); // Try user-provided framework search paths first; frameworks contain // binaries as well as modules. for (auto &frameworkDir : searchPathOpts.FrameworkSearchPaths) { path = frameworkDir; llvm::sys::path::append(path, frameworkPart.str()); success = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL); if (success) break; } // If that fails, let dlopen search for system frameworks. if (!success) success = dlopen(frameworkPart.c_str(), RTLD_LAZY | RTLD_GLOBAL); break; } } return success; } bool swift::immediate::tryLoadLibraries(ArrayRef<LinkLibrary> LinkLibraries, SearchPathOptions SearchPathOpts, DiagnosticEngine &Diags) { SmallVector<bool, 4> LoadedLibraries; LoadedLibraries.append(LinkLibraries.size(), false); // Libraries are not sorted in the topological order of dependencies, and we // don't know the dependencies in advance. Try to load all libraries until // we stop making progress. bool HadProgress; do { HadProgress = false; for (unsigned i = 0; i != LinkLibraries.size(); ++i) { if (!LoadedLibraries[i] && tryLoadLibrary(LinkLibraries[i], SearchPathOpts)) { LoadedLibraries[i] = true; HadProgress = true; } } } while (HadProgress); return std::all_of(LoadedLibraries.begin(), LoadedLibraries.end(), [](bool Value) { return Value; }); } static void linkerDiagnosticHandlerNoCtx(const llvm::DiagnosticInfo &DI) { if (DI.getSeverity() != llvm::DS_Error) return; std::string MsgStorage; { llvm::raw_string_ostream Stream(MsgStorage); llvm::DiagnosticPrinterRawOStream DP(Stream); DI.print(DP); } llvm::errs() << "Error linking swift modules\n"; llvm::errs() << MsgStorage << "\n"; } static void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI, void *Context) { // This assert self documents our precondition that Context is always // nullptr. It seems that parts of LLVM are using the flexibility of having a // context. We don't really care about this. assert(Context == nullptr && "We assume Context is always a nullptr"); return linkerDiagnosticHandlerNoCtx(DI); } bool swift::immediate::linkLLVMModules(llvm::Module *Module, llvm::Module *SubModule // TODO: reactivate the linker mode if it is // supported in llvm again. Otherwise remove the // commented code completely. /*, llvm::Linker::LinkerMode LinkerMode */) { llvm::LLVMContext &Ctx = SubModule->getContext(); auto OldHandler = Ctx.getDiagnosticHandler(); void *OldDiagnosticContext = Ctx.getDiagnosticContext(); Ctx.setDiagnosticHandler(linkerDiagnosticHandler, nullptr); // TODO: reactivate the linker mode if it is // supported in llvm again. Otherwise remove the // commented code completely. bool Failed = llvm::Linker::linkModules(*Module, *SubModule, linkerDiagnosticHandlerNoCtx /*, LinkerMode*/); Ctx.setDiagnosticHandler(OldHandler, OldDiagnosticContext); return !Failed; } bool swift::immediate::IRGenImportedModules( CompilerInstance &CI, llvm::Module &Module, llvm::SmallPtrSet<swift::Module *, 8> &ImportedModules, SmallVectorImpl<llvm::Function*> &InitFns, IRGenOptions &IRGenOpts, const SILOptions &SILOpts) { swift::Module *M = CI.getMainModule(); // Perform autolinking. SmallVector<LinkLibrary, 4> AllLinkLibraries(IRGenOpts.LinkLibraries); auto addLinkLibrary = [&](LinkLibrary linkLib) { AllLinkLibraries.push_back(linkLib); }; M->forAllVisibleModules({}, /*includePrivateTopLevel=*/true, [&](Module::ImportedModule import) { import.second->collectLinkLibraries(addLinkLibrary); }); // Hack to handle thunks eagerly synthesized by the Clang importer. swift::Module *prev = nullptr; for (auto external : CI.getASTContext().ExternalDefinitions) { swift::Module *next = external->getModuleContext(); if (next == prev) continue; next->collectLinkLibraries(addLinkLibrary); prev = next; } tryLoadLibraries(AllLinkLibraries, CI.getASTContext().SearchPathOpts, CI.getDiags()); ImportedModules.insert(M); if (!CI.hasSourceImport()) return false; // IRGen the modules this module depends on. This is only really necessary // for imported source, but that's a very convenient thing to do in -i mode. // FIXME: Crawling all loaded modules is a hack. // FIXME: And re-doing SILGen, SIL-linking, SIL diagnostics, and IRGen is // expensive, because it's not properly being limited to new things right now. bool hadError = false; for (auto &entry : CI.getASTContext().LoadedModules) { swift::Module *import = entry.second; if (!ImportedModules.insert(import).second) continue; std::unique_ptr<SILModule> SILMod = performSILGeneration(import, CI.getSILOptions()); performSILLinking(SILMod.get()); if (runSILDiagnosticPasses(*SILMod)) { hadError = true; break; } // FIXME: We shouldn't need to use the global context here, but // something is persisting across calls to performIRGeneration. auto SubModule = performIRGeneration(IRGenOpts, import, SILMod.get(), import->getName().str(), llvm::getGlobalContext()); if (CI.getASTContext().hadError()) { hadError = true; break; } if (!linkLLVMModules(&Module, SubModule.get() // TODO: reactivate the linker mode if it is // supported in llvm again. Otherwise remove the // commented code completely. /*, llvm::Linker::DestroySource */)) { hadError = true; break; } // FIXME: This is an ugly hack; need to figure out how this should // actually work. SmallVector<char, 20> NameBuf; StringRef InitFnName = (import->getName().str() + ".init").toStringRef(NameBuf); llvm::Function *InitFn = Module.getFunction(InitFnName); if (InitFn) InitFns.push_back(InitFn); } return hadError; } int swift::RunImmediately(CompilerInstance &CI, const ProcessCmdLine &CmdLine, IRGenOptions &IRGenOpts, const SILOptions &SILOpts) { ASTContext &Context = CI.getASTContext(); // IRGen the main module. auto *swiftModule = CI.getMainModule(); // FIXME: We shouldn't need to use the global context here, but // something is persisting across calls to performIRGeneration. auto ModuleOwner = performIRGeneration( IRGenOpts, swiftModule, CI.getSILModule(), swiftModule->getName().str(), llvm::getGlobalContext()); auto *Module = ModuleOwner.get(); if (Context.hadError()) return -1; SmallVector<llvm::Function*, 8> InitFns; llvm::SmallPtrSet<swift::Module *, 8> ImportedModules; if (IRGenImportedModules(CI, *Module, ImportedModules, InitFns, IRGenOpts, SILOpts)) return -1; llvm::PassManagerBuilder PMBuilder; PMBuilder.OptLevel = 2; PMBuilder.Inliner = llvm::createFunctionInliningPass(200); if (!loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPath)) { CI.getDiags().diagnose(SourceLoc(), diag::error_immediate_mode_missing_stdlib); return -1; } // Build the ExecutionEngine. llvm::EngineBuilder builder(std::move(ModuleOwner)); std::string ErrorMsg; llvm::TargetOptions TargetOpt; std::string CPU; std::vector<std::string> Features; std::tie(TargetOpt, CPU, Features) = getIRTargetOptions(IRGenOpts, swiftModule->getASTContext()); builder.setRelocationModel(llvm::Reloc::PIC_); builder.setTargetOptions(TargetOpt); builder.setMCPU(CPU); builder.setMAttrs(Features); builder.setErrorStr(&ErrorMsg); builder.setEngineKind(llvm::EngineKind::JIT); llvm::ExecutionEngine *EE = builder.create(); if (!EE) { llvm::errs() << "Error loading JIT: " << ErrorMsg; return -1; } DEBUG(llvm::dbgs() << "Module to be executed:\n"; Module->dump()); EE->finalizeObject(); // Run the generated program. for (auto InitFn : InitFns) { DEBUG(llvm::dbgs() << "Running initialization function " << InitFn->getName() << '\n'); EE->runFunctionAsMain(InitFn, CmdLine, 0); } DEBUG(llvm::dbgs() << "Running static constructors\n"); EE->runStaticConstructorsDestructors(false); DEBUG(llvm::dbgs() << "Running main\n"); llvm::Function *EntryFn = Module->getFunction("main"); return EE->runFunctionAsMain(EntryFn, CmdLine, 0); } <|endoftext|>
<commit_before>//===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements misc. GraphWriter support routines. // //===----------------------------------------------------------------------===// #include "llvm/Support/GraphWriter.h" #include "llvm/System/Path.h" #include "llvm/System/Program.h" #include "llvm/Config/config.h" using namespace llvm; std::string llvm::DOT::EscapeString(const std::string &Label) { std::string Str(Label); for (unsigned i = 0; i != Str.length(); ++i) switch (Str[i]) { case '\n': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; Str[i] = 'n'; break; case '\t': Str.insert(Str.begin()+i, ' '); // Convert to two spaces ++i; Str[i] = ' '; break; case '\\': if (i+1 != Str.length()) switch (Str[i+1]) { case 'l': continue; // don't disturb \l case '|': case '{': case '}': Str.erase(Str.begin()+i); continue; default: break; } case '{': case '}': case '<': case '>': case '|': case '"': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; // don't infinite loop break; } return Str; } void llvm::DisplayGraph(const sys::Path &Filename, bool wait, GraphProgram::Name program) { std::string ErrMsg; #if HAVE_GRAPHVIZ sys::Path Graphviz(LLVM_PATH_GRAPHVIZ); std::vector<const char*> args; args.push_back(Graphviz.c_str()); args.push_back(Filename.c_str()); args.push_back(0); errs() << "Running 'Graphviz' program... "; if (sys::Program::ExecuteAndWait(Graphviz, &args[0],0,0,0,0,&ErrMsg)) errs() << "Error viewing graph " << Filename.str() << ": " << ErrMsg << "\n"; else Filename.eraseFromDisk(); #elif (HAVE_GV && (HAVE_DOT || HAVE_FDP || HAVE_NEATO || \ HAVE_TWOPI || HAVE_CIRCO)) sys::Path PSFilename = Filename; PSFilename.appendSuffix("ps"); sys::Path prog; // Set default grapher #if HAVE_CIRCO prog = sys::Path(LLVM_PATH_CIRCO); #endif #if HAVE_TWOPI prog = sys::Path(LLVM_PATH_TWOPI); #endif #if HAVE_NEATO prog = sys::Path(LLVM_PATH_NEATO); #endif #if HAVE_FDP prog = sys::Path(LLVM_PATH_FDP); #endif #if HAVE_DOT prog = sys::Path(LLVM_PATH_DOT); #endif // Find which program the user wants #if HAVE_DOT if (program == GraphProgram::DOT) prog = sys::Path(LLVM_PATH_DOT); #endif #if (HAVE_FDP) if (program == GraphProgram::FDP) prog = sys::Path(LLVM_PATH_FDP); #endif #if (HAVE_NEATO) if (program == GraphProgram::NEATO) prog = sys::Path(LLVM_PATH_NEATO); #endif #if (HAVE_TWOPI) if (program == GraphProgram::TWOPI) prog = sys::Path(LLVM_PATH_TWOPI); #endif #if (HAVE_CIRCO) if (program == GraphProgram::CIRCO) prog = sys::Path(LLVM_PATH_CIRCO); #endif std::vector<const char*> args; args.push_back(prog.c_str()); args.push_back("-Tps"); args.push_back("-Nfontname=Courier"); args.push_back("-Gsize=7.5,10"); args.push_back(Filename.c_str()); args.push_back("-o"); args.push_back(PSFilename.c_str()); args.push_back(0); errs() << "Running '" << prog.str() << "' program... "; if (sys::Program::ExecuteAndWait(prog, &args[0], 0, 0, 0, 0, &ErrMsg)) { errs() << "Error viewing graph " << Filename.str() << ": '" << ErrMsg << "\n"; } else { errs() << " done. \n"; sys::Path gv(LLVM_PATH_GV); args.clear(); args.push_back(gv.c_str()); args.push_back(PSFilename.c_str()); args.push_back("--spartan"); args.push_back(0); ErrMsg.clear(); if (wait) { if (sys::Program::ExecuteAndWait(gv, &args[0],0,0,0,0,&ErrMsg)) errs() << "Error viewing graph: " << ErrMsg << "\n"; Filename.eraseFromDisk(); PSFilename.eraseFromDisk(); } else { sys::Program::ExecuteNoWait(gv, &args[0],0,0,0,&ErrMsg); errs() << "Remember to erase graph files: " << Filename.str() << " " << PSFilename.str() << "\n"; } } #elif HAVE_DOTTY sys::Path dotty(LLVM_PATH_DOTTY); std::vector<const char*> args; args.push_back(dotty.c_str()); args.push_back(Filename.c_str()); args.push_back(0); errs() << "Running 'dotty' program... "; if (sys::Program::ExecuteAndWait(dotty, &args[0],0,0,0,0,&ErrMsg)) { errs() << "Error viewing graph " << Filename.str() << ": " << ErrMsg << "\n"; } else { // Dotty spawns another app and doesn't wait until it returns #if defined (__MINGW32__) || defined (_WINDOWS) return; #endif Filename.eraseFromDisk(); } #endif } <commit_msg>reduce indentation<commit_after>//===-- GraphWriter.cpp - Implements GraphWriter support routines ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements misc. GraphWriter support routines. // //===----------------------------------------------------------------------===// #include "llvm/Support/GraphWriter.h" #include "llvm/System/Path.h" #include "llvm/System/Program.h" #include "llvm/Config/config.h" using namespace llvm; std::string llvm::DOT::EscapeString(const std::string &Label) { std::string Str(Label); for (unsigned i = 0; i != Str.length(); ++i) switch (Str[i]) { case '\n': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; Str[i] = 'n'; break; case '\t': Str.insert(Str.begin()+i, ' '); // Convert to two spaces ++i; Str[i] = ' '; break; case '\\': if (i+1 != Str.length()) switch (Str[i+1]) { case 'l': continue; // don't disturb \l case '|': case '{': case '}': Str.erase(Str.begin()+i); continue; default: break; } case '{': case '}': case '<': case '>': case '|': case '"': Str.insert(Str.begin()+i, '\\'); // Escape character... ++i; // don't infinite loop break; } return Str; } void llvm::DisplayGraph(const sys::Path &Filename, bool wait, GraphProgram::Name program) { std::string ErrMsg; #if HAVE_GRAPHVIZ sys::Path Graphviz(LLVM_PATH_GRAPHVIZ); std::vector<const char*> args; args.push_back(Graphviz.c_str()); args.push_back(Filename.c_str()); args.push_back(0); errs() << "Running 'Graphviz' program... "; if (sys::Program::ExecuteAndWait(Graphviz, &args[0],0,0,0,0,&ErrMsg)) errs() << "Error viewing graph " << Filename.str() << ": " << ErrMsg << "\n"; else Filename.eraseFromDisk(); #elif (HAVE_GV && (HAVE_DOT || HAVE_FDP || HAVE_NEATO || \ HAVE_TWOPI || HAVE_CIRCO)) sys::Path PSFilename = Filename; PSFilename.appendSuffix("ps"); sys::Path prog; // Set default grapher #if HAVE_CIRCO prog = sys::Path(LLVM_PATH_CIRCO); #endif #if HAVE_TWOPI prog = sys::Path(LLVM_PATH_TWOPI); #endif #if HAVE_NEATO prog = sys::Path(LLVM_PATH_NEATO); #endif #if HAVE_FDP prog = sys::Path(LLVM_PATH_FDP); #endif #if HAVE_DOT prog = sys::Path(LLVM_PATH_DOT); #endif // Find which program the user wants #if HAVE_DOT if (program == GraphProgram::DOT) prog = sys::Path(LLVM_PATH_DOT); #endif #if (HAVE_FDP) if (program == GraphProgram::FDP) prog = sys::Path(LLVM_PATH_FDP); #endif #if (HAVE_NEATO) if (program == GraphProgram::NEATO) prog = sys::Path(LLVM_PATH_NEATO); #endif #if (HAVE_TWOPI) if (program == GraphProgram::TWOPI) prog = sys::Path(LLVM_PATH_TWOPI); #endif #if (HAVE_CIRCO) if (program == GraphProgram::CIRCO) prog = sys::Path(LLVM_PATH_CIRCO); #endif std::vector<const char*> args; args.push_back(prog.c_str()); args.push_back("-Tps"); args.push_back("-Nfontname=Courier"); args.push_back("-Gsize=7.5,10"); args.push_back(Filename.c_str()); args.push_back("-o"); args.push_back(PSFilename.c_str()); args.push_back(0); errs() << "Running '" << prog.str() << "' program... "; if (sys::Program::ExecuteAndWait(prog, &args[0], 0, 0, 0, 0, &ErrMsg)) { errs() << "Error viewing graph " << Filename.str() << ": '" << ErrMsg << "\n"; return; } errs() << " done. \n"; sys::Path gv(LLVM_PATH_GV); args.clear(); args.push_back(gv.c_str()); args.push_back(PSFilename.c_str()); args.push_back("--spartan"); args.push_back(0); ErrMsg.clear(); if (wait) { if (sys::Program::ExecuteAndWait(gv, &args[0],0,0,0,0,&ErrMsg)) errs() << "Error viewing graph: " << ErrMsg << "\n"; Filename.eraseFromDisk(); PSFilename.eraseFromDisk(); } else { sys::Program::ExecuteNoWait(gv, &args[0],0,0,0,&ErrMsg); errs() << "Remember to erase graph files: " << Filename.str() << " " << PSFilename.str() << "\n"; } #elif HAVE_DOTTY sys::Path dotty(LLVM_PATH_DOTTY); std::vector<const char*> args; args.push_back(dotty.c_str()); args.push_back(Filename.c_str()); args.push_back(0); errs() << "Running 'dotty' program... "; if (sys::Program::ExecuteAndWait(dotty, &args[0],0,0,0,0,&ErrMsg)) { errs() << "Error viewing graph " << Filename.str() << ": " << ErrMsg << "\n"; } else { // Dotty spawns another app and doesn't wait until it returns #if defined (__MINGW32__) || defined (_WINDOWS) return; #endif Filename.eraseFromDisk(); } #endif } <|endoftext|>
<commit_before>#include <memory> #include <UnitTest++/UnitTest++.h> #include "Article.h" #include "ArticleCollection.h" #include "WalkerException.h" SUITE(CollectionMergeTests) { using namespace WikiWalker; // dragon -> treasure // -> fire // -> flying // cat -> - // apple -> fruit // window -> outside void createArticlesAndFillFirst(ArticleCollection & ac) { auto a1 = std::make_shared<Article>("Dragon"); auto a2 = std::make_shared<Article>("Treasure"); auto a3 = std::make_shared<Article>("Fire"); auto a4 = std::make_shared<Article>("Flying"); a1->addLink(a2); a1->addLink(a3); a1->addLink(a4); auto a5 = std::make_shared<Article>("Cat"); auto a6 = std::make_shared<Article>("Apple"); auto a7 = std::make_shared<Article>("Fruit"); a6->addLink(a7); auto a8 = std::make_shared<Article>("Window"); auto a9 = std::make_shared<Article>("Outside"); a8->addLink(a9); ac.add(a1); ac.add(a2); ac.add(a3); ac.add(a4); ac.add(a5); ac.add(a6); ac.add(a7); ac.add(a8); ac.add(a9); } // dragon -> - // cat -> milk // -> lazy // wood -> house // window -> glass // -> cleaning void createArticlesAndFillSecond(ArticleCollection & ac) { auto b1 = std::make_shared<Article>("Dragon"); auto b2 = std::make_shared<Article>("Cat"); auto b9 = std::make_shared<Article>("Milk"); auto b3 = std::make_shared<Article>("Lazy"); b2->addLink(b3); b2->addLink(b9); auto b4 = std::make_shared<Article>("Wood"); auto b5 = std::make_shared<Article>("House"); b4->addLink(b5); auto b6 = std::make_shared<Article>("Window"); auto b7 = std::make_shared<Article>("Glass"); auto b8 = std::make_shared<Article>("Cleaning"); b6->addLink(b7); b6->addLink(b8); ac.add(b1); ac.add(b2); ac.add(b3); ac.add(b4); ac.add(b5); ac.add(b6); ac.add(b7); ac.add(b8); ac.add(b9); } // check when first half is preferred void checkFirst(ArticleCollection & c1) { CHECK_EQUAL(15, c1.getNumArticles()); auto ptr = c1.get("Dragon"); CHECK(ptr != nullptr); CHECK_EQUAL(3, ptr->getNumLinks()); ptr = c1.get("Cat"); CHECK(ptr != nullptr); CHECK_THROW(ptr->getNumLinks(), WalkerException); ptr = c1.get("Window"); CHECK(ptr != nullptr); CHECK_EQUAL(1, ptr->getNumLinks()); } // check second half is preferred void checkSecond(ArticleCollection & c2) { CHECK_EQUAL(15, c2.getNumArticles()); auto ptr = c2.get("Dragon"); CHECK(ptr != nullptr); CHECK_THROW(ptr->getNumLinks(), WalkerException); ptr = c2.get("Cat"); CHECK(ptr != nullptr); CHECK_EQUAL(2, ptr->getNumLinks()); ptr = c2.get("Window"); CHECK(ptr != nullptr); CHECK_EQUAL(2, ptr->getNumLinks()); } TEST(ArticleCollection_TestMergeIgnore) { { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); a1.merge(a2, ArticleCollection::MergeStrategy::IgnoreDuplicates); checkFirst(a1); } { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); // reverse merge a2.merge(a1, ArticleCollection::MergeStrategy::IgnoreDuplicates); checkSecond(a2); } } // overwrite behaves "exactly the opposite" of ignore TEST(ArticleCollection_TestMergeOverwrite) { { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); a1.merge(a2, ArticleCollection::MergeStrategy::AlwaysOverwrite); checkSecond(a1); } { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); // reverse merge a2.merge(a1, ArticleCollection::MergeStrategy::AlwaysOverwrite); checkFirst(a2); } } void checkMoreLinks(ArticleCollection & ac) { auto ptr = ac.get("Dragon"); CHECK(ptr != nullptr); CHECK_EQUAL(3, ptr->getNumLinks()); ptr = ac.get("Cat"); CHECK(ptr != nullptr); CHECK_EQUAL(2, ptr->getNumLinks()); ptr = ac.get("Window"); CHECK(ptr != nullptr); CHECK_EQUAL(2, ptr->getNumLinks()); } TEST(ArticleCollection_TestMergeMoreLinks) { { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); a1.merge(a2, ArticleCollection::MergeStrategy::UseArticleWithMoreLinks); CHECK_EQUAL(15, a1.getNumArticles()); checkMoreLinks(a1); } { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); // reverse merge a2.merge(a1, ArticleCollection::MergeStrategy::UseArticleWithMoreLinks); CHECK_EQUAL(15, a2.getNumArticles()); checkMoreLinks(a2); } } TEST(ArticleCollection_TestMerge) { ArticleCollection ac1; ac1.add(std::make_shared<Article>("ManaMana")); ac1.add(std::make_shared<Article>("Dragon")); ac1.add(std::make_shared<Article>("Cereals")); { ArticleCollection ac2; ac2.add(std::make_shared<Article>("Dragon")); ac2.add(std::make_shared<Article>("Git")); ac2.add(std::make_shared<Article>("Stroustrup")); ac1.merge(ac2, ArticleCollection::MergeStrategy::IgnoreDuplicates); CHECK_EQUAL(5, ac1.getNumArticles()); CHECK_EQUAL(3, ac2.getNumArticles()); } // check again after scope is left CHECK_EQUAL(5, ac1.getNumArticles()); } } <commit_msg>Clarify merge tests with comments<commit_after>#include <memory> #include <UnitTest++/UnitTest++.h> #include "Article.h" #include "ArticleCollection.h" #include "WalkerException.h" SUITE(CollectionMergeTests) { using namespace WikiWalker; /*! * Create test data of the following structure: * dragon -> treasure * -> fire * -> flying * cat -> - * apple -> fruit * window -> outside */ void createArticlesAndFillFirst(ArticleCollection & ac) { auto a1 = std::make_shared<Article>("Dragon"); auto a2 = std::make_shared<Article>("Treasure"); auto a3 = std::make_shared<Article>("Fire"); auto a4 = std::make_shared<Article>("Flying"); a1->addLink(a2); a1->addLink(a3); a1->addLink(a4); auto a5 = std::make_shared<Article>("Cat"); auto a6 = std::make_shared<Article>("Apple"); auto a7 = std::make_shared<Article>("Fruit"); a6->addLink(a7); auto a8 = std::make_shared<Article>("Window"); auto a9 = std::make_shared<Article>("Outside"); a8->addLink(a9); ac.add(a1); ac.add(a2); ac.add(a3); ac.add(a4); ac.add(a5); ac.add(a6); ac.add(a7); ac.add(a8); ac.add(a9); } /*! * Create test data of the following structure: * * dragon -> - * cat -> milk * -> lazy * wood -> house * window -> glass * -> cleaning */ void createArticlesAndFillSecond(ArticleCollection & ac) { auto b1 = std::make_shared<Article>("Dragon"); auto b2 = std::make_shared<Article>("Cat"); auto b9 = std::make_shared<Article>("Milk"); auto b3 = std::make_shared<Article>("Lazy"); b2->addLink(b3); b2->addLink(b9); auto b4 = std::make_shared<Article>("Wood"); auto b5 = std::make_shared<Article>("House"); b4->addLink(b5); auto b6 = std::make_shared<Article>("Window"); auto b7 = std::make_shared<Article>("Glass"); auto b8 = std::make_shared<Article>("Cleaning"); b6->addLink(b7); b6->addLink(b8); ac.add(b1); ac.add(b2); ac.add(b3); ac.add(b4); ac.add(b5); ac.add(b6); ac.add(b7); ac.add(b8); ac.add(b9); } /*! check whether data from first set is preferred * * Overview of the combined structure- * * dragon -> treasure | dragon -> - * -> fire | * -> flying | * | * cat -> - | cat -> milk * | -> lazy * | * apple -> fruit | * | * | wood -> house * | * window -> outside | window -> glass * | -> cleaning * * * So we have 15 articles in total, and either side of the links may exist */ void checkConflicts_DataFromFirstSetPreferred(ArticleCollection & c1) { // 15 articles in total, no matter what CHECK_EQUAL(15, c1.getNumArticles()); // data from createArticlesAndFillFirst won auto ptr = c1.get("Dragon"); CHECK(ptr != nullptr); CHECK_EQUAL(3, ptr->getNumLinks()); ptr = c1.get("Cat"); CHECK(ptr != nullptr); CHECK_THROW(ptr->getNumLinks(), WalkerException); ptr = c1.get("Window"); CHECK(ptr != nullptr); CHECK_EQUAL(1, ptr->getNumLinks()); } /*! * see #checkFirst, only for the second set */ void checkConflicts_DataFromSecondSetPreferred(ArticleCollection & c2) { CHECK_EQUAL(15, c2.getNumArticles()); // data from createArticlesAndFillSecond won auto ptr = c2.get("Dragon"); CHECK(ptr != nullptr); CHECK_THROW(ptr->getNumLinks(), WalkerException); ptr = c2.get("Cat"); CHECK(ptr != nullptr); CHECK_EQUAL(2, ptr->getNumLinks()); ptr = c2.get("Window"); CHECK(ptr != nullptr); CHECK_EQUAL(2, ptr->getNumLinks()); } TEST(ArticleCollection_TestMergeIgnore) { { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); a1.merge(a2, ArticleCollection::MergeStrategy::IgnoreDuplicates); checkConflicts_DataFromFirstSetPreferred(a1); } { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); // reverse merge a2.merge(a1, ArticleCollection::MergeStrategy::IgnoreDuplicates); checkConflicts_DataFromSecondSetPreferred(a2); } } // overwrite behaves "exactly the opposite" of ignore TEST(ArticleCollection_TestMergeOverwrite) { { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); a1.merge(a2, ArticleCollection::MergeStrategy::AlwaysOverwrite); checkConflicts_DataFromSecondSetPreferred(a1); } { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); // reverse merge a2.merge(a1, ArticleCollection::MergeStrategy::AlwaysOverwrite); checkConflicts_DataFromFirstSetPreferred(a2); } } void checkMoreLinks(ArticleCollection & ac) { auto ptr = ac.get("Dragon"); CHECK(ptr != nullptr); CHECK_EQUAL(3, ptr->getNumLinks()); ptr = ac.get("Cat"); CHECK(ptr != nullptr); CHECK_EQUAL(2, ptr->getNumLinks()); ptr = ac.get("Window"); CHECK(ptr != nullptr); CHECK_EQUAL(2, ptr->getNumLinks()); } TEST(ArticleCollection_TestMergeMoreLinks) { { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); a1.merge(a2, ArticleCollection::MergeStrategy::UseArticleWithMoreLinks); CHECK_EQUAL(15, a1.getNumArticles()); checkMoreLinks(a1); } { ArticleCollection a1, a2; createArticlesAndFillFirst(a1); createArticlesAndFillSecond(a2); // reverse merge a2.merge(a1, ArticleCollection::MergeStrategy::UseArticleWithMoreLinks); CHECK_EQUAL(15, a2.getNumArticles()); checkMoreLinks(a2); } } TEST(ArticleCollection_TestMerge) { ArticleCollection ac1; ac1.add(std::make_shared<Article>("ManaMana")); ac1.add(std::make_shared<Article>("Dragon")); ac1.add(std::make_shared<Article>("Cereals")); { ArticleCollection ac2; ac2.add(std::make_shared<Article>("Dragon")); ac2.add(std::make_shared<Article>("Git")); ac2.add(std::make_shared<Article>("Stroustrup")); ac1.merge(ac2, ArticleCollection::MergeStrategy::IgnoreDuplicates); CHECK_EQUAL(5, ac1.getNumArticles()); CHECK_EQUAL(3, ac2.getNumArticles()); } // check again after scope is left CHECK_EQUAL(5, ac1.getNumArticles()); } } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <cmath> namespace yks { inline float srgb_from_linear(float x) { return x <= 0.0031308f ? 12.92f * x : 1.055f * std::pow(x, 1.0f/2.4f) - 0.055f; } inline uint8_t byte_from_linear(float x) { return uint8_t(srgb_from_linear(x) * 255.0f + 0.5f); } }<commit_msg>Added sRGB -> linear mapping function.<commit_after>#pragma once #include <cstdint> #include <cmath> namespace yks { inline float srgb_from_linear(float x) { return x <= 0.0031308f ? 12.92f * x : 1.055f * std::pow(x, 1.0f/2.4f) - 0.055f; } inline float linear_from_srgb(float x) { return x <= 0.04045 ? x / 12.92f : std::pow((x + 0.055f) / 1.055f, 2.4f); } inline uint8_t byte_from_linear(float x) { return uint8_t(srgb_from_linear(x) * 255.0f + 0.5f); } }<|endoftext|>
<commit_before>// @(#)root/graf:$Id$ // Author: Rene Brun 17/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TStyle.h" #include "TPaveLabel.h" #include "TLatex.h" #include "TVirtualPad.h" ClassImp(TPaveLabel) //______________________________________________________________________________ //* A PaveLabel is a Pave (see TPave) with a text centered in the Pave. //Begin_Html /* <img src="gif/pavelabel.gif"> */ //End_Html // //______________________________________________________________________________ TPaveLabel::TPaveLabel(): TPave(), TAttText() { // Pavelabel default constructor. } //______________________________________________________________________________ TPaveLabel::TPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label, Option_t *option) :TPave(x1,y1,x2,y2,3,option), TAttText(22,0,1,gStyle->GetTextFont(),0.99) { // Pavelabel normal constructor. // // a PaveLabel is a Pave with a label centered in the Pave // The Pave is by default defined bith bordersize=5 and option ="br". // The text size is automatically computed as a function of the pave size. // // IMPORTANT NOTE: // Because TPave objects (and objects deriving from TPave) have their // master coordinate system in NDC, one cannot use the TBox functions // SetX1,SetY1,SetX2,SetY2 to change the corner coordinates. One should use // instead SetX1NDC, SetY1NDC, SetX2NDC, SetY2NDC. fLabel = label; } //______________________________________________________________________________ TPaveLabel::~TPaveLabel() { // Pavelabel default destructor. } //______________________________________________________________________________ TPaveLabel::TPaveLabel(const TPaveLabel &pavelabel) : TPave(pavelabel), TAttText(pavelabel) { // Pavelabel copy constructor. ((TPaveLabel&)pavelabel).Copy(*this); } //______________________________________________________________________________ void TPaveLabel::Copy(TObject &obj) const { // Copy this pavelabel to pavelabel. TPave::Copy(obj); TAttText::Copy(((TPaveLabel&)obj)); ((TPaveLabel&)obj).fLabel = fLabel; } //______________________________________________________________________________ void TPaveLabel::Draw(Option_t *option) { // Draw this pavelabel with its current attributes. Option_t *opt; if (option && strlen(option)) opt = option; else opt = GetOption(); AppendPad(opt); } //______________________________________________________________________________ void TPaveLabel::DrawPaveLabel(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char *label, Option_t *option) { // Draw this pavelabel with new coordinates. TPaveLabel *newpavelabel = new TPaveLabel(x1,y1,x2,y2,label,option); newpavelabel->SetBit(kCanDelete); newpavelabel->AppendPad(); } //______________________________________________________________________________ void TPaveLabel::Paint(Option_t *option) { // Paint this pavelabel with its current attributes. // Convert from NDC to pad coordinates TPave::ConvertNDCtoPad(); PaintPaveLabel(fX1, fY1, fX2, fY2, GetLabel(), strlen(option)?option:GetOption()); } //______________________________________________________________________________ void TPaveLabel::PaintPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label ,Option_t *option) { // Draw this pavelabel with new coordinates. Int_t nch = strlen(label); // Draw the pave TPave::PaintPave(x1,y1,x2,y2,GetBorderSize(),option); Float_t nspecials = 0; for (Int_t i=0;i<nch;i++) { if (label[i] == '!') nspecials += 1; if (label[i] == '?') nspecials += 1.5; if (label[i] == '#') nspecials += 1; if (label[i] == '`') nspecials += 1; if (label[i] == '^') nspecials += 1.5; if (label[i] == '~') nspecials += 1; if (label[i] == '&') nspecials += 2; if (label[i] == '\\') nspecials += 3; // octal characters very likely } nch -= Int_t(nspecials + 0.5); if (nch <= 0) return; // Draw label Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2()); Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1()); Double_t labelsize, textsize = GetTextSize(); Int_t automat = 0; if (GetTextFont()%10 > 2) { // fixed size font specified in pixels labelsize = GetTextSize(); } else { if (TMath::Abs(textsize -0.99) < 0.001) automat = 1; if (textsize == 0) { textsize = 0.99; automat = 1;} Int_t ypixel = TMath::Abs(gPad->YtoPixel(y1) - gPad->YtoPixel(y2)); labelsize = textsize*ypixel/hh; if (wh < hh) labelsize *= hh/wh; } TLatex latex; latex.SetTextAngle(GetTextAngle()); latex.SetTextFont(GetTextFont()); latex.SetTextAlign(GetTextAlign()); latex.SetTextColor(GetTextColor()); latex.SetTextSize(labelsize); if (automat) { UInt_t w,h; latex.GetTextExtent(w,h,GetTitle()); labelsize = h/hh; Double_t wxlabel = TMath::Abs(gPad->XtoPixel(x2) - gPad->XtoPixel(x1)); if (w > 0.99*wxlabel) {labelsize *= 0.99*wxlabel/w; h = UInt_t(h*0.99*wxlabel/w);} if (h < 1) h = 1; labelsize = Double_t(h)/hh; if (wh < hh) labelsize *= hh/wh; latex.SetTextSize(labelsize); } Int_t halign = GetTextAlign()/10; Int_t valign = GetTextAlign()%10; Double_t x = 0.5*(x1+x2); if (halign == 1) x = x1 + 0.02*(x2-x1); if (halign == 3) x = x2 - 0.02*(x2-x1); Double_t y = 0.5*(y1+y2); if (valign == 1) y = y1 + 0.02*(y2-y1); if (valign == 3) y = y2 - 0.02*(y2-y1); latex.PaintLatex(x, y, GetTextAngle(),labelsize,GetLabel()); } //______________________________________________________________________________ void TPaveLabel::SavePrimitive(ostream &out, Option_t * /*= ""*/) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TPaveLabel::Class())) { out<<" "; } else { out<<" TPaveLabel *"; } TString s = fLabel.Data(); s.ReplaceAll("\"","\\\""); if (fOption.Contains("NDC")) { out<<"pl = new TPaveLabel("<<fX1NDC<<","<<fY1NDC<<","<<fX2NDC<<","<<fY2NDC <<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl; } else { out<<"pl = new TPaveLabel("<<gPad->PadtoX(fX1)<<","<<gPad->PadtoY(fY1)<<","<<gPad->PadtoX(fX2)<<","<<gPad->PadtoY(fY2) <<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl; } if (fBorderSize != 3) { out<<" pl->SetBorderSize("<<fBorderSize<<");"<<endl; } SaveFillAttributes(out,"pl",19,1001); SaveLineAttributes(out,"pl",1,1,1); SaveTextAttributes(out,"pl",22,0,1,62,0); out<<" pl->Draw();"<<endl; } <commit_msg>From Valeri Fine: With the original ROOT version the effect of the labelsize *= 0.99*wxlabel/w is overriden by labelsize = Double_t(h)/hh;<commit_after>// @(#)root/graf:$Id$ // Author: Rene Brun 17/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TStyle.h" #include "TPaveLabel.h" #include "TLatex.h" #include "TVirtualPad.h" ClassImp(TPaveLabel) //______________________________________________________________________________ //* A PaveLabel is a Pave (see TPave) with a text centered in the Pave. //Begin_Html /* <img src="gif/pavelabel.gif"> */ //End_Html // //______________________________________________________________________________ TPaveLabel::TPaveLabel(): TPave(), TAttText() { // Pavelabel default constructor. } //______________________________________________________________________________ TPaveLabel::TPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label, Option_t *option) :TPave(x1,y1,x2,y2,3,option), TAttText(22,0,1,gStyle->GetTextFont(),0.99) { // Pavelabel normal constructor. // // a PaveLabel is a Pave with a label centered in the Pave // The Pave is by default defined bith bordersize=5 and option ="br". // The text size is automatically computed as a function of the pave size. // // IMPORTANT NOTE: // Because TPave objects (and objects deriving from TPave) have their // master coordinate system in NDC, one cannot use the TBox functions // SetX1,SetY1,SetX2,SetY2 to change the corner coordinates. One should use // instead SetX1NDC, SetY1NDC, SetX2NDC, SetY2NDC. fLabel = label; } //______________________________________________________________________________ TPaveLabel::~TPaveLabel() { // Pavelabel default destructor. } //______________________________________________________________________________ TPaveLabel::TPaveLabel(const TPaveLabel &pavelabel) : TPave(pavelabel), TAttText(pavelabel) { // Pavelabel copy constructor. ((TPaveLabel&)pavelabel).Copy(*this); } //______________________________________________________________________________ void TPaveLabel::Copy(TObject &obj) const { // Copy this pavelabel to pavelabel. TPave::Copy(obj); TAttText::Copy(((TPaveLabel&)obj)); ((TPaveLabel&)obj).fLabel = fLabel; } //______________________________________________________________________________ void TPaveLabel::Draw(Option_t *option) { // Draw this pavelabel with its current attributes. Option_t *opt; if (option && strlen(option)) opt = option; else opt = GetOption(); AppendPad(opt); } //______________________________________________________________________________ void TPaveLabel::DrawPaveLabel(Double_t x1, Double_t y1, Double_t x2, Double_t y2, const char *label, Option_t *option) { // Draw this pavelabel with new coordinates. TPaveLabel *newpavelabel = new TPaveLabel(x1,y1,x2,y2,label,option); newpavelabel->SetBit(kCanDelete); newpavelabel->AppendPad(); } //______________________________________________________________________________ void TPaveLabel::Paint(Option_t *option) { // Paint this pavelabel with its current attributes. // Convert from NDC to pad coordinates TPave::ConvertNDCtoPad(); PaintPaveLabel(fX1, fY1, fX2, fY2, GetLabel(), strlen(option)?option:GetOption()); } //______________________________________________________________________________ void TPaveLabel::PaintPaveLabel(Double_t x1, Double_t y1,Double_t x2, Double_t y2, const char *label ,Option_t *option) { // Draw this pavelabel with new coordinates. Int_t nch = strlen(label); // Draw the pave TPave::PaintPave(x1,y1,x2,y2,GetBorderSize(),option); Float_t nspecials = 0; for (Int_t i=0;i<nch;i++) { if (label[i] == '!') nspecials += 1; if (label[i] == '?') nspecials += 1.5; if (label[i] == '#') nspecials += 1; if (label[i] == '`') nspecials += 1; if (label[i] == '^') nspecials += 1.5; if (label[i] == '~') nspecials += 1; if (label[i] == '&') nspecials += 2; if (label[i] == '\\') nspecials += 3; // octal characters very likely } nch -= Int_t(nspecials + 0.5); if (nch <= 0) return; // Draw label Double_t wh = (Double_t)gPad->XtoPixel(gPad->GetX2()); Double_t hh = (Double_t)gPad->YtoPixel(gPad->GetY1()); Double_t labelsize, textsize = GetTextSize(); Int_t automat = 0; if (GetTextFont()%10 > 2) { // fixed size font specified in pixels labelsize = GetTextSize(); } else { if (TMath::Abs(textsize -0.99) < 0.001) automat = 1; if (textsize == 0) { textsize = 0.99; automat = 1;} Int_t ypixel = TMath::Abs(gPad->YtoPixel(y1) - gPad->YtoPixel(y2)); labelsize = textsize*ypixel/hh; if (wh < hh) labelsize *= hh/wh; } TLatex latex; latex.SetTextAngle(GetTextAngle()); latex.SetTextFont(GetTextFont()); latex.SetTextAlign(GetTextAlign()); latex.SetTextColor(GetTextColor()); latex.SetTextSize(labelsize); if (automat) { UInt_t w,h; latex.GetTextExtent(w,h,GetTitle()); labelsize = h/hh; Double_t wxlabel = TMath::Abs(gPad->XtoPixel(x2) - gPad->XtoPixel(x1)); while (w > 0.99*wxlabel) { labelsize *= 0.99*wxlabel/w;latex.SetTextSize(labelsize); latex.GetTextExtent(w,h,GetTitle());} if (h < 1) h = 1; if (h==1) { labelsize = Double_t(h)/hh; if (wh < hh) labelsize *= hh/wh; latex.SetTextSize(labelsize); } } Int_t halign = GetTextAlign()/10; Int_t valign = GetTextAlign()%10; Double_t x = 0.5*(x1+x2); if (halign == 1) x = x1 + 0.02*(x2-x1); if (halign == 3) x = x2 - 0.02*(x2-x1); Double_t y = 0.5*(y1+y2); if (valign == 1) y = y1 + 0.02*(y2-y1); if (valign == 3) y = y2 - 0.02*(y2-y1); latex.PaintLatex(x, y, GetTextAngle(),labelsize,GetLabel()); } //______________________________________________________________________________ void TPaveLabel::SavePrimitive(ostream &out, Option_t * /*= ""*/) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; out<<" "<<endl; if (gROOT->ClassSaved(TPaveLabel::Class())) { out<<" "; } else { out<<" TPaveLabel *"; } TString s = fLabel.Data(); s.ReplaceAll("\"","\\\""); if (fOption.Contains("NDC")) { out<<"pl = new TPaveLabel("<<fX1NDC<<","<<fY1NDC<<","<<fX2NDC<<","<<fY2NDC <<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl; } else { out<<"pl = new TPaveLabel("<<gPad->PadtoX(fX1)<<","<<gPad->PadtoY(fY1)<<","<<gPad->PadtoX(fX2)<<","<<gPad->PadtoY(fY2) <<","<<quote<<s.Data()<<quote<<","<<quote<<fOption<<quote<<");"<<endl; } if (fBorderSize != 3) { out<<" pl->SetBorderSize("<<fBorderSize<<");"<<endl; } SaveFillAttributes(out,"pl",19,1001); SaveLineAttributes(out,"pl",1,1,1); SaveTextAttributes(out,"pl",22,0,1,62,0); out<<" pl->Draw();"<<endl; } <|endoftext|>
<commit_before>/******************************************************************************* Module: FGMatrix.cpp Author: Originally by Tony Peden [formatted here (and broken??) by JSB] Date started: 1998 Purpose: FGMatrix class Called by: Various FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- HISTORY -------------------------------------------------------------------------------- ??/??/?? TP Created 03/16/2000 JSB Added exception throwing ******************************************************************************** INCLUDES *******************************************************************************/ #include "FGMatrix.h" /******************************************************************************* ************************************ CODE ************************************** *******************************************************************************/ double** FGalloc(int rows, int cols) { double **A; A = new double *[rows+1]; if (!A) return NULL; for (int i=0; i <= rows; i++){ A[i] = new double [cols+1]; if (!A[i]) return NULL; } return A; } /******************************************************************************/ void dealloc(double **A, int rows) { for(int i=0;i<= rows;i++) delete[] A[i]; delete[] A; } /******************************************************************************/ FGMatrix::FGMatrix(const unsigned int r, const unsigned int c) : rows(r), cols(c) { data = FGalloc(rows,cols); InitMatrix(); rowCtr = colCtr = 1; } /******************************************************************************/ FGMatrix::FGMatrix(const FGMatrix& M) { data = NULL; rowCtr = colCtr = 1; *this = M; } /******************************************************************************/ FGMatrix::~FGMatrix(void) { dealloc(data,rows); rowCtr = colCtr = 1; rows = cols = 0; } /******************************************************************************/ ostream& operator<<(ostream& os, const FGMatrix& M) { for (unsigned int i=1; i<=M.Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { if (i == M.Rows() && j == M.Cols()) os << M.data[i][j]; else os << M.data[i][j] << ", "; } } return os; } /******************************************************************************/ FGMatrix& FGMatrix::operator<<(const float ff) { data[rowCtr][colCtr] = ff; if (++colCtr > Cols()) { colCtr = 1; if (++rowCtr > Rows()) rowCtr = 1; } return *this; } /******************************************************************************/ istream& operator>>(istream& is, FGMatrix& M) { for (unsigned int i=1; i<=M.Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { is >> M.data[i][j]; } } return is; } /******************************************************************************/ FGMatrix& FGMatrix::operator=(const FGMatrix& M) { if (&M != this) { if (data != NULL) dealloc(data,rows); width = M.width; prec = M.prec; delim = M.delim; origin = M.origin; rows = M.rows; cols = M.cols; data = FGalloc(rows,cols); for (unsigned int i=0; i<=rows; i++) { for (unsigned int j=0; j<=cols; j++) { data[i][j] = M.data[i][j]; } } } return *this; } /******************************************************************************/ unsigned int FGMatrix::Rows(void) const { return rows; } /******************************************************************************/ unsigned int FGMatrix::Cols(void) const { return cols; } /******************************************************************************/ void FGMatrix::SetOParams(char delim,int width,int prec,int origin) { FGMatrix::delim = delim; FGMatrix::width = width; FGMatrix::prec = prec; FGMatrix::origin = origin; } /******************************************************************************/ void FGMatrix::InitMatrix(double value) { if (data) { for (unsigned int i=0;i<=rows;i++) { for (unsigned int j=0;j<=cols;j++) { operator()(i,j) = value; } } } } /******************************************************************************/ void FGMatrix::InitMatrix(void) { this->InitMatrix(0); } // ***************************************************************************** // binary operators ************************************************************ // ***************************************************************************** FGMatrix FGMatrix::operator-(const FGMatrix& M) { if ((Rows() != M.Rows()) || (Cols() != M.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator -"; throw mE; } FGMatrix Diff(Rows(), Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { Diff(i,j) = data[i][j] - M(i,j); } } return Diff; } /******************************************************************************/ void FGMatrix::operator-=(const FGMatrix &M) { if ((Rows() != M.Rows()) || (Cols() != M.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator -="; throw mE; } for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { data[i][j] -= M(i,j); } } } /******************************************************************************/ FGMatrix FGMatrix::operator+(const FGMatrix& M) { if ((Rows() != M.Rows()) || (Cols() != M.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator +"; throw mE; } FGMatrix Sum(Rows(), Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { Sum(i,j) = data[i][j] + M(i,j); } } return Sum; } /******************************************************************************/ void FGMatrix::operator+=(const FGMatrix &M) { if ((Rows() != M.Rows()) || (Cols() != M.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator +="; throw mE; } for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { data[i][j]+=M(i,j); } } } /******************************************************************************/ FGMatrix operator*(double scalar, FGMatrix &M) { FGMatrix Product(M.Rows(), M.Cols()); for (unsigned int i=1; i<=M.Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { Product(i,j) = scalar*M(i,j); } } return Product; } /******************************************************************************/ void FGMatrix::operator*=(const double scalar) { for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { data[i][j] *= scalar; } } } /******************************************************************************/ FGMatrix FGMatrix::operator*(const FGMatrix& M) { if (Cols() != M.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator *"; throw mE; } FGMatrix Product(Rows(), M.Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { Product(i,j) = 0; for (unsigned int k=1; k<=Cols(); k++) { Product(i,j) += data[i][k] * M(k,j); } } } return Product; } /******************************************************************************/ void FGMatrix::operator*=(const FGMatrix& M) { if (Cols() != M.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator *="; throw mE; } double **prod; prod = FGalloc(Rows(), M.Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { prod[i][j] = 0; for (unsigned int k=1; k<=Cols(); k++) { prod[i][j] += data[i][k] * M(k,j); } } } dealloc(data, Rows()); data = prod; cols = M.cols; } /******************************************************************************/ FGMatrix FGMatrix::operator/(const double scalar) { FGMatrix Quot(Rows(), Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { Quot(i,j) = data[i][j]/scalar; } } return Quot; } /******************************************************************************/ void FGMatrix::operator/=(const double scalar) { for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { data[i][j]/=scalar; } } } /******************************************************************************/ void FGMatrix::T(void) { if (rows==cols) TransposeSquare(); else TransposeNonSquare(); } /******************************************************************************/ FGColumnVector FGMatrix::operator*(const FGColumnVector& Col) { FGColumnVector Product(Col.Rows()); if (Cols() != Col.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Column Vector operator *"; throw mE; } for (unsigned int i=1;i<=Rows();i++) { Product(i) = 0.00; for (unsigned int j=1;j<=Cols();j++) { Product(i) += Col(j)*data[i][j]; } } return Product; } /******************************************************************************/ void FGMatrix::TransposeSquare(void) { for (unsigned int i=1; i<=rows; i++) { for (unsigned int j=i+1; j<=cols; j++) { double tmp = data[i][j]; data[i][j] = data[j][i]; data[j][i] = tmp; } } } /******************************************************************************/ void FGMatrix::TransposeNonSquare(void) { double **tran; tran = FGalloc(rows,cols); for (unsigned int i=1; i<=rows; i++) { for (unsigned int j=1; j<=cols; j++) { tran[j][i] = data[i][j]; } } dealloc(data,rows); data = tran; unsigned int m = rows; rows = cols; cols = m; } /******************************************************************************/ FGColumnVector::FGColumnVector(void):FGMatrix(3,1) { } FGColumnVector::FGColumnVector(int m):FGMatrix(m,1) { } FGColumnVector::FGColumnVector(const FGColumnVector& b):FGMatrix(b) { } FGColumnVector::~FGColumnVector() { } /******************************************************************************/ double& FGColumnVector::operator()(int m) const { return FGMatrix::operator()(m,1); } /******************************************************************************/ FGColumnVector operator*(const FGMatrix& Mat, const FGColumnVector& Col) { FGColumnVector Product(Col.Rows()); if (Mat.Cols() != Col.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Column Vector operator *"; throw mE; } for (unsigned int i=1;i<=Mat.Rows();i++) { Product(i) = 0.00; for (unsigned int j=1;j<=Mat.Cols();j++) { Product(i) += Col(j)*Mat(i,j); } } return Product; } /******************************************************************************/ FGColumnVector FGColumnVector::operator+(const FGColumnVector& C) { if (Rows() != C.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Column Vector operator *"; throw mE; } FGColumnVector Sum(C.Rows()); for (unsigned int i=1; i<=C.Rows(); i++) { Sum(i) = C(i) + data[i][1]; } return Sum; } /******************************************************************************/ FGColumnVector FGColumnVector::operator*(const double scalar) { FGColumnVector Product(Rows()); for (unsigned int i=1; i<=Rows(); i++) Product(i) = scalar * data[i][1]; return Product; } /******************************************************************************/ FGColumnVector FGColumnVector::operator-(const FGColumnVector& V) { if ((Rows() != V.Rows()) || (Cols() != V.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Column Vector operator -"; throw mE; } FGColumnVector Diff(Rows()); for (unsigned int i=1; i<=Rows(); i++) { Diff(i) = data[i][1] - V(i); } return Diff; } /******************************************************************************/ FGColumnVector FGColumnVector::operator/(const double scalar) { FGColumnVector Quotient(Rows()); for (unsigned int i=1; i<=Rows(); i++) Quotient(i) = data[i][1] / scalar; return Quotient; } /******************************************************************************/ FGColumnVector operator*(const double scalar, const FGColumnVector& C) { FGColumnVector Product(C.Rows()); for (unsigned int i=1; i<=C.Rows(); i++) { Product(i) = scalar * C(i); } return Product; } /******************************************************************************/ float FGColumnVector::Magnitude(void) { double num=0.0; if ((data[1][1] == 0.00) && (data[2][1] == 0.00) && (data[3][1] == 0.00)) { return 0.00; } else { for (unsigned int i = 1; i<=Rows(); i++) num += data[i][1]*data[i][1]; return sqrt(num); } } /******************************************************************************/ FGColumnVector FGColumnVector::Normalize(void) { double Mag = Magnitude(); if(Mag != 0 { for (unsigned int i=1; i<=Rows(); i++) for (unsigned int j=1; j<=Cols(); j++) data[i][j] = data[i][j]/Mag; } return *this; } /******************************************************************************/ FGColumnVector FGColumnVector::operator*(const FGColumnVector& V) { if (Rows() != 3 || V.Rows() != 3) { MatrixException mE; mE.Message = "Invalid row count in vector cross product function"; throw mE; } FGColumnVector Product(3); Product(1) = data[2][1] * V(3) - data[3][1] * V(2); Product(2) = data[3][1] * V(1) - data[1][1] * V(3); Product(3) = data[1][1] * V(2) - data[2][1] * V(1); return Product; } /******************************************************************************/ FGColumnVector FGColumnVector::multElementWise(const FGColumnVector& V) { if (Rows() != 3 || V.Rows() != 3) { MatrixException mE; mE.Message = "Invalid row count in vector cross product function"; throw mE; } FGColumnVector Product(3); Product(1) = data[1][1] * V(1); Product(2) = data[2][1] * V(2); Product(3) = data[3][1] * V(3); return Product; } /******************************************************************************/ <commit_msg>Fixed a missing parenthesis in recent mod of FGMatrix<commit_after>/******************************************************************************* Module: FGMatrix.cpp Author: Originally by Tony Peden [formatted here (and broken??) by JSB] Date started: 1998 Purpose: FGMatrix class Called by: Various FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- HISTORY -------------------------------------------------------------------------------- ??/??/?? TP Created 03/16/2000 JSB Added exception throwing ******************************************************************************** INCLUDES *******************************************************************************/ #include "FGMatrix.h" /******************************************************************************* ************************************ CODE ************************************** *******************************************************************************/ double** FGalloc(int rows, int cols) { double **A; A = new double *[rows+1]; if (!A) return NULL; for (int i=0; i <= rows; i++){ A[i] = new double [cols+1]; if (!A[i]) return NULL; } return A; } /******************************************************************************/ void dealloc(double **A, int rows) { for(int i=0;i<= rows;i++) delete[] A[i]; delete[] A; } /******************************************************************************/ FGMatrix::FGMatrix(const unsigned int r, const unsigned int c) : rows(r), cols(c) { data = FGalloc(rows,cols); InitMatrix(); rowCtr = colCtr = 1; } /******************************************************************************/ FGMatrix::FGMatrix(const FGMatrix& M) { data = NULL; rowCtr = colCtr = 1; *this = M; } /******************************************************************************/ FGMatrix::~FGMatrix(void) { dealloc(data,rows); rowCtr = colCtr = 1; rows = cols = 0; } /******************************************************************************/ ostream& operator<<(ostream& os, const FGMatrix& M) { for (unsigned int i=1; i<=M.Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { if (i == M.Rows() && j == M.Cols()) os << M.data[i][j]; else os << M.data[i][j] << ", "; } } return os; } /******************************************************************************/ FGMatrix& FGMatrix::operator<<(const float ff) { data[rowCtr][colCtr] = ff; if (++colCtr > Cols()) { colCtr = 1; if (++rowCtr > Rows()) rowCtr = 1; } return *this; } /******************************************************************************/ istream& operator>>(istream& is, FGMatrix& M) { for (unsigned int i=1; i<=M.Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { is >> M.data[i][j]; } } return is; } /******************************************************************************/ FGMatrix& FGMatrix::operator=(const FGMatrix& M) { if (&M != this) { if (data != NULL) dealloc(data,rows); width = M.width; prec = M.prec; delim = M.delim; origin = M.origin; rows = M.rows; cols = M.cols; data = FGalloc(rows,cols); for (unsigned int i=0; i<=rows; i++) { for (unsigned int j=0; j<=cols; j++) { data[i][j] = M.data[i][j]; } } } return *this; } /******************************************************************************/ unsigned int FGMatrix::Rows(void) const { return rows; } /******************************************************************************/ unsigned int FGMatrix::Cols(void) const { return cols; } /******************************************************************************/ void FGMatrix::SetOParams(char delim,int width,int prec,int origin) { FGMatrix::delim = delim; FGMatrix::width = width; FGMatrix::prec = prec; FGMatrix::origin = origin; } /******************************************************************************/ void FGMatrix::InitMatrix(double value) { if (data) { for (unsigned int i=0;i<=rows;i++) { for (unsigned int j=0;j<=cols;j++) { operator()(i,j) = value; } } } } /******************************************************************************/ void FGMatrix::InitMatrix(void) { this->InitMatrix(0); } // ***************************************************************************** // binary operators ************************************************************ // ***************************************************************************** FGMatrix FGMatrix::operator-(const FGMatrix& M) { if ((Rows() != M.Rows()) || (Cols() != M.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator -"; throw mE; } FGMatrix Diff(Rows(), Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { Diff(i,j) = data[i][j] - M(i,j); } } return Diff; } /******************************************************************************/ void FGMatrix::operator-=(const FGMatrix &M) { if ((Rows() != M.Rows()) || (Cols() != M.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator -="; throw mE; } for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { data[i][j] -= M(i,j); } } } /******************************************************************************/ FGMatrix FGMatrix::operator+(const FGMatrix& M) { if ((Rows() != M.Rows()) || (Cols() != M.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator +"; throw mE; } FGMatrix Sum(Rows(), Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { Sum(i,j) = data[i][j] + M(i,j); } } return Sum; } /******************************************************************************/ void FGMatrix::operator+=(const FGMatrix &M) { if ((Rows() != M.Rows()) || (Cols() != M.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator +="; throw mE; } for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { data[i][j]+=M(i,j); } } } /******************************************************************************/ FGMatrix operator*(double scalar, FGMatrix &M) { FGMatrix Product(M.Rows(), M.Cols()); for (unsigned int i=1; i<=M.Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { Product(i,j) = scalar*M(i,j); } } return Product; } /******************************************************************************/ void FGMatrix::operator*=(const double scalar) { for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { data[i][j] *= scalar; } } } /******************************************************************************/ FGMatrix FGMatrix::operator*(const FGMatrix& M) { if (Cols() != M.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator *"; throw mE; } FGMatrix Product(Rows(), M.Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { Product(i,j) = 0; for (unsigned int k=1; k<=Cols(); k++) { Product(i,j) += data[i][k] * M(k,j); } } } return Product; } /******************************************************************************/ void FGMatrix::operator*=(const FGMatrix& M) { if (Cols() != M.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Matrix operator *="; throw mE; } double **prod; prod = FGalloc(Rows(), M.Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=M.Cols(); j++) { prod[i][j] = 0; for (unsigned int k=1; k<=Cols(); k++) { prod[i][j] += data[i][k] * M(k,j); } } } dealloc(data, Rows()); data = prod; cols = M.cols; } /******************************************************************************/ FGMatrix FGMatrix::operator/(const double scalar) { FGMatrix Quot(Rows(), Cols()); for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { Quot(i,j) = data[i][j]/scalar; } } return Quot; } /******************************************************************************/ void FGMatrix::operator/=(const double scalar) { for (unsigned int i=1; i<=Rows(); i++) { for (unsigned int j=1; j<=Cols(); j++) { data[i][j]/=scalar; } } } /******************************************************************************/ void FGMatrix::T(void) { if (rows==cols) TransposeSquare(); else TransposeNonSquare(); } /******************************************************************************/ FGColumnVector FGMatrix::operator*(const FGColumnVector& Col) { FGColumnVector Product(Col.Rows()); if (Cols() != Col.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Column Vector operator *"; throw mE; } for (unsigned int i=1;i<=Rows();i++) { Product(i) = 0.00; for (unsigned int j=1;j<=Cols();j++) { Product(i) += Col(j)*data[i][j]; } } return Product; } /******************************************************************************/ void FGMatrix::TransposeSquare(void) { for (unsigned int i=1; i<=rows; i++) { for (unsigned int j=i+1; j<=cols; j++) { double tmp = data[i][j]; data[i][j] = data[j][i]; data[j][i] = tmp; } } } /******************************************************************************/ void FGMatrix::TransposeNonSquare(void) { double **tran; tran = FGalloc(rows,cols); for (unsigned int i=1; i<=rows; i++) { for (unsigned int j=1; j<=cols; j++) { tran[j][i] = data[i][j]; } } dealloc(data,rows); data = tran; unsigned int m = rows; rows = cols; cols = m; } /******************************************************************************/ FGColumnVector::FGColumnVector(void):FGMatrix(3,1) { } FGColumnVector::FGColumnVector(int m):FGMatrix(m,1) { } FGColumnVector::FGColumnVector(const FGColumnVector& b):FGMatrix(b) { } FGColumnVector::~FGColumnVector() { } /******************************************************************************/ double& FGColumnVector::operator()(int m) const { return FGMatrix::operator()(m,1); } /******************************************************************************/ FGColumnVector operator*(const FGMatrix& Mat, const FGColumnVector& Col) { FGColumnVector Product(Col.Rows()); if (Mat.Cols() != Col.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Column Vector operator *"; throw mE; } for (unsigned int i=1;i<=Mat.Rows();i++) { Product(i) = 0.00; for (unsigned int j=1;j<=Mat.Cols();j++) { Product(i) += Col(j)*Mat(i,j); } } return Product; } /******************************************************************************/ FGColumnVector FGColumnVector::operator+(const FGColumnVector& C) { if (Rows() != C.Rows()) { MatrixException mE; mE.Message = "Invalid row/column match in Column Vector operator *"; throw mE; } FGColumnVector Sum(C.Rows()); for (unsigned int i=1; i<=C.Rows(); i++) { Sum(i) = C(i) + data[i][1]; } return Sum; } /******************************************************************************/ FGColumnVector FGColumnVector::operator*(const double scalar) { FGColumnVector Product(Rows()); for (unsigned int i=1; i<=Rows(); i++) Product(i) = scalar * data[i][1]; return Product; } /******************************************************************************/ FGColumnVector FGColumnVector::operator-(const FGColumnVector& V) { if ((Rows() != V.Rows()) || (Cols() != V.Cols())) { MatrixException mE; mE.Message = "Invalid row/column match in Column Vector operator -"; throw mE; } FGColumnVector Diff(Rows()); for (unsigned int i=1; i<=Rows(); i++) { Diff(i) = data[i][1] - V(i); } return Diff; } /******************************************************************************/ FGColumnVector FGColumnVector::operator/(const double scalar) { FGColumnVector Quotient(Rows()); for (unsigned int i=1; i<=Rows(); i++) Quotient(i) = data[i][1] / scalar; return Quotient; } /******************************************************************************/ FGColumnVector operator*(const double scalar, const FGColumnVector& C) { FGColumnVector Product(C.Rows()); for (unsigned int i=1; i<=C.Rows(); i++) { Product(i) = scalar * C(i); } return Product; } /******************************************************************************/ float FGColumnVector::Magnitude(void) { double num=0.0; if ((data[1][1] == 0.00) && (data[2][1] == 0.00) && (data[3][1] == 0.00)) { return 0.00; } else { for (unsigned int i = 1; i<=Rows(); i++) num += data[i][1]*data[i][1]; return sqrt(num); } } /******************************************************************************/ FGColumnVector FGColumnVector::Normalize(void) { double Mag = Magnitude(); if (Mag != 0) { for (unsigned int i=1; i<=Rows(); i++) for (unsigned int j=1; j<=Cols(); j++) data[i][j] = data[i][j]/Mag; } return *this; } /******************************************************************************/ FGColumnVector FGColumnVector::operator*(const FGColumnVector& V) { if (Rows() != 3 || V.Rows() != 3) { MatrixException mE; mE.Message = "Invalid row count in vector cross product function"; throw mE; } FGColumnVector Product(3); Product(1) = data[2][1] * V(3) - data[3][1] * V(2); Product(2) = data[3][1] * V(1) - data[1][1] * V(3); Product(3) = data[1][1] * V(2) - data[2][1] * V(1); return Product; } /******************************************************************************/ FGColumnVector FGColumnVector::multElementWise(const FGColumnVector& V) { if (Rows() != 3 || V.Rows() != 3) { MatrixException mE; mE.Message = "Invalid row count in vector cross product function"; throw mE; } FGColumnVector Product(3); Product(1) = data[1][1] * V(1); Product(2) = data[2][1] * V(2); Product(3) = data[3][1] * V(3); return Product; } /******************************************************************************/ <|endoftext|>
<commit_before>//===-- asan_malloc_win.cc ------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // Windows-specific malloc interception. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_WINDOWS #include "asan_allocator.h" #include "asan_interceptors.h" #include "asan_internal.h" #include "asan_stack.h" #include "sanitizer_common/sanitizer_interception.h" #include <stddef.h> // ---------------------- Replacement functions ---------------- {{{1 using namespace __asan; // NOLINT // FIXME: Simply defining functions with the same signature in *.obj // files overrides the standard functions in *.lib // This works well for simple helloworld-like tests but might need to be // revisited in the future. extern "C" { SANITIZER_INTERFACE_ATTRIBUTE void free(void *ptr) { GET_STACK_TRACE_FREE; return asan_free(ptr, &stack, FROM_MALLOC); } SANITIZER_INTERFACE_ATTRIBUTE void _free_dbg(void* ptr, int) { free(ptr); } void cfree(void *ptr) { CHECK(!"cfree() should not be used on Windows?"); } SANITIZER_INTERFACE_ATTRIBUTE void *malloc(size_t size) { GET_STACK_TRACE_MALLOC; return asan_malloc(size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void* _malloc_dbg(size_t size, int , const char*, int) { return malloc(size); } SANITIZER_INTERFACE_ATTRIBUTE void *calloc(size_t nmemb, size_t size) { GET_STACK_TRACE_MALLOC; return asan_calloc(nmemb, size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void* _calloc_dbg(size_t n, size_t size, int, const char*, int) { return calloc(n, size); } SANITIZER_INTERFACE_ATTRIBUTE void *_calloc_impl(size_t nmemb, size_t size, int *errno_tmp) { return calloc(nmemb, size); } SANITIZER_INTERFACE_ATTRIBUTE void *realloc(void *ptr, size_t size) { GET_STACK_TRACE_MALLOC; return asan_realloc(ptr, size, &stack); } SANITIZER_INTERFACE_ATTRIBUTE void *_realloc_dbg(void *ptr, size_t size, int) { CHECK(!"_realloc_dbg should not exist!"); return 0; } SANITIZER_INTERFACE_ATTRIBUTE void* _recalloc(void* p, size_t n, size_t elem_size) { if (!p) return calloc(n, elem_size); const size_t size = n * elem_size; if (elem_size != 0 && size / elem_size != n) return 0; return realloc(p, size); } SANITIZER_INTERFACE_ATTRIBUTE size_t _msize(void *ptr) { GET_CURRENT_PC_BP_SP; (void)sp; return asan_malloc_usable_size(ptr, pc, bp); } SANITIZER_INTERFACE_ATTRIBUTE void *_expand(void *memblock, size_t size) { // _expand is used in realloc-like functions to resize the buffer if possible. // We don't want memory to stand still while resizing buffers, so return 0. return 0; } SANITIZER_INTERFACE_ATTRIBUTE void *_expand_dbg(void *memblock, size_t size) { return 0; } // TODO(timurrrr): Might want to add support for _aligned_* allocation // functions to detect a bit more bugs. Those functions seem to wrap malloc(). int _CrtDbgReport(int, const char*, int, const char*, const char*, ...) { ShowStatsAndAbort(); } int _CrtDbgReportW(int reportType, const wchar_t*, int, const wchar_t*, const wchar_t*, ...) { ShowStatsAndAbort(); } int _CrtSetReportMode(int, int) { return 0; } } // extern "C" namespace __asan { void ReplaceSystemMalloc() { #if defined(_DLL) # error MD CRT is not yet supported, see PR20214. #endif } } // namespace __asan #endif // _WIN32 <commit_msg>[ASan/Win] Introduce a new macro for malloc-like function attributes; also, clang-format the definitions of these functions<commit_after>//===-- asan_malloc_win.cc ------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of AddressSanitizer, an address sanity checker. // // Windows-specific malloc interception. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_WINDOWS #include "asan_allocator.h" #include "asan_interceptors.h" #include "asan_internal.h" #include "asan_stack.h" #include "sanitizer_common/sanitizer_interception.h" #include <stddef.h> // ---------------------- Replacement functions ---------------- {{{1 using namespace __asan; // NOLINT // FIXME: Simply defining functions with the same signature in *.obj // files overrides the standard functions in *.lib // This works well for simple helloworld-like tests but might need to be // revisited in the future. // The function attributes will be different for -MD CRT. // Just introduce an extra macro for now, it will get a different value under // ASAN_DYNAMIC soon. #define ALLOCATION_FUNCTION_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE extern "C" { ALLOCATION_FUNCTION_ATTRIBUTE void free(void *ptr) { GET_STACK_TRACE_FREE; return asan_free(ptr, &stack, FROM_MALLOC); } ALLOCATION_FUNCTION_ATTRIBUTE void _free_dbg(void *ptr, int) { free(ptr); } ALLOCATION_FUNCTION_ATTRIBUTE void cfree(void *) { CHECK(!"cfree() should not be used on Windows"); } ALLOCATION_FUNCTION_ATTRIBUTE void *malloc(size_t size) { GET_STACK_TRACE_MALLOC; return asan_malloc(size, &stack); } ALLOCATION_FUNCTION_ATTRIBUTE void *_malloc_dbg(size_t size, int, const char *, int) { return malloc(size); } ALLOCATION_FUNCTION_ATTRIBUTE void *calloc(size_t nmemb, size_t size) { GET_STACK_TRACE_MALLOC; return asan_calloc(nmemb, size, &stack); } ALLOCATION_FUNCTION_ATTRIBUTE void *_calloc_dbg(size_t nmemb, size_t size, int, const char *, int) { return calloc(nmemb, size); } ALLOCATION_FUNCTION_ATTRIBUTE void *_calloc_impl(size_t nmemb, size_t size, int *errno_tmp) { return calloc(nmemb, size); } ALLOCATION_FUNCTION_ATTRIBUTE void *realloc(void *ptr, size_t size) { GET_STACK_TRACE_MALLOC; return asan_realloc(ptr, size, &stack); } ALLOCATION_FUNCTION_ATTRIBUTE void *_realloc_dbg(void *ptr, size_t size, int) { CHECK(!"_realloc_dbg should not exist!"); return 0; } ALLOCATION_FUNCTION_ATTRIBUTE void *_recalloc(void *p, size_t n, size_t elem_size) { if (!p) return calloc(n, elem_size); const size_t size = n * elem_size; if (elem_size != 0 && size / elem_size != n) return 0; return realloc(p, size); } ALLOCATION_FUNCTION_ATTRIBUTE size_t _msize(void *ptr) { GET_CURRENT_PC_BP_SP; (void)sp; return asan_malloc_usable_size(ptr, pc, bp); } ALLOCATION_FUNCTION_ATTRIBUTE void *_expand(void *memblock, size_t size) { // _expand is used in realloc-like functions to resize the buffer if possible. // We don't want memory to stand still while resizing buffers, so return 0. return 0; } ALLOCATION_FUNCTION_ATTRIBUTE void *_expand_dbg(void *memblock, size_t size) { return _expand(memblock, size); } // TODO(timurrrr): Might want to add support for _aligned_* allocation // functions to detect a bit more bugs. Those functions seem to wrap malloc(). int _CrtDbgReport(int, const char*, int, const char*, const char*, ...) { ShowStatsAndAbort(); } int _CrtDbgReportW(int reportType, const wchar_t*, int, const wchar_t*, const wchar_t*, ...) { ShowStatsAndAbort(); } int _CrtSetReportMode(int, int) { return 0; } } // extern "C" namespace __asan { void ReplaceSystemMalloc() { #if defined(_DLL) # error MD CRT is not yet supported, see PR20214. #endif } } // namespace __asan #endif // _WIN32 <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperChoiceParameter.h" #include "otbWrapperListViewParameter.h" #include "otbWrapperBoolParameter.h" #include "otbWrapperApplicationRegistry.h" #include "otbWrapperTypes.h" #include "otbWrapperApplication.h" #include <vector> #include <string> #include <iostream> #include <cassert> #include <fstream> int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "Usage : " << argv[0] << " name OTB_APPLICATION_PATH [out_dir]" << std::endl; return EXIT_FAILURE; } using namespace otb::Wrapper; const std::string module(argv[1]); /* TestApplication is removed in CMakeLists.txt */ #if 0 if (module == "TestApplication") return EXIT_SUCCESS; #endif ApplicationRegistry::AddApplicationPath(argv[2]); Application::Pointer appli = ApplicationRegistry::CreateApplicationFaster(module.c_str()); assert(!appli.IsNull()); std::map<ParameterType, std::string> parameterTypeToString; parameterTypeToString[ParameterType_Empty] = "QgsProcessingParameterBoolean"; parameterTypeToString[ParameterType_Bool] = "QgsProcessingParameterBoolean"; parameterTypeToString[ParameterType_Int] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Float] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_RAM] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Radius] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Choice] = "OTBParameterChoice"; parameterTypeToString[ParameterType_String] = "QgsProcessingParameterString"; parameterTypeToString[ParameterType_InputImage] = "QgsProcessingParameterRasterLayer"; parameterTypeToString[ParameterType_InputFilename] = "QgsProcessingParameterFile"; parameterTypeToString[ParameterType_InputImageList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_InputVectorData] = "QgsProcessingParameterVectorLayer"; parameterTypeToString[ParameterType_InputFilenameList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_InputVectorDataList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_OutputImage] = "QgsProcessingParameterRasterDestination"; parameterTypeToString[ParameterType_OutputVectorData] = "QgsProcessingParameterVectorDestination"; parameterTypeToString[ParameterType_OutputFilename] = "QgsProcessingParameterFileDestination"; parameterTypeToString[ParameterType_Directory] = "QgsProcessingParameterFile"; // TODO parameterTypeToString[ParameterType_StringList] = "QgsProcessingParameterString"; // ListView parameters are treated as plain string (QLineEdit) in qgis processing ui. // This seems rather unpleasant when comparing Qgis processing with Monteverdi/Mapla in OTB // We tried to push something simple with checkboxes but its too risky for this version // and clock is ticking... parameterTypeToString[ParameterType_ListView] = "QgsProcessingParameterString"; // For next update of plugin code ListView should use a custom widget wrapper and behave // exactly like OTB Mapla. And this #if 0 block is our TODO remainder. #if 0 parameterTypeToString[ParameterType_ListView] = "OTBParameterListView"; #endif const std::vector<std::string> appKeyList = appli->GetParametersKeys(true); const unsigned int nbOfParam = appKeyList.size(); std::string output_file = module + ".txt"; std::string algs_txt = "algs.txt"; if (argc > 3) { output_file = std::string(argv[3]) + module + ".txt"; algs_txt = std::string(argv[3]) + "algs.txt"; } std::ofstream dFile; dFile.open (output_file, std::ios::out); std::cerr << "Writing " << output_file << std::endl; std::string output_parameter_name; bool hasRasterOutput = false; { for (unsigned int i = 0; i < nbOfParam; i++) { Parameter::Pointer param = appli->GetParameterByKey(appKeyList[i]); if (param->GetMandatory()) { ParameterType type = appli->GetParameterType(appKeyList[i]); if (type == ParameterType_OutputImage ) { output_parameter_name = appKeyList[i]; hasRasterOutput = true; } } } } if(output_parameter_name.empty()) dFile << module << std::endl; else dFile << module << "|" << output_parameter_name << std::endl; dFile << appli->GetDescription() << std::endl; const std::string group = appli->GetDocTags().size() > 0 ? appli->GetDocTags()[0] : "UNCLASSIFIED"; dFile << group << std::endl; for (unsigned int i = 0; i < nbOfParam; i++) { const std::string name = appKeyList[i]; Parameter::Pointer param = appli->GetParameterByKey(name); ParameterType type = appli->GetParameterType(name); const std::string description = param->GetName(); std::string qgis_type = parameterTypeToString[type]; #if 0 if (type == ParameterType_ListView) { ListViewParameter *lv_param = dynamic_cast<ListViewParameter*>(param.GetPointer()); std::cerr << "lv_param->GetSingleSelection()" << lv_param->GetSingleSelection() << std::endl; if (lv_param->GetSingleSelection()) { qgis_type = "QgsProcessingParameterEnum"; std::vector<std::string> key_list = appli->GetChoiceKeys(name); std::string values = ""; for( auto k : key_list) values += k + ";"; values.pop_back(); dFile << "|" << values ; } } #endif if ( type == ParameterType_Group || type == ParameterType_OutputProcessXML || type == ParameterType_InputProcessXML || type == ParameterType_RAM || param->GetRole() == Role_Output ) { // group parameter cannot have any value. // outxml and inxml parameters are not relevant for QGIS and is considered a bit noisy // ram is added by qgis-otb processing provider plugin as an advanced parameter for all apps // parameter role cannot be of type Role_Output continue; } assert(!qgis_type.empty()); if(qgis_type.empty()) { std::cerr << "No mapping found for parameter '" <<name <<"' type=" << type << std::endl; return EXIT_FAILURE; } bool isDestination = false; bool isEpsgCode = false; // use QgsProcessingParameterCrs if required. // TODO: do a regex on name to match ==epsg || *\.epsg.\* if ( name == "epsg" || name == "map.epsg.code" || name == "mapproj.epsg.code" || name == "mode.epsg.code") { qgis_type = "QgsProcessingParameterCrs"; isEpsgCode = true; } dFile << qgis_type << "|" << name << "|" << description; std::string default_value = "None"; if (type == ParameterType_Int) { if (isEpsgCode) { if (param->HasValue() && appli->GetParameterInt(name) < 1) default_value = "EPSG: " + appli->GetParameterAsString(name); else default_value = "ProjectCrs"; } else { dFile << "|QgsProcessingParameterNumber.Integer"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } } else if (type == ParameterType_Float) { dFile << "|QgsProcessingParameterNumber.Double"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if (type == ParameterType_Radius) { dFile << "|QgsProcessingParameterNumber.Integer"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if(type == ParameterType_InputFilename) { // TODO: if parameter InputFilename can give supported extensions // we can use it gitlab #1559 dFile << "|QgsProcessingParameterFile.File|txt"; } else if(type == ParameterType_Directory) { dFile << "|QgsProcessingParameterFile.Folder|False"; } else if (type == ParameterType_InputImageList) { dFile << "|3"; //QgsProcessing.TypeRaster } else if (type == ParameterType_InputVectorDataList) { dFile << "|-1"; //QgsProcessing.TypeVectorAnyGeometry } else if (type == ParameterType_InputVectorData) { dFile << "|-1"; //QgsProcessing.TypeVectorAnyGeometry } else if(type == ParameterType_InputFilenameList) { dFile << "|4"; //QgsProcessing.TypeFile" } else if(type ==ParameterType_String) { // Below line is interpreted in qgis processing as // 1. default_value = None // 2. multiLine = False // For more details, // please refer to documetation of QgsProcessingParameterString. default_value = "None|False"; } else if(type ==ParameterType_StringList) { // Below line is interpreted in qgis processing as // 1. default_value = None // 2. multiLine = True // For more details, // please refer to documetation of QgsProcessingParameterString. // setting default_value this way is an exception for ParameterType_StringList and ParameterType_String default_value = "None|True"; } else if (type == ParameterType_InputImage) { // default is None and nothing to add to dFile } else if(type ==ParameterType_ListView) { // default is None and nothing to add to dFile } else if(type == ParameterType_Bool) { default_value = appli->GetParameterAsString(name); } else if(type == ParameterType_Choice) { std::vector<std::string> key_list = appli->GetChoiceKeys(name); std::string values = ""; for( auto k : key_list) values += k + ";"; values.pop_back(); dFile << "|" << values ; ChoiceParameter *cparam = dynamic_cast<ChoiceParameter*>(param.GetPointer()); default_value = std::to_string(cparam->GetValue()); } else if(type == ParameterType_OutputVectorData || type == ParameterType_OutputImage || type == ParameterType_OutputFilename) { // No need for default_value, optional and extra fields in dFile. // If parameter is a destination type. qgis_type|name|description is enough. // So we simply set isDestination to true and skip to end to append a new line. isDestination = true; } else { std::cout << "ERROR: default_value is empty for '" << name << "' type='" << qgis_type << "'" << std::endl; return EXIT_FAILURE; } if (!isDestination) { std::string optional; if (param->GetMandatory()) { // TODO: avoid workaround for stringlist types (fix appengine) // type == ParameterType_StringList check is needed because: // If parameter is mandatory it can have no value // It is accepted in OTB that, string list could be generated dynamically // qgis has no such option to handle dynamic values yet.. // So mandatory parameters whose type is StringList is considered optional optional = param->HasValue() || type == ParameterType_StringList ? "True" : "False"; } else { optional = "True"; } #if 0 std::cerr << name; std::cerr << " mandatory=" << param->GetMandatory(); std::cerr << " HasValue=" << param->HasValue(); std::cerr << " qgis_type=" << qgis_type; std::cerr << " optional=" << optional << std::endl; #endif dFile << "|" << default_value << "|" << optional; } dFile << std::endl; } if(hasRasterOutput) { dFile << "*QgsProcessingParameterEnum|outputpixeltype|Output pixel type|unit8;int;float;double|False|2|True" << std::endl; } dFile.close(); std::ofstream indexFile; indexFile.open (algs_txt, std::ios::out | std::ios::app ); indexFile << group << "|" << module << std::endl; indexFile.close(); std::cerr << "Updated " << algs_txt << std::endl; return EXIT_SUCCESS; } <commit_msg>REFAC: change the way qgis_type is looked for in the std::map<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperChoiceParameter.h" #include "otbWrapperListViewParameter.h" #include "otbWrapperBoolParameter.h" #include "otbWrapperApplicationRegistry.h" #include "otbWrapperTypes.h" #include "otbWrapperApplication.h" #include <vector> #include <string> #include <iostream> #include <cassert> #include <fstream> int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "Usage : " << argv[0] << " name OTB_APPLICATION_PATH [out_dir]" << std::endl; return EXIT_FAILURE; } using namespace otb::Wrapper; const std::string module(argv[1]); /* TestApplication is removed in CMakeLists.txt */ #if 0 if (module == "TestApplication") return EXIT_SUCCESS; #endif ApplicationRegistry::AddApplicationPath(argv[2]); Application::Pointer appli = ApplicationRegistry::CreateApplicationFaster(module.c_str()); assert(!appli.IsNull()); std::map<ParameterType, std::string> parameterTypeToString; parameterTypeToString[ParameterType_Empty] = "QgsProcessingParameterBoolean"; parameterTypeToString[ParameterType_Bool] = "QgsProcessingParameterBoolean"; parameterTypeToString[ParameterType_Int] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Float] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_RAM] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Radius] = "QgsProcessingParameterNumber"; parameterTypeToString[ParameterType_Choice] = "OTBParameterChoice"; parameterTypeToString[ParameterType_String] = "QgsProcessingParameterString"; parameterTypeToString[ParameterType_InputImage] = "QgsProcessingParameterRasterLayer"; parameterTypeToString[ParameterType_InputFilename] = "QgsProcessingParameterFile"; parameterTypeToString[ParameterType_InputImageList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_InputVectorData] = "QgsProcessingParameterVectorLayer"; parameterTypeToString[ParameterType_InputFilenameList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_InputVectorDataList] = "QgsProcessingParameterMultipleLayers"; parameterTypeToString[ParameterType_OutputImage] = "QgsProcessingParameterRasterDestination"; parameterTypeToString[ParameterType_OutputVectorData] = "QgsProcessingParameterVectorDestination"; parameterTypeToString[ParameterType_OutputFilename] = "QgsProcessingParameterFileDestination"; parameterTypeToString[ParameterType_Directory] = "QgsProcessingParameterFile"; // TODO parameterTypeToString[ParameterType_StringList] = "QgsProcessingParameterString"; // ListView parameters are treated as plain string (QLineEdit) in qgis processing ui. // This seems rather unpleasant when comparing Qgis processing with Monteverdi/Mapla in OTB // We tried to push something simple with checkboxes but its too risky for this version // and clock is ticking... parameterTypeToString[ParameterType_ListView] = "QgsProcessingParameterString"; // For next update of plugin code ListView should use a custom widget wrapper and behave // exactly like OTB Mapla. And this #if 0 block is our TODO remainder. #if 0 parameterTypeToString[ParameterType_ListView] = "OTBParameterListView"; #endif const std::vector<std::string> appKeyList = appli->GetParametersKeys(true); const unsigned int nbOfParam = appKeyList.size(); std::string output_file = module + ".txt"; std::string algs_txt = "algs.txt"; if (argc > 3) { output_file = std::string(argv[3]) + module + ".txt"; algs_txt = std::string(argv[3]) + "algs.txt"; } std::ofstream dFile; dFile.open (output_file, std::ios::out); std::cerr << "Writing " << output_file << std::endl; std::string output_parameter_name; bool hasRasterOutput = false; { for (unsigned int i = 0; i < nbOfParam; i++) { Parameter::Pointer param = appli->GetParameterByKey(appKeyList[i]); if (param->GetMandatory()) { ParameterType type = appli->GetParameterType(appKeyList[i]); if (type == ParameterType_OutputImage ) { output_parameter_name = appKeyList[i]; hasRasterOutput = true; } } } } if(output_parameter_name.empty()) dFile << module << std::endl; else dFile << module << "|" << output_parameter_name << std::endl; dFile << appli->GetDescription() << std::endl; const std::string group = appli->GetDocTags().size() > 0 ? appli->GetDocTags()[0] : "UNCLASSIFIED"; dFile << group << std::endl; for (unsigned int i = 0; i < nbOfParam; i++) { const std::string name = appKeyList[i]; Parameter::Pointer param = appli->GetParameterByKey(name); ParameterType type = appli->GetParameterType(name); const std::string description = param->GetName(); if ( type == ParameterType_Group || type == ParameterType_OutputProcessXML || type == ParameterType_InputProcessXML || type == ParameterType_RAM || param->GetRole() == Role_Output ) { // group parameter cannot have any value. // outxml and inxml parameters are not relevant for QGIS and is considered a bit noisy // ram is added by qgis-otb processing provider plugin as an advanced parameter for all apps // parameter role cannot be of type Role_Output continue; } auto it = parameterTypeToString.find(type); assert( it != parameterTypeToString.end() ); if( it == parameterTypeToString.end() ) { std::cerr << "No mapping found for parameter '" <<name <<"' type=" << type << std::endl; return EXIT_FAILURE; } std::string qgis_type = it->second; #if 0 if (type == ParameterType_ListView) { ListViewParameter *lv_param = dynamic_cast<ListViewParameter*>(param.GetPointer()); std::cerr << "lv_param->GetSingleSelection()" << lv_param->GetSingleSelection() << std::endl; if (lv_param->GetSingleSelection()) { qgis_type = "QgsProcessingParameterEnum"; std::vector<std::string> key_list = appli->GetChoiceKeys(name); std::string values = ""; for( auto k : key_list) values += k + ";"; values.pop_back(); dFile << "|" << values ; } } #endif bool isDestination = false; bool isEpsgCode = false; // use QgsProcessingParameterCrs if required. // TODO: do a regex on name to match ==epsg || *\.epsg.\* if ( name == "epsg" || name == "map.epsg.code" || name == "mapproj.epsg.code" || name == "mode.epsg.code") { qgis_type = "QgsProcessingParameterCrs"; isEpsgCode = true; } dFile << qgis_type << "|" << name << "|" << description; std::string default_value = "None"; if (type == ParameterType_Int) { if (isEpsgCode) { if (param->HasValue() && appli->GetParameterInt(name) < 1) default_value = "EPSG: " + appli->GetParameterAsString(name); else default_value = "ProjectCrs"; } else { dFile << "|QgsProcessingParameterNumber.Integer"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } } else if (type == ParameterType_Float) { dFile << "|QgsProcessingParameterNumber.Double"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if (type == ParameterType_Radius) { dFile << "|QgsProcessingParameterNumber.Integer"; default_value = param->HasValue() ? appli->GetParameterAsString(name): "0"; } else if(type == ParameterType_InputFilename) { // TODO: if parameter InputFilename can give supported extensions // we can use it gitlab #1559 dFile << "|QgsProcessingParameterFile.File|txt"; } else if(type == ParameterType_Directory) { dFile << "|QgsProcessingParameterFile.Folder|False"; } else if (type == ParameterType_InputImageList) { dFile << "|3"; //QgsProcessing.TypeRaster } else if (type == ParameterType_InputVectorDataList) { dFile << "|-1"; //QgsProcessing.TypeVectorAnyGeometry } else if (type == ParameterType_InputVectorData) { dFile << "|-1"; //QgsProcessing.TypeVectorAnyGeometry } else if(type == ParameterType_InputFilenameList) { dFile << "|4"; //QgsProcessing.TypeFile" } else if(type ==ParameterType_String) { // Below line is interpreted in qgis processing as // 1. default_value = None // 2. multiLine = False // For more details, // please refer to documetation of QgsProcessingParameterString. default_value = "None|False"; } else if(type ==ParameterType_StringList) { // Below line is interpreted in qgis processing as // 1. default_value = None // 2. multiLine = True // For more details, // please refer to documetation of QgsProcessingParameterString. // setting default_value this way is an exception for ParameterType_StringList and ParameterType_String default_value = "None|True"; } else if (type == ParameterType_InputImage) { // default is None and nothing to add to dFile } else if(type ==ParameterType_ListView) { // default is None and nothing to add to dFile } else if(type == ParameterType_Bool) { default_value = appli->GetParameterAsString(name); } else if(type == ParameterType_Choice) { std::vector<std::string> key_list = appli->GetChoiceKeys(name); std::string values = ""; for( auto k : key_list) values += k + ";"; values.pop_back(); dFile << "|" << values ; ChoiceParameter *cparam = dynamic_cast<ChoiceParameter*>(param.GetPointer()); default_value = std::to_string(cparam->GetValue()); } else if(type == ParameterType_OutputVectorData || type == ParameterType_OutputImage || type == ParameterType_OutputFilename) { // No need for default_value, optional and extra fields in dFile. // If parameter is a destination type. qgis_type|name|description is enough. // So we simply set isDestination to true and skip to end to append a new line. isDestination = true; } else { std::cout << "ERROR: default_value is empty for '" << name << "' type='" << qgis_type << "'" << std::endl; return EXIT_FAILURE; } if (!isDestination) { std::string optional; if (param->GetMandatory()) { // TODO: avoid workaround for stringlist types (fix appengine) // type == ParameterType_StringList check is needed because: // If parameter is mandatory it can have no value // It is accepted in OTB that, string list could be generated dynamically // qgis has no such option to handle dynamic values yet.. // So mandatory parameters whose type is StringList is considered optional optional = param->HasValue() || type == ParameterType_StringList ? "True" : "False"; } else { optional = "True"; } #if 0 std::cerr << name; std::cerr << " mandatory=" << param->GetMandatory(); std::cerr << " HasValue=" << param->HasValue(); std::cerr << " qgis_type=" << qgis_type; std::cerr << " optional=" << optional << std::endl; #endif dFile << "|" << default_value << "|" << optional; } dFile << std::endl; } if(hasRasterOutput) { dFile << "*QgsProcessingParameterEnum|outputpixeltype|Output pixel type|unit8;int;float;double|False|2|True" << std::endl; } dFile.close(); std::ofstream indexFile; indexFile.open (algs_txt, std::ios::out | std::ios::app ); indexFile << group << "|" << module << std::endl; indexFile.close(); std::cerr << "Updated " << algs_txt << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "ncv.h" #include "common/convolution.hpp" #include "opencl/opencl.h" using namespace ncv; const std::string conv_program_source = R"xxx( #pragma OPENCL EXTENSION cl_amd_fp64 : enable #pragma OPENCL EXTENSION cl_khr_fp64 : enable __kernel void conv_kernel( __global const double* idata, int icols, __constant const double* kdata, int krows, int kcols, __global double* odata) { const int x = get_global_id(0); const int y = get_global_id(1); double sum = 0; for (int r = 0, kidx = 0; r < krows; r ++) { int iidx = (y + r) * icols + x; for (int c = 0; c < kcols; c ++, kidx ++, iidx ++) { sum += kdata[kidx] * idata[iidx]; } } odata[y * get_global_size(0) + x] = sum; } )xxx"; ncv::thread_pool_t pool; const size_t tests = 4; void init_matrix(int rows, int cols, matrix_t& matrix) { matrix.resize(rows, cols); matrix.setRandom(); matrix /= rows; } void init_matrices(int rows, int cols, int count, matrices_t& matrices) { matrices.resize(count); for (int i = 0; i < count; i ++) { init_matrix(rows, cols, matrices[i]); } } void zero_matrices(matrices_t& matrices) { for (size_t i = 0; i < matrices.size(); i ++) { matrices[i].setZero(); } } scalar_t sum_matrices(matrices_t& matrices) { scalar_t sum = 0; for (size_t i = 0; i < matrices.size(); i ++) { sum += matrices[i].sum(); } return sum; } template <typename top> void test_conv2D_1cpu(top op, const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas) { ncv::stats_t<double, size_t> proc_stats; // run multiple tests for (size_t t = 0; t < tests; t ++) { zero_matrices(odatas); const ncv::timer_t timer; for (size_t i = 0; i < idatas.size(); i ++) { op(idatas[i], kdata, odatas[i]); } proc_stats(timer.miliseconds()); } const scalar_t sum = sum_matrices(odatas); const size_t milis = static_cast<size_t>(proc_stats.avg()); std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right) << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ") "; } template <typename top> void test_conv2D_xcpu(top op, const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas) { ncv::stats_t<double, size_t> proc_stats; // run multiple tests for (size_t t = 0; t < tests; t ++) { zero_matrices(odatas); const ncv::timer_t timer; ncv::thread_loop(idatas.size(), [&] (size_t i) { op(idatas[i], kdata, odatas[i]); }, pool); proc_stats(timer.miliseconds()); } const scalar_t sum = sum_matrices(odatas); const size_t milis = static_cast<size_t>(proc_stats.avg()); std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right) << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ") "; } void test_conv2D_gpu(const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas) { const cl::Context& context = ocl::manager_t::instance().context(); const cl::CommandQueue& queue = ocl::manager_t::instance().queue(); const cl::Program program = ocl::manager_t::instance().program_from_text(conv_program_source); cl::Kernel kernel = cl::Kernel(program, "conv_kernel"); const int icols = static_cast<int>(idatas[0].cols()); const int krows = static_cast<int>(kdata.rows()); const int kcols = static_cast<int>(kdata.cols()); const int orows = static_cast<int>(odatas[0].rows()); const int ocols = static_cast<int>(odatas[0].cols()); const size_t mem_idata = idatas[0].size() * sizeof(scalar_t); const size_t mem_kdata = kdata.size() * sizeof(scalar_t); const size_t mem_odata = odatas[0].size() * sizeof(scalar_t); // create buffers once cl::Buffer cl_idata = cl::Buffer(context, CL_MEM_READ_ONLY, mem_idata, NULL); cl::Buffer cl_kdata = cl::Buffer(context, CL_MEM_READ_ONLY, mem_kdata, NULL); cl::Buffer cl_odata = cl::Buffer(context, CL_MEM_WRITE_ONLY, mem_odata, NULL); // setup kernel buffers once kernel.setArg(0, cl_idata); kernel.setArg(1, sizeof(int), (void*)&icols); kernel.setArg(2, cl_kdata); kernel.setArg(3, sizeof(int), (void*)&krows); kernel.setArg(4, sizeof(int), (void*)&kcols); kernel.setArg(5, cl_odata); queue.finish(); // transfer constants cl::Event event; queue.enqueueWriteBuffer(cl_kdata, CL_FALSE, 0, mem_kdata, kdata.data(), NULL, &event); queue.finish(); ncv::stats_t<double, size_t> proc_stats; // run multiple tests for (size_t t = 0; t < tests; t ++) { zero_matrices(odatas); ncv::timer_t timer; for (size_t i = 0; i < idatas.size(); i ++) { const matrix_t& idata = idatas[i]; matrix_t& odata = odatas[i]; // I - send inputs to gpu cl::Event event; queue.enqueueWriteBuffer(cl_idata, CL_FALSE, 0, mem_idata, idata.data(), NULL, &event); queue.finish(); // II - gpu processing queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(ocols, orows), cl::NullRange, NULL, &event); queue.finish(); // III - read results from gpu queue.enqueueReadBuffer(cl_odata, CL_TRUE, 0, mem_odata, odata.data(), NULL, &event); } proc_stats(timer.miliseconds()); } const scalar_t sum = sum_matrices(odatas); const size_t milis = static_cast<size_t>(proc_stats.avg()); std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right) << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ") "; } void test(int isize, int ksize, int n_samples) { const int osize = isize - ksize + 1; matrices_t idatas, odatas; matrix_t kdata; init_matrices(isize, isize, n_samples, idatas); init_matrices(osize, osize, n_samples, odatas); init_matrix(ksize, ksize, kdata); std::cout << "mix (isize = " << isize << ", ksize = " << ksize << "): \t"; test_conv2D_1cpu(ncv::math::conv_eib<matrix_t>, "eib(1CPU)", idatas, kdata, odatas); test_conv2D_xcpu(ncv::math::conv_eib<matrix_t>, "eib(xCPU)", idatas, kdata, odatas); test_conv2D_1cpu(ncv::math::conv_dot<matrix_t>, "dot(1CPU)", idatas, kdata, odatas); test_conv2D_xcpu(ncv::math::conv_dot<matrix_t>, "dot(xCPU)", idatas, kdata, odatas); test_conv2D_gpu("dot(GPU)", idatas, kdata, odatas); std::cout << std::endl; } int main(int argc, char* argv[]) { if (!ocl::manager_t::instance().valid()) { exit(EXIT_FAILURE); } static const int min_isize = 24; static const int max_isize = 48; static const int min_ksize = 5; static const int max_ksize = 13; static const int n_samples = 10000; try { for (int isize = min_isize; isize <= max_isize; isize += 4) { for (int ksize = min_ksize; ksize <= max_ksize; ksize ++) { test(isize, ksize, n_samples); } std::cout << std::endl; } } catch (cl::Error e) { log_error() << "OpenCL fatal error: <" << e.what() << "> (" << ocl::error_string(e.err()) << ")!"; } return EXIT_SUCCESS; } <commit_msg>faster GPU-based convolution (process many convolutions at the same time)<commit_after>#include "ncv.h" #include "common/convolution.hpp" #include "opencl/opencl.h" using namespace ncv; const std::string conv_program_source = R"xxx( #pragma OPENCL EXTENSION cl_amd_fp64 : enable #pragma OPENCL EXTENSION cl_khr_fp64 : enable __kernel void conv_kernel( __global const double* idata, __constant double* kdata, int krows, int kcols, __global double* odata) { const int odims = get_global_size(0); const int ocols = get_global_size(1); const int orows = get_global_size(2); const int osize = orows * ocols; const int icols = ocols + kcols - 1; const int irows = orows + krows - 1; const int isize = irows * icols; const int o = get_global_id(0); const int x = get_global_id(1); const int y = get_global_id(2); double sum = 0; for (int r = 0, kidx = 0; r < krows; r ++) { int iidx = o * isize + (y + r) * icols + x; for (int c = 0; c < kcols; c ++, kidx ++, iidx ++) { sum += kdata[kidx] * idata[iidx]; } } odata[o * osize + y * ocols + x] = sum; } )xxx"; ncv::thread_pool_t pool; const size_t tests = 4; void init_matrix(int rows, int cols, matrix_t& matrix) { matrix.resize(rows, cols); matrix.setRandom(); matrix /= rows; } void init_matrices(int rows, int cols, int count, matrices_t& matrices) { matrices.resize(count); for (int i = 0; i < count; i ++) { init_matrix(rows, cols, matrices[i]); } } void zero_matrices(matrices_t& matrices) { for (size_t i = 0; i < matrices.size(); i ++) { matrices[i].setZero(); } } scalar_t sum_matrices(matrices_t& matrices) { scalar_t sum = 0; for (size_t i = 0; i < matrices.size(); i ++) { sum += matrices[i].sum(); } return sum; } template <typename top> void test_conv2D_1cpu(top op, const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas) { ncv::stats_t<double, size_t> proc_stats; // run multiple tests for (size_t t = 0; t < tests; t ++) { zero_matrices(odatas); const ncv::timer_t timer; for (size_t i = 0; i < idatas.size(); i ++) { op(idatas[i], kdata, odatas[i]); } proc_stats(timer.miliseconds()); } const scalar_t sum = sum_matrices(odatas); const size_t milis = static_cast<size_t>(proc_stats.avg()); std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right) << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ") "; } template <typename top> void test_conv2D_xcpu(top op, const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas) { ncv::stats_t<double, size_t> proc_stats; // run multiple tests for (size_t t = 0; t < tests; t ++) { zero_matrices(odatas); const ncv::timer_t timer; ncv::thread_loop(idatas.size(), [&] (size_t i) { op(idatas[i], kdata, odatas[i]); }, pool); proc_stats(timer.miliseconds()); } const scalar_t sum = sum_matrices(odatas); const size_t milis = static_cast<size_t>(proc_stats.avg()); std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right) << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ") "; } void test_conv2D_gpu(const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas) { const cl::Context& context = ocl::manager_t::instance().context(); const cl::CommandQueue& queue = ocl::manager_t::instance().queue(); const cl::Program program = ocl::manager_t::instance().program_from_text(conv_program_source); cl::Kernel kernel = cl::Kernel(program, "conv_kernel"); const int irows = static_cast<int>(idatas[0].rows()); const int icols = static_cast<int>(idatas[0].cols()); const int isize = irows * icols; const int krows = static_cast<int>(kdata.rows()); const int kcols = static_cast<int>(kdata.cols()); const int orows = static_cast<int>(odatas[0].rows()); const int ocols = static_cast<int>(odatas[0].cols()); const int osize = orows * ocols; const int tsend = 10; scalars_t sidata(tsend * isize); scalars_t sodata(tsend * osize); const size_t mem_idata = idatas[0].size() * sizeof(scalar_t) * tsend; const size_t mem_kdata = kdata.size() * sizeof(scalar_t); const size_t mem_odata = odatas[0].size() * sizeof(scalar_t) * tsend; // create buffers once cl::Buffer cl_idata = cl::Buffer(context, CL_MEM_READ_ONLY, mem_idata, NULL); cl::Buffer cl_kdata = cl::Buffer(context, CL_MEM_READ_ONLY, mem_kdata, NULL); cl::Buffer cl_odata = cl::Buffer(context, CL_MEM_WRITE_ONLY, mem_odata, NULL); // setup kernel buffers once kernel.setArg(0, cl_idata); kernel.setArg(1, cl_kdata); kernel.setArg(2, sizeof(int), (void*)&krows); kernel.setArg(3, sizeof(int), (void*)&kcols); kernel.setArg(4, cl_odata); queue.finish(); // transfer constants cl::Event event; queue.enqueueWriteBuffer(cl_kdata, CL_FALSE, 0, mem_kdata, kdata.data(), NULL, &event); queue.finish(); ncv::stats_t<double, size_t> proc_stats; // run multiple tests for (size_t t = 0; t < tests; t ++) { zero_matrices(odatas); ncv::timer_t timer; for (size_t i = 0; i < idatas.size(); i += tsend) { for (size_t it = 0; it < tsend; it ++) { const matrix_t& idata = idatas[i + it]; std::copy(idata.data(), idata.data() + idata.size(), sidata.data() + (it * isize)); } // I - send inputs to gpu cl::Event event; queue.enqueueWriteBuffer(cl_idata, CL_FALSE, 0, mem_idata, sidata.data(), NULL, &event); queue.finish(); // II - gpu processing queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(tsend, ocols, orows), cl::NullRange, NULL, &event); queue.finish(); // III - read results from gpu queue.enqueueReadBuffer(cl_odata, CL_TRUE, 0, mem_odata, sodata.data(), NULL, &event); for (size_t it = 0; it < tsend; it ++) { matrix_t& odata = odatas[i + it]; std::copy(sodata.data() + (it * osize), sodata.data() + (it * osize + osize), odata.data()); } } proc_stats(timer.miliseconds()); } const scalar_t sum = sum_matrices(odatas); const size_t milis = static_cast<size_t>(proc_stats.avg()); std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right) << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ") "; } void test(int isize, int ksize, int n_samples) { const int osize = isize - ksize + 1; matrices_t idatas, odatas; matrix_t kdata; init_matrices(isize, isize, n_samples, idatas); init_matrices(osize, osize, n_samples, odatas); init_matrix(ksize, ksize, kdata); std::cout << "mix (isize = " << isize << ", ksize = " << ksize << "): \t"; test_conv2D_1cpu(ncv::math::conv_eib<matrix_t>, "eib(1CPU)", idatas, kdata, odatas); test_conv2D_xcpu(ncv::math::conv_eib<matrix_t>, "eib(xCPU)", idatas, kdata, odatas); test_conv2D_1cpu(ncv::math::conv_dot<matrix_t>, "dot(1CPU)", idatas, kdata, odatas); test_conv2D_xcpu(ncv::math::conv_dot<matrix_t>, "dot(xCPU)", idatas, kdata, odatas); test_conv2D_gpu("dot(GPU)", idatas, kdata, odatas); std::cout << std::endl; } int main(int argc, char* argv[]) { if (!ocl::manager_t::instance().valid()) { exit(EXIT_FAILURE); } static const int min_isize = 24; static const int max_isize = 48; static const int min_ksize = 5; static const int max_ksize = 13; static const int n_samples = 10000; try { for (int isize = min_isize; isize <= max_isize; isize += 4) { for (int ksize = min_ksize; ksize <= max_ksize; ksize ++) { test(isize, ksize, n_samples); } std::cout << std::endl; } } catch (cl::Error e) { log_error() << "OpenCL fatal error: <" << e.what() << "> (" << ocl::error_string(e.err()) << ")!"; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * ougoing_buffer_test.cpp * * Created on: Jan 25, 2016 * Author: zmij */ #include <gtest/gtest.h> #include <wire/encoding/buffers.hpp> namespace wire { namespace encoding { namespace test { namespace { const int INSERT_CHARS = 100; } // namespace TEST(OutgoingBuffer, Construction) { outgoing out; EXPECT_TRUE(out.empty()); EXPECT_EQ(0, out.size()); out.push_back(1); EXPECT_EQ(1, out.size()); for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS + 1, out.size()); out.pop_back(); EXPECT_EQ(INSERT_CHARS, out.size()); } TEST(OutgoingBuffer, ForwardIterators) { outgoing out; outgoing::iterator b = out.begin(); outgoing::iterator e = out.end(); outgoing::const_iterator cb = out.begin(); outgoing::const_iterator ce = out.end(); EXPECT_EQ(e, b); EXPECT_EQ(0, b - e); EXPECT_EQ(ce, cb); EXPECT_EQ(0, cb - ce); for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } b = out.begin(); e = out.end(); ASSERT_NE(b, e); EXPECT_EQ(INSERT_CHARS, e - b); EXPECT_EQ(-INSERT_CHARS, b - e); { int steps = 0; for (outgoing::iterator p = b; p != e; ++p, ++steps) {} EXPECT_EQ(INSERT_CHARS, steps); } { int steps = 0; for (outgoing::const_iterator p = b; p != e; ++p, ++steps) {} EXPECT_EQ(INSERT_CHARS, steps); } { outgoing out1; EXPECT_DEATH({ out.begin() - out1.begin(); }, "Iterator belongs to container"); } } TEST(OutgoingBuffer, DISABLED_ReverseIterators) { outgoing out; for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS, out.size()); int steps = 0; for (outgoing::reverse_iterator p = out.rbegin(); p != out.rend(); ++p, ++steps) {} EXPECT_EQ(INSERT_CHARS, steps); } TEST(OutgoingBuffer, Encapsulation) { outgoing out; for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS, out.size()); { outgoing::encapsulation encaps(out.begin_encapsulation()); for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS, encaps.size()); EXPECT_EQ(INSERT_CHARS*2, out.size()); // Before encapsulation is closed } EXPECT_EQ(INSERT_CHARS*2 + 3, out.size()); // After encapsulation is closed, size of 100 fits into one byte, 2 bytes are encaps header } } // namespace test } // namespace encoding } // namespace wire <commit_msg>Add nested encapsulation test<commit_after>/* * ougoing_buffer_test.cpp * * Created on: Jan 25, 2016 * Author: zmij */ #include <gtest/gtest.h> #include <wire/encoding/buffers.hpp> namespace wire { namespace encoding { namespace test { namespace { const int INSERT_CHARS = 100; } // namespace TEST(OutgoingBuffer, Construction) { outgoing out; EXPECT_TRUE(out.empty()); EXPECT_EQ(0, out.size()); out.push_back(1); EXPECT_EQ(1, out.size()); for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS + 1, out.size()); out.pop_back(); EXPECT_EQ(INSERT_CHARS, out.size()); } TEST(OutgoingBuffer, ForwardIterators) { outgoing out; outgoing::iterator b = out.begin(); outgoing::iterator e = out.end(); outgoing::const_iterator cb = out.begin(); outgoing::const_iterator ce = out.end(); EXPECT_EQ(e, b); EXPECT_EQ(0, b - e); EXPECT_EQ(ce, cb); EXPECT_EQ(0, cb - ce); for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } b = out.begin(); e = out.end(); ASSERT_NE(b, e); EXPECT_EQ(INSERT_CHARS, e - b); EXPECT_EQ(-INSERT_CHARS, b - e); { int steps = 0; for (outgoing::iterator p = b; p != e; ++p, ++steps) {} EXPECT_EQ(INSERT_CHARS, steps); } { int steps = 0; for (outgoing::const_iterator p = b; p != e; ++p, ++steps) {} EXPECT_EQ(INSERT_CHARS, steps); } { outgoing out1; EXPECT_DEATH({ out.begin() - out1.begin(); }, "Iterator belongs to container"); } } TEST(OutgoingBuffer, DISABLED_ReverseIterators) { outgoing out; for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS, out.size()); int steps = 0; for (outgoing::reverse_iterator p = out.rbegin(); p != out.rend(); ++p, ++steps) {} EXPECT_EQ(INSERT_CHARS, steps); } TEST(OutgoingBuffer, Encapsulation) { outgoing out; for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS, out.size()); { outgoing::encapsulation encaps(out.begin_encapsulation()); for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS, encaps.size()); EXPECT_EQ(INSERT_CHARS*2, out.size()); // Before encapsulation is closed } EXPECT_EQ(INSERT_CHARS*2 + 3, out.size()); // After encapsulation is closed, size of 100 fits into one byte, 2 bytes are encaps header } TEST(OutgoingBuffer, NestedEncapsulation) { outgoing out; for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS, out.size()); { outgoing::encapsulation outer(out.begin_encapsulation()); for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS, outer.size()); EXPECT_EQ(INSERT_CHARS*2, out.size()); // Before encapsulation is closed { outgoing::encapsulation inner(out.begin_encapsulation()); for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS, inner.size()); EXPECT_EQ(INSERT_CHARS*2, outer.size()); EXPECT_EQ(INSERT_CHARS*3, out.size()); // Before encapsulation is closed } EXPECT_EQ(INSERT_CHARS*2 + 3, outer.size()); EXPECT_EQ(INSERT_CHARS*3 + 3, out.size()); // Before encapsulation is closed for (uint8_t i = 0; i < INSERT_CHARS; ++i) { out.push_back(i); } EXPECT_EQ(INSERT_CHARS*3 + 3, outer.size()); EXPECT_EQ(INSERT_CHARS*4 + 3, out.size()); // Before encapsulation is closed } EXPECT_EQ(INSERT_CHARS*4 + 7, out.size()); // After encapsulation is closed, size of 200 fits into two bytes, 2 bytes per encaps header } } // namespace test } // namespace encoding } // namespace wire <|endoftext|>
<commit_before>AliAnalysisGrid* CreateAlienHandlerCaloEtSim(TString outputDir, TString outputName, const char * pluginRunMode) { // Check if user has a valid token, otherwise make one. This has limitations. // One can always follow the standard procedure of calling alien-token-init then // source /tmp/gclient_env_$UID in the current shell. if (!AliAnalysisGrid::CreateToken()) return NULL; AliAnalysisAlien *plugin = new AliAnalysisAlien(); // Overwrite all generated files, datasets and output results from a previous session plugin->SetOverwriteMode(); // Set the run mode (can be "full", "test", "offline", "submit" or "terminate") // plugin->SetRunMode("full"); // VERY IMPORTANT - DECRIBED BELOW // plugin->SetRunMode("test"); // VERY IMPORTANT - DECRIBED BELOW plugin->SetRunMode(pluginRunMode); // VERY IMPORTANT - DECRIBED BELOW // Set versions of used packages plugin->SetAPIVersion("V1.1x"); plugin->SetROOTVersion("v5-27-06-1"); plugin->SetAliROOTVersion("v4-20-12-AN"); // Declare input data to be processed. // Method 1: Create automatically XML collections using alien 'find' command. // Define production directory LFN // plugin->SetGridDataDir("/alice/sim/LHC10a18"); // Set data search pattern // plugin->SetDataPattern("*ESDs.root"); // simulated, tags not used // plugin->SetDataPattern("*ESDs/pass4/*ESDs.root"); // real data check reco pass and data base directory // plugin->SetRunPrefix("000"); // real data // plugin->SetDataPattern("*tag.root"); // Use ESD tags (same applies for AOD's) // ...then add run numbers to be considered // plugin->AddRunNumber(125020); // simulated // plugin->AddRunNumber(104065); // real data // Method 2: Declare existing data files (raw collections, xml collections, root file) // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir()) // XML collections added via this method can be combined with the first method if // the content is compatible (using or not tags) plugin->AddDataFile("tag.xml"); // plugin->AddDataFile("wn.xml"); // test // file generated with: find -x tag /alice/sim/LHC10d1/117222/* AliESDs.root > tag.xml // Define alien work directory where all files will be copied. Relative to alien $HOME. plugin->SetGridWorkingDir(outputDir.Data()); // Declare alien output directory. Relative to working directory. plugin->SetGridOutputDir("output"); // In this case will be $HOME/work/output // Declare the analysis source files names separated by blancs. To be compiled runtime IN THE SAME ORDER THEY ARE LISTED // using ACLiC on the worker nodes. plugin->SetAnalysisSource("AliAnalysisEtCuts.cxx AliAnalysisHadEtCorrections.cxx AliAnalysisEtCommon.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx"); // Declare all libraries (other than the default ones for the framework. These will be // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here. plugin->SetAdditionalLibs("AliAnalysisEtCuts.h AliAnalysisEt.h AliAnalysisEtMonteCarlo.h AliAnalysisEtMonteCarloPhos.h AliAnalysisEtMonteCarloEmcal.h AliAnalysisEtReconstructed.h AliAnalysisEtReconstructedPhos.h AliAnalysisEtReconstructedEmcal.h AliAnalysisTaskTotEt.h AliAnalysisEtCuts.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx AliAnalysisEtCommon.cxx AliAnalysisEtCommon.h AliAnalysisHadEtCorrections.h AliAnalysisHadEtCorrections.cxx ConfigEtMonteCarlo.C ConfigEtReconstructed.C"); plugin->SetExecutableCommand("aliroot -b -q"); // add extra include files/path plugin->AddIncludePath("-I. -I$ALICE_ROOT/EMCAL -I$ALICE_ROOT/ANALYSIS"); // No need for output file names. Procedure is automatic. <-- not true plugin->SetDefaultOutputs(kFALSE); plugin->SetOutputFiles(outputName.Data()); // No need define the files to be archived. Note that this is handled automatically by the plugin. // plugin->SetOutputArchive("log_archive.zip:stdout,stderr"); // Set a name for the generated analysis macro (default MyAnalysis.C) Make this unique ! plugin->SetAnalysisMacro("DavidEtAnalysis.C"); // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore). The optimum for an analysis // is correlated with the run time - count few hours TTL per job, not minutes ! plugin->SetSplitMaxInputFileNumber(100); // Optionally set number of failed jobs that will trigger killing waiting sub-jobs. plugin->SetMaxInitFailed(5); // Optionally resubmit threshold. plugin->SetMasterResubmitThreshold(90); // Optionally set time to live (default 30000 sec) plugin->SetTTL(20000); // Optionally set input format (default xml-single) plugin->SetInputFormat("xml-single"); // Optionally modify the name of the generated JDL (default analysis.jdl) plugin->SetJDLName("TaskEt.jdl"); // Optionally modify job price (default 1) plugin->SetPrice(1); // Optionally modify split mode (default 'se') plugin->SetSplitMode("se"); return plugin; } <commit_msg>Updates to get jobs running on the grid<commit_after>AliAnalysisGrid* CreateAlienHandlerCaloEtSim(TString outputDir, TString outputName, const char * pluginRunMode) { // Check if user has a valid token, otherwise make one. This has limitations. // One can always follow the standard procedure of calling alien-token-init then // source /tmp/gclient_env_$UID in the current shell. if (!AliAnalysisGrid::CreateToken()) return NULL; AliAnalysisAlien *plugin = new AliAnalysisAlien(); // Overwrite all generated files, datasets and output results from a previous session plugin->SetOverwriteMode(); // Set the run mode (can be "full", "test", "offline", "submit" or "terminate") // plugin->SetRunMode("full"); // VERY IMPORTANT - DECRIBED BELOW // plugin->SetRunMode("test"); // VERY IMPORTANT - DECRIBED BELOW plugin->SetRunMode(pluginRunMode); // VERY IMPORTANT - DECRIBED BELOW // Set versions of used packages plugin->SetAPIVersion("V1.1x"); plugin->SetROOTVersion("v5-27-06b"); plugin->SetAliROOTVersion("v4-21-11-AN"); // Declare input data to be processed. // Method 1: Create automatically XML collections using alien 'find' command. // Define production directory LFN // plugin->SetGridDataDir("/alice/sim/LHC10a18"); // Set data search pattern // plugin->SetDataPattern("*ESDs.root"); // simulated, tags not used // plugin->SetDataPattern("*ESDs/pass4/*ESDs.root"); // real data check reco pass and data base directory // plugin->SetRunPrefix("000"); // real data // plugin->SetDataPattern("*tag.root"); // Use ESD tags (same applies for AOD's) // ...then add run numbers to be considered // plugin->AddRunNumber(125020); // simulated // plugin->AddRunNumber(104065); // real data plugin->SetGridDataDir("/alice/sim/LHC10d4"); plugin->SetDataPattern("*ESDs.root"); plugin->AddRunNumber("120741");//smallest of the above // Method 2: Declare existing data files (raw collections, xml collections, root file) // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir()) // XML collections added via this method can be combined with the first method if // the content is compatible (using or not tags) //plugin->AddDataFile("tag.xml"); // plugin->AddDataFile("wn.xml"); // test // file generated with: find -x tag /alice/sim/LHC10d1/117222/* AliESDs.root > tag.xml // Define alien work directory where all files will be copied. Relative to alien $HOME. plugin->SetGridWorkingDir(outputDir.Data()); // Declare alien output directory. Relative to working directory. plugin->SetGridOutputDir("output"); // In this case will be $HOME/work/output // Declare the analysis source files names separated by blancs. To be compiled runtime IN THE SAME ORDER THEY ARE LISTED // using ACLiC on the worker nodes. plugin->SetAnalysisSource("AliAnalysisEtCuts.cxx AliAnalysisHadEtCorrections.cxx AliAnalysisEtCommon.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx"); // Declare all libraries (other than the default ones for the framework. These will be // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here. plugin->SetAdditionalLibs("AliAnalysisEtCuts.h AliAnalysisEt.h AliAnalysisEtMonteCarlo.h AliAnalysisEtMonteCarloPhos.h AliAnalysisEtMonteCarloEmcal.h AliAnalysisEtReconstructed.h AliAnalysisEtReconstructedPhos.h AliAnalysisEtReconstructedEmcal.h AliAnalysisTaskTotEt.h AliAnalysisEtCuts.cxx AliAnalysisEt.cxx AliAnalysisEtMonteCarlo.cxx AliAnalysisEtMonteCarloPhos.cxx AliAnalysisEtMonteCarloEmcal.cxx AliAnalysisEtReconstructed.cxx AliAnalysisEtReconstructedPhos.cxx AliAnalysisEtReconstructedEmcal.cxx AliAnalysisTaskTotEt.cxx AliAnalysisEtCommon.cxx AliAnalysisEtCommon.h AliAnalysisHadEtCorrections.h AliAnalysisHadEtCorrections.cxx ConfigEtMonteCarlo.C ConfigEtReconstructed.C physicsSelections.root corrections.root"); plugin->SetExecutableCommand("aliroot -b -q"); // add extra include files/path plugin->AddIncludePath("-I. -I$ALICE_ROOT/EMCAL -I$ALICE_ROOT/ANALYSIS"); // No need for output file names. Procedure is automatic. <-- not true plugin->SetDefaultOutputs(kFALSE); plugin->SetOutputFiles(outputName.Data()); // No need define the files to be archived. Note that this is handled automatically by the plugin. // plugin->SetOutputArchive("log_archive.zip:stdout,stderr"); // Set a name for the generated analysis macro (default MyAnalysis.C) Make this unique ! plugin->SetAnalysisMacro("DavidEtAnalysis.C"); // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore). The optimum for an analysis // is correlated with the run time - count few hours TTL per job, not minutes ! plugin->SetSplitMaxInputFileNumber(100); // Optionally set number of failed jobs that will trigger killing waiting sub-jobs. plugin->SetMaxInitFailed(5); // Optionally resubmit threshold. plugin->SetMasterResubmitThreshold(90); // Optionally set time to live (default 30000 sec) plugin->SetTTL(20000); // Optionally set input format (default xml-single) plugin->SetInputFormat("xml-single"); // Optionally modify the name of the generated JDL (default analysis.jdl) plugin->SetJDLName("TaskEt.jdl"); // Optionally modify job price (default 1) plugin->SetPrice(1); // Optionally modify split mode (default 'se') plugin->SetSplitMode("se"); return plugin; } <|endoftext|>
<commit_before> AliAnalysisTaskEMCALIsoPhoton *AddTaskEMCALIsoPhoton( TString period = "LHC11d", TString trigbitname = "kEMC7", TString geoname="EMCAL_COMPLETEV1", TString pathstrsel = "/" ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEMCALIsoPhoton", "No analysis manager to connect to."); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskEMCALIsoPhoton* ana = new AliAnalysisTaskEMCALIsoPhoton(""); Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL); if(!isMC) ana->SelectCollisionCandidates( AliVEvent::kEMC1 | AliVEvent::kMB | AliVEvent::kEMC7 | AliVEvent::kINT7); //ana->SetClusThreshold(clusTh); ana->SetTrainMode(kTRUE); ana->SetTriggerBit(trigbitname); ana->SetMcMode(isMC); ana->SetPathStringSelect(pathstrsel.Data()); AliESDtrackCuts *cutsp = new AliESDtrackCuts; cutsp->SetMinNClustersTPC(70); cutsp->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8); cutsp->SetMaxChi2PerClusterTPC(4); cutsp->SetRequireTPCRefit(kTRUE); cutsp->SetAcceptKinkDaughters(kFALSE); cutsp->SetMaxDCAToVertexZ(3.2); cutsp->SetMaxDCAToVertexXY(2.4); cutsp->SetDCAToVertex2D(kTRUE); cutsp->SetPtRange(0.2); cutsp->SetEtaRange(-1.0,1.0); ana->SetPrimTrackCuts(cutsp); ana->SetPeriod(period.Data()); ana->SetGeoName(geoname.Data()); mgr->AddTask(ana); TString containername = "histosEMCALIsoPhoton"; TString containernameQA = "histosQA"; if(pathstrsel != "/"){ TString dirpth = (TSubString)pathstrsel.operator()(1,1); containername += dirpth; containernameQA += dirpth; } // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(containername.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, Form("%s", AliAnalysisManager::GetCommonFileName())); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(containernameQA.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, Form("%s", AliAnalysisManager::GetCommonFileName())); mgr->ConnectInput (ana, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (ana, 1, coutput1 ); mgr->ConnectOutput (ana, 2, coutput2 ); return ana; } <commit_msg>parametrizing the output containers names according to trigger type<commit_after> AliAnalysisTaskEMCALIsoPhoton *AddTaskEMCALIsoPhoton( TString period = "LHC11d", TString trigbitname = "kEMC7", TString geoname="EMCAL_COMPLETEV1", TString pathstrsel = "/" ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEMCALIsoPhoton", "No analysis manager to connect to."); return NULL; } // Create the task and configure it. //=========================================================================== AliAnalysisTaskEMCALIsoPhoton* ana = new AliAnalysisTaskEMCALIsoPhoton(""); Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL); if(!isMC) ana->SelectCollisionCandidates( AliVEvent::kEMC1 | AliVEvent::kMB | AliVEvent::kEMC7 | AliVEvent::kINT7); //ana->SetClusThreshold(clusTh); ana->SetTrainMode(kTRUE); ana->SetTriggerBit(trigbitname); ana->SetMcMode(isMC); ana->SetPathStringSelect(pathstrsel.Data()); AliESDtrackCuts *cutsp = new AliESDtrackCuts; cutsp->SetMinNClustersTPC(70); cutsp->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8); cutsp->SetMaxChi2PerClusterTPC(4); cutsp->SetRequireTPCRefit(kTRUE); cutsp->SetAcceptKinkDaughters(kFALSE); cutsp->SetMaxDCAToVertexZ(3.2); cutsp->SetMaxDCAToVertexXY(2.4); cutsp->SetDCAToVertex2D(kTRUE); cutsp->SetPtRange(0.2); cutsp->SetEtaRange(-1.0,1.0); ana->SetPrimTrackCuts(cutsp); ana->SetPeriod(period.Data()); ana->SetGeoName(geoname.Data()); mgr->AddTask(ana); TString containername = "histEMCIsoPhoton."+trigbitname; TString containernameQA = "histosQA."+trigbitname; if(pathstrsel != "/"){ TString dirpth = (TSubString)pathstrsel.operator()(1,1); containername += dirpth; containernameQA += dirpth; } // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(containername.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, Form("%s", AliAnalysisManager::GetCommonFileName())); AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(containernameQA.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, Form("%s", AliAnalysisManager::GetCommonFileName())); mgr->ConnectInput (ana, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (ana, 1, coutput1 ); mgr->ConnectOutput (ana, 2, coutput2 ); return ana; } <|endoftext|>
<commit_before><commit_msg>rename module<commit_after><|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <stdint.h> #include <assert.h> #include "mailbox.h" #include "v3d.h" // I/O access volatile unsigned *v3d; int mbox; // Execute a nop control list to prove that we have contol. void testControlLists() { // First we allocate and map some videocore memory to build our control list in. // ask the blob to allocate us 256 bytes with 4k alignment, zero it. unsigned int handle = mem_alloc(mbox, 0x100, 0x1000, MEM_FLAG_COHERENT | MEM_FLAG_ZERO); if (!handle) { printf("Error: Unable to allocate memory"); return; } // ask the blob to lock our memory at a single location at give is that address. uint32_t bus_addr = mem_lock(mbox, handle); // map that address into our local address space. uint8_t *list = (uint8_t*) mapmem(bus_addr, 0x100); // Now we construct our control list. // 255 nops, with a halt somewhere in the middle for(int i = 0; i < 0xff; i++) { list[i] = 1; // NOP } list[0xbb] = 0; // Halt. // And then we setup the v3d pipeline to execute the control list. printf("V3D_CT0CS: 0x%08x\n", v3d[V3D_CT0CS]); printf("Start Address: 0x%08x\n", bus_addr); // Current Address = start of our list (bus address) v3d[V3D_CT0CA] = bus_addr; // End Address = just after the end of our list (bus address) // This also starts execution. v3d[V3D_CT0EA] = bus_addr + 0x100; // print status while running printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); // Wait a second to be sure the contorl list execution has finished while(v3d[V3D_CT0CS] & 0x20); // print the status again. printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); // Release memory; unmapmem((void *) list, 0x100); mem_unlock(mbox, handle); mem_free(mbox, handle); } void addbyte(uint8_t **list, uint8_t d) { *((*list)++) = d; } void addshort(uint8_t **list, uint16_t d) { *((*list)++) = (d) & 0xff; *((*list)++) = (d >> 8) & 0xff; } void addword(uint8_t **list, uint32_t d) { *((*list)++) = (d) & 0xff; *((*list)++) = (d >> 8) & 0xff; *((*list)++) = (d >> 16) & 0xff; *((*list)++) = (d >> 24) & 0xff; } void addfloat(uint8_t **list, float f) { uint32_t d = *((uint32_t *)&f); *((*list)++) = (d) & 0xff; *((*list)++) = (d >> 8) & 0xff; *((*list)++) = (d >> 16) & 0xff; *((*list)++) = (d >> 24) & 0xff; } void testBinner() { // Like above, we allocate/lock/map some videocore memory // I'm just shoving everything in a single buffer because I'm lazy // 8Mb, 4k alignment unsigned int handle = mem_alloc(mbox, 0x800000, 0x1000, MEM_FLAG_COHERENT | MEM_FLAG_ZERO); if (!handle) { printf("Error: Unable to allocate memory"); return; } uint32_t bus_addr = mem_lock(mbox, handle); uint8_t *list = (uint8_t*) mapmem(bus_addr, 0x800000); uint8_t *p = list; // Configuration stuff // Tile Binning Configuration. // Tile state data is 48 bytes per tile, I think it can be thrown away // as soon as binning is finished. addbyte(&p, 112); addword(&p, bus_addr + 0x6200); // tile allocation memory address addword(&p, 0x8000); // tile allocation memory size addword(&p, bus_addr + 0x100); // Tile state data address addbyte(&p, 30); // 1920/64 addbyte(&p, 17); // 1080/64 (16.875) addbyte(&p, 0x04); // config // Start tile binning. addbyte(&p, 6); // Primitive type addbyte(&p, 56); addbyte(&p, 0x32); // 16 bit triangle // Clip Window addbyte(&p, 102); addshort(&p, 0); addshort(&p, 0); addshort(&p, 1920); // width addshort(&p, 1080); // height // State addbyte(&p, 96); addbyte(&p, 0x03); // enable both foward and back facing polygons addbyte(&p, 0x00); // depth testing disabled addbyte(&p, 0x02); // enable early depth write // Viewport offset addbyte(&p, 103); addshort(&p, 0); addshort(&p, 0); // The triangle // No Vertex Shader state (takes pre-transformed vertexes, // so we don't have to supply a working coordinate shader to test the binner. addbyte(&p, 65); addword(&p, bus_addr + 0x80); // Shader Record // primitive index list addbyte(&p, 32); addbyte(&p, 0x04); // 8bit index, trinagles addword(&p, 3); // Length addword(&p, bus_addr + 0x70); // address addword(&p, 2); // Maximum index // End of bin list // Flush addbyte(&p, 5); // Nop addbyte(&p, 1); // Halt addbyte(&p, 0); int length = p - list; assert(length < 0x80); // Shader Record p = list + 0x80; addbyte(&p, 0x01); // flags addbyte(&p, 6*4); // stride addbyte(&p, 0xcc); // num uniforms (not used) addbyte(&p, 0); // num varyings addword(&p, bus_addr + 0xfe00); // Fragment shader code addword(&p, bus_addr + 0xff00); // Fragment shader uniforms addword(&p, bus_addr + 0xa0); // Vertex Data // Vertex Data p = list + 0xa0; // Vertex: Top, red addshort(&p, (1920/2) << 4); // X in 12.4 fixed point addshort(&p, 200 << 4); // Y in 12.4 fixed point addfloat(&p, 1.0f); // Z addfloat(&p, 1.0f); // 1/W addfloat(&p, 1.0f); // Varying 0 (Red) addfloat(&p, 0.0f); // Varying 1 (Green) addfloat(&p, 0.0f); // Varying 2 (Blue) // Vertex: bottom left, Green addshort(&p, 560 << 4); // X in 12.4 fixed point addshort(&p, 800 << 4); // Y in 12.4 fixed point addfloat(&p, 1.0f); // Z addfloat(&p, 1.0f); // 1/W addfloat(&p, 0.0f); // Varying 0 (Red) addfloat(&p, 1.0f); // Varying 1 (Green) addfloat(&p, 0.0f); // Varying 2 (Blue) // Vertex: bottom right, Blue addshort(&p, 1460 << 4); // X in 12.4 fixed point addshort(&p, 800 << 4); // Y in 12.4 fixed point addfloat(&p, 1.0f); // Z addfloat(&p, 1.0f); // 1/W addfloat(&p, 0.0f); // Varying 0 (Red) addfloat(&p, 0.0f); // Varying 1 (Green) addfloat(&p, 1.0f); // Varying 2 (Blue) // Vertex list p = list + 0x70; addbyte(&p, 0); // top addbyte(&p, 1); // bottom left addbyte(&p, 2); // bottom right // fragment shader p = list + 0xfe00; addword(&p, 0xffffffff); addword(&p, 0xe0020ba7); /* ldi tlbc, 0xffffffff */ addword(&p, 0x009e7000); addword(&p, 0x500009e7); /* nop; nop; sbdone */ addword(&p, 0x009e7000); addword(&p, 0x300009e7); /* nop; nop; thrend */ addword(&p, 0x009e7000); addword(&p, 0x100009e7); /* nop; nop; nop */ addword(&p, 0x009e7000); addword(&p, 0x100009e7); /* nop; nop; nop */ // Render control list p = list + 0xe200; // Clear color addbyte(&p, 114); addword(&p, 0); addword(&p, 0); addword(&p, 0); addbyte(&p, 0); // Tile Rendering Mode Configuration addbyte(&p, 113); addword(&p, bus_addr + 0x10000); // framebuffer addresss addshort(&p, 1920); // width addshort(&p, 1080); // height addbyte(&p, 0x04); // framebuffer mode (linear rgba8888) addbyte(&p, 0x00); // Link all binned lists together for(int x = 0; x < 30; x++) { for(int y = 0; y < 17; y++) { // Tile Coordinates addbyte(&p, 115); addbyte(&p, x); addbyte(&p, y); // Call Tile sublist addbyte(&p, 17); addword(&p, bus_addr + 0x6200 + (y * 30 + x) * 32); // Last tile needs a special store instruction if(x == 29 && y == 16) { // Store resolved tile color buffer and signal end of frame addbyte(&p, 25); } else { // Store resolved tile color buffer addbyte(&p, 24); } } } int render_length = p - (list + 0xe200); // Run our control list printf("Binner control list constructed\n"); printf("Start Address: 0x%08x, length: 0x%x\n", bus_addr, length); v3d[V3D_CT0CA] = bus_addr; v3d[V3D_CT0EA] = bus_addr + length; printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); // Wait for control list to execute while(v3d[V3D_CT0CS] & 0x20); printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); printf("V3D_CT1CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT1CS], v3d[V3D_CT1CA]); v3d[V3D_CT1CA] = bus_addr + 0xe200; v3d[V3D_CT1EA] = bus_addr + 0xe200 + render_length; sleep(1); //while(v3d[V3D_CT1CS] & 0x20); printf("V3D_CT1CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT1CS], v3d[V3D_CT1CA]); v3d[V3D_CT1CS] = 0x20; // just dump the buffer to a file FILE *f = fopen("binner_dump.bin", "w"); for(int i = 0; i < 0x800000; i++) { fputc(list[i], f); } fclose(f); printf("Buffer containing binned tile lists dumpped to binner_dump.bin\n"); // Release resources unmapmem((void *) list, 0x800000); mem_unlock(mbox, handle); mem_free(mbox, handle); } int main(int argc, char **argv) { mbox = mbox_open(); // The blob now has this nice handy call which powers up the v3d pipeline. qpu_enable(mbox, 1); // map v3d's registers into our address space. v3d = (unsigned *) mapmem(0x20c00000, 0x1000); if(v3d[V3D_IDENT0] != 0x02443356) { // Magic number. printf("Error: V3D pipeline isn't powered up and accessable.\n"); exit(-1); } // We now have access to the v3d registers, we should do something. testBinner(); return 0; } <commit_msg>Clear the tile buffer at the start of rendering.<commit_after>#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <stdint.h> #include <assert.h> #include "mailbox.h" #include "v3d.h" // I/O access volatile unsigned *v3d; int mbox; // Execute a nop control list to prove that we have contol. void testControlLists() { // First we allocate and map some videocore memory to build our control list in. // ask the blob to allocate us 256 bytes with 4k alignment, zero it. unsigned int handle = mem_alloc(mbox, 0x100, 0x1000, MEM_FLAG_COHERENT | MEM_FLAG_ZERO); if (!handle) { printf("Error: Unable to allocate memory"); return; } // ask the blob to lock our memory at a single location at give is that address. uint32_t bus_addr = mem_lock(mbox, handle); // map that address into our local address space. uint8_t *list = (uint8_t*) mapmem(bus_addr, 0x100); // Now we construct our control list. // 255 nops, with a halt somewhere in the middle for(int i = 0; i < 0xff; i++) { list[i] = 1; // NOP } list[0xbb] = 0; // Halt. // And then we setup the v3d pipeline to execute the control list. printf("V3D_CT0CS: 0x%08x\n", v3d[V3D_CT0CS]); printf("Start Address: 0x%08x\n", bus_addr); // Current Address = start of our list (bus address) v3d[V3D_CT0CA] = bus_addr; // End Address = just after the end of our list (bus address) // This also starts execution. v3d[V3D_CT0EA] = bus_addr + 0x100; // print status while running printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); // Wait a second to be sure the contorl list execution has finished while(v3d[V3D_CT0CS] & 0x20); // print the status again. printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); // Release memory; unmapmem((void *) list, 0x100); mem_unlock(mbox, handle); mem_free(mbox, handle); } void addbyte(uint8_t **list, uint8_t d) { *((*list)++) = d; } void addshort(uint8_t **list, uint16_t d) { *((*list)++) = (d) & 0xff; *((*list)++) = (d >> 8) & 0xff; } void addword(uint8_t **list, uint32_t d) { *((*list)++) = (d) & 0xff; *((*list)++) = (d >> 8) & 0xff; *((*list)++) = (d >> 16) & 0xff; *((*list)++) = (d >> 24) & 0xff; } void addfloat(uint8_t **list, float f) { uint32_t d = *((uint32_t *)&f); *((*list)++) = (d) & 0xff; *((*list)++) = (d >> 8) & 0xff; *((*list)++) = (d >> 16) & 0xff; *((*list)++) = (d >> 24) & 0xff; } void testBinner() { // Like above, we allocate/lock/map some videocore memory // I'm just shoving everything in a single buffer because I'm lazy // 8Mb, 4k alignment unsigned int handle = mem_alloc(mbox, 0x800000, 0x1000, MEM_FLAG_COHERENT | MEM_FLAG_ZERO); if (!handle) { printf("Error: Unable to allocate memory"); return; } uint32_t bus_addr = mem_lock(mbox, handle); uint8_t *list = (uint8_t*) mapmem(bus_addr, 0x800000); uint8_t *p = list; // Configuration stuff // Tile Binning Configuration. // Tile state data is 48 bytes per tile, I think it can be thrown away // as soon as binning is finished. addbyte(&p, 112); addword(&p, bus_addr + 0x6200); // tile allocation memory address addword(&p, 0x8000); // tile allocation memory size addword(&p, bus_addr + 0x100); // Tile state data address addbyte(&p, 30); // 1920/64 addbyte(&p, 17); // 1080/64 (16.875) addbyte(&p, 0x04); // config // Start tile binning. addbyte(&p, 6); // Primitive type addbyte(&p, 56); addbyte(&p, 0x32); // 16 bit triangle // Clip Window addbyte(&p, 102); addshort(&p, 0); addshort(&p, 0); addshort(&p, 1920); // width addshort(&p, 1080); // height // State addbyte(&p, 96); addbyte(&p, 0x03); // enable both foward and back facing polygons addbyte(&p, 0x00); // depth testing disabled addbyte(&p, 0x02); // enable early depth write // Viewport offset addbyte(&p, 103); addshort(&p, 0); addshort(&p, 0); // The triangle // No Vertex Shader state (takes pre-transformed vertexes, // so we don't have to supply a working coordinate shader to test the binner. addbyte(&p, 65); addword(&p, bus_addr + 0x80); // Shader Record // primitive index list addbyte(&p, 32); addbyte(&p, 0x04); // 8bit index, trinagles addword(&p, 3); // Length addword(&p, bus_addr + 0x70); // address addword(&p, 2); // Maximum index // End of bin list // Flush addbyte(&p, 5); // Nop addbyte(&p, 1); // Halt addbyte(&p, 0); int length = p - list; assert(length < 0x80); // Shader Record p = list + 0x80; addbyte(&p, 0x01); // flags addbyte(&p, 6*4); // stride addbyte(&p, 0xcc); // num uniforms (not used) addbyte(&p, 0); // num varyings addword(&p, bus_addr + 0xfe00); // Fragment shader code addword(&p, bus_addr + 0xff00); // Fragment shader uniforms addword(&p, bus_addr + 0xa0); // Vertex Data // Vertex Data p = list + 0xa0; // Vertex: Top, red addshort(&p, (1920/2) << 4); // X in 12.4 fixed point addshort(&p, 200 << 4); // Y in 12.4 fixed point addfloat(&p, 1.0f); // Z addfloat(&p, 1.0f); // 1/W addfloat(&p, 1.0f); // Varying 0 (Red) addfloat(&p, 0.0f); // Varying 1 (Green) addfloat(&p, 0.0f); // Varying 2 (Blue) // Vertex: bottom left, Green addshort(&p, 560 << 4); // X in 12.4 fixed point addshort(&p, 800 << 4); // Y in 12.4 fixed point addfloat(&p, 1.0f); // Z addfloat(&p, 1.0f); // 1/W addfloat(&p, 0.0f); // Varying 0 (Red) addfloat(&p, 1.0f); // Varying 1 (Green) addfloat(&p, 0.0f); // Varying 2 (Blue) // Vertex: bottom right, Blue addshort(&p, 1460 << 4); // X in 12.4 fixed point addshort(&p, 800 << 4); // Y in 12.4 fixed point addfloat(&p, 1.0f); // Z addfloat(&p, 1.0f); // 1/W addfloat(&p, 0.0f); // Varying 0 (Red) addfloat(&p, 0.0f); // Varying 1 (Green) addfloat(&p, 1.0f); // Varying 2 (Blue) // Vertex list p = list + 0x70; addbyte(&p, 0); // top addbyte(&p, 1); // bottom left addbyte(&p, 2); // bottom right // fragment shader p = list + 0xfe00; addword(&p, 0xffffffff); addword(&p, 0xe0020ba7); /* ldi tlbc, 0xffffffff */ addword(&p, 0x009e7000); addword(&p, 0x500009e7); /* nop; nop; sbdone */ addword(&p, 0x009e7000); addword(&p, 0x300009e7); /* nop; nop; thrend */ addword(&p, 0x009e7000); addword(&p, 0x100009e7); /* nop; nop; nop */ addword(&p, 0x009e7000); addword(&p, 0x100009e7); /* nop; nop; nop */ // Render control list p = list + 0xe200; // Clear color addbyte(&p, 114); addword(&p, 0); addword(&p, 0); addword(&p, 0); addbyte(&p, 0); // Tile Rendering Mode Configuration addbyte(&p, 113); addword(&p, bus_addr + 0x10000); // framebuffer addresss addshort(&p, 1920); // width addshort(&p, 1080); // height addbyte(&p, 0x04); // framebuffer mode (linear rgba8888) addbyte(&p, 0x00); // Do a store of the first tile to force the tile buffer to be cleared // Tile Coordinates addbyte(&p, 115); addbyte(&p, 0); addbyte(&p, 0); // Store Tile Buffer General addbyte(&p, 28); addshort(&p, 0); // Store nothing (just clear) addword(&p, 0); // no address is needed // Link all binned lists together for(int x = 0; x < 30; x++) { for(int y = 0; y < 17; y++) { // Tile Coordinates addbyte(&p, 115); addbyte(&p, x); addbyte(&p, y); // Call Tile sublist addbyte(&p, 17); addword(&p, bus_addr + 0x6200 + (y * 30 + x) * 32); // Last tile needs a special store instruction if(x == 29 && y == 16) { // Store resolved tile color buffer and signal end of frame addbyte(&p, 25); } else { // Store resolved tile color buffer addbyte(&p, 24); } } } int render_length = p - (list + 0xe200); // Run our control list printf("Binner control list constructed\n"); printf("Start Address: 0x%08x, length: 0x%x\n", bus_addr, length); v3d[V3D_CT0CA] = bus_addr; v3d[V3D_CT0EA] = bus_addr + length; printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); // Wait for control list to execute while(v3d[V3D_CT0CS] & 0x20); printf("V3D_CT0CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT0CS], v3d[V3D_CT0CA]); printf("V3D_CT1CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT1CS], v3d[V3D_CT1CA]); v3d[V3D_CT1CA] = bus_addr + 0xe200; v3d[V3D_CT1EA] = bus_addr + 0xe200 + render_length; sleep(1); //while(v3d[V3D_CT1CS] & 0x20); printf("V3D_CT1CS: 0x%08x, Address: 0x%08x\n", v3d[V3D_CT1CS], v3d[V3D_CT1CA]); v3d[V3D_CT1CS] = 0x20; // just dump the buffer to a file FILE *f = fopen("binner_dump.bin", "w"); for(int i = 0; i < 0x800000; i++) { fputc(list[i], f); } fclose(f); printf("Buffer containing binned tile lists dumpped to binner_dump.bin\n"); // Release resources unmapmem((void *) list, 0x800000); mem_unlock(mbox, handle); mem_free(mbox, handle); } int main(int argc, char **argv) { mbox = mbox_open(); // The blob now has this nice handy call which powers up the v3d pipeline. qpu_enable(mbox, 1); // map v3d's registers into our address space. v3d = (unsigned *) mapmem(0x20c00000, 0x1000); if(v3d[V3D_IDENT0] != 0x02443356) { // Magic number. printf("Error: V3D pipeline isn't powered up and accessable.\n"); exit(-1); } // We now have access to the v3d registers, we should do something. testBinner(); return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #define CATCH_CONFIG_MAIN #include "Catch.hpp" #include "hck_engine.h" static bool shutdown = true; extern bool running; void hck_log(int level, const char *fmt, ...){ va_list args; va_start(args, fmt); vprintf(errbuf, fmt, args); va_end(args); puts(""); } static void start_engine(){ if (fork() == 0){ zbx_setproctitle("zabbix_proxy: http check keepalive #1"); shutdown = false; processing_thread(); shutdown = true; exit(1); } } TEST_CASE( "IPv4 Test to Online Host" ) { start_engine(); int fd = connect_to_hck(); unsigned short result = execute_check(fd, "216.58.194.174","80"); REQUIRE( result == 1 ); close(fd); running = false; while(!shutdown){ sleep(1); } } TEST_CASE( "IPv4 Test to Offline Host" ) { start_engine(); int fd = connect_to_hck(); unsigned short result = execute_check(fd, "127.123.123.123","14"); REQUIRE( result == 0 ); close(fd); running = false; while(!shutdown){ sleep(1); } }<commit_msg>missing refs<commit_after>#include <stdio.h> #include <stdarg.h> #define CATCH_CONFIG_MAIN #include "Catch.hpp" #include "hck_engine.h" static bool shutdown = true; extern bool running; void hck_log(int level, const char *fmt, ...){ va_list args; va_start(args, fmt); vprintf(errbuf, fmt, args); va_end(args); puts(""); } static void start_engine(){ if (fork() == 0){ zbx_setproctitle("zabbix_proxy: http check keepalive #1"); shutdown = false; processing_thread(); shutdown = true; exit(1); } } TEST_CASE( "IPv4 Test to Online Host" ) { start_engine(); int fd = connect_to_hck(); unsigned short result = execute_check(fd, "216.58.194.174","80"); REQUIRE( result == 1 ); close(fd); running = false; while(!shutdown){ sleep(1); } } TEST_CASE( "IPv4 Test to Offline Host" ) { start_engine(); int fd = connect_to_hck(); unsigned short result = execute_check(fd, "127.123.123.123","14"); REQUIRE( result == 0 ); close(fd); running = false; while(!shutdown){ sleep(1); } }<|endoftext|>
<commit_before>#include "Command.h" //clang++ -std=c++11 test.cpp int main(int argc, char *argv[]) { std::string testString( "test { a , b , c , [foo : 1, bar : 2 ] }" ); std::cout << "VVVVVVVVV" << std::endl; std::cout << "running tests on Command with init string:" << std::endl << "\t" << testString << std::endl; Command testCmd( testString ); std::cout <<"Reseralizes as " << testCmd.text() << std::endl; std::cout << "Testing type()" << std::endl; if( testCmd.type() == "test" ) std::cout<<"\tsuccess!" << std::endl; else std::cout << "\tfail :(" << std::endl; std::cout << "Testing getValueAt(\"0\")" << std::endl; if( testCmd.getValueAt<std::string>("0") == "a" ) std::cout<<"\tsuccess!" << std::endl; else{ std::cout << "\tfail :(" << std::endl; std::cout << "getValueAt<std::string>(\"0\") returns \"" << testCmd.getValueAt<std::string>("0") << "\"" << std::endl; } std::cout << "Testing getValueAt(\"1\")" << std::endl; if( testCmd.getValueAt<std::string>("1") == "b" ) std::cout<<"\tsuccess!" << std::endl; else{ std::cout << "\tfail :(" << std::endl; std::cout << "getValueAt<std::string>(\"1\") returns \"" << testCmd.getValueAt<std::string>("1") << "\"" << std::endl; } std::cout << "Testing getValueAt(\"3/foo\")" << std::endl; if( testCmd.getValueAt<std::string>("3/foo") == "1" ) std::cout<<"\tsuccess!" << std::endl; else{ std::cout << "\tfail :(" << std::endl; std::cout << "getValueAt<std::string>(\"3/foo\") returns \"" << testCmd.getValueAt<std::string>("3/foo") << "\"" << std::endl; } std::cout << "Testing getValueAt(\"3/bar\")" << std::endl; if( testCmd.getValueAt<std::string>("3/bar") == "2" ) std::cout<<"\tsuccess!" << std::endl; else{ std::cout << "\tfail :(" << std::endl; std::cout << "getValueAt<std::string>(\"3/bar\") returns \"" << testCmd.getValueAt<std::string>("3/bar") << "\"" << std::endl; } return 0; } <commit_msg>Wrote a macro to do unit tests.<commit_after>#include "Command.h" //clang++ -std=c++11 test.cpp #define TEST( name, exp, result ) {\ std::cout << "Testing " << name << std::endl;\ if( exp == result )\ std::cout << "\tsuccess!" << std::endl; \ else{ \ std::cout << #exp << " returns " << exp << std::endl; \ } \ } int main(int argc, char *argv[]) { std::string testString( "test { a , b , c , [foo : 1, bar : 2 ] }" ); std::cout << "running tests on Command with init string:" << std::endl << "\t" << testString << std::endl; Command testCmd( testString ); std::cout <<"Reseralizes as " << testCmd.text() << std::endl; TEST( "type", testCmd.type(), "test" ); TEST( "get value at 1", testCmd.getValueAt<std::string>("1"), "b" ); TEST( "get value at 3/foo", testCmd.getValueAt<std::string>("3/foo"), "1" ); TEST( "get value at 3/bar", testCmd.getValueAt<std::string>("3/bar"), "2" ); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <algorithm> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE TimSortTest #include <boost/test/unit_test.hpp> #include "timsort.hpp" BOOST_AUTO_TEST_CASE( simple10 ) { std::vector<int> a; a.push_back(60); a.push_back(50); a.push_back( 1); a.push_back(40); a.push_back(80); a.push_back(20); a.push_back(30); a.push_back(70); a.push_back(10); a.push_back(90); timsort(a.begin(), a.end(), std::less<int>()); BOOST_CHECK_EQUAL( a[0], 1 ); BOOST_CHECK_EQUAL( a[1], 10 ); BOOST_CHECK_EQUAL( a[2], 20 ); BOOST_CHECK_EQUAL( a[3], 30 ); BOOST_CHECK_EQUAL( a[4], 40 ); BOOST_CHECK_EQUAL( a[5], 50 ); BOOST_CHECK_EQUAL( a[6], 60 ); BOOST_CHECK_EQUAL( a[7], 70 ); BOOST_CHECK_EQUAL( a[8], 80 ); BOOST_CHECK_EQUAL( a[9], 90 ); std::reverse(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); BOOST_CHECK_EQUAL( a[0], 1 ); BOOST_CHECK_EQUAL( a[1], 10 ); BOOST_CHECK_EQUAL( a[2], 20 ); BOOST_CHECK_EQUAL( a[3], 30 ); BOOST_CHECK_EQUAL( a[4], 40 ); BOOST_CHECK_EQUAL( a[5], 50 ); BOOST_CHECK_EQUAL( a[6], 60 ); BOOST_CHECK_EQUAL( a[7], 70 ); BOOST_CHECK_EQUAL( a[8], 80 ); BOOST_CHECK_EQUAL( a[9], 90 ); } BOOST_AUTO_TEST_CASE( shuffle30 ) { const int size = 30; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } BOOST_AUTO_TEST_CASE( shuffle31 ) { const int size = 31; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } BOOST_AUTO_TEST_CASE( shuffle32 ) { const int size = 32; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } BOOST_AUTO_TEST_CASE( shuffle128 ) { const int size = 128; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } BOOST_AUTO_TEST_CASE( shuffle1024 ) { const int size = 1024; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } for(int n = 0; n < 100; ++n) { std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } } BOOST_AUTO_TEST_CASE( c_array ) { int a[] = { 7, 1, 5, 3, 9 }; timsort(a, a + sizeof(a) / sizeof(int), std::less<int>()); BOOST_CHECK_EQUAL(a[0], 1); BOOST_CHECK_EQUAL(a[1], 3); BOOST_CHECK_EQUAL(a[2], 5); BOOST_CHECK_EQUAL(a[3], 7); BOOST_CHECK_EQUAL(a[4], 9); } <commit_msg>Add stability test<commit_after>#include <iostream> #include <vector> #include <algorithm> #include <utility> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE TimSortTest #include <boost/test/unit_test.hpp> #include "timsort.hpp" BOOST_AUTO_TEST_CASE( simple10 ) { std::vector<int> a; a.push_back(60); a.push_back(50); a.push_back( 1); a.push_back(40); a.push_back(80); a.push_back(20); a.push_back(30); a.push_back(70); a.push_back(10); a.push_back(90); timsort(a.begin(), a.end(), std::less<int>()); BOOST_CHECK_EQUAL( a[0], 1 ); BOOST_CHECK_EQUAL( a[1], 10 ); BOOST_CHECK_EQUAL( a[2], 20 ); BOOST_CHECK_EQUAL( a[3], 30 ); BOOST_CHECK_EQUAL( a[4], 40 ); BOOST_CHECK_EQUAL( a[5], 50 ); BOOST_CHECK_EQUAL( a[6], 60 ); BOOST_CHECK_EQUAL( a[7], 70 ); BOOST_CHECK_EQUAL( a[8], 80 ); BOOST_CHECK_EQUAL( a[9], 90 ); std::reverse(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); BOOST_CHECK_EQUAL( a[0], 1 ); BOOST_CHECK_EQUAL( a[1], 10 ); BOOST_CHECK_EQUAL( a[2], 20 ); BOOST_CHECK_EQUAL( a[3], 30 ); BOOST_CHECK_EQUAL( a[4], 40 ); BOOST_CHECK_EQUAL( a[5], 50 ); BOOST_CHECK_EQUAL( a[6], 60 ); BOOST_CHECK_EQUAL( a[7], 70 ); BOOST_CHECK_EQUAL( a[8], 80 ); BOOST_CHECK_EQUAL( a[9], 90 ); } BOOST_AUTO_TEST_CASE( shuffle30 ) { const int size = 30; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } BOOST_AUTO_TEST_CASE( shuffle31 ) { const int size = 31; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } BOOST_AUTO_TEST_CASE( shuffle32 ) { const int size = 32; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } BOOST_AUTO_TEST_CASE( shuffle128 ) { const int size = 128; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } BOOST_AUTO_TEST_CASE( shuffle1024 ) { const int size = 1024; std::vector<int> a; for(int i = 0; i < size; ++i) { a.push_back((i+1) * 10); } for(int n = 0; n < 100; ++n) { std::random_shuffle(a.begin(), a.end()); timsort(a.begin(), a.end(), std::less<int>()); for(int i = 0; i < size; ++i) { BOOST_CHECK_EQUAL( a[i], (i+1) * 10 ); } } } BOOST_AUTO_TEST_CASE( c_array ) { int a[] = { 7, 1, 5, 3, 9 }; timsort(a, a + sizeof(a) / sizeof(int), std::less<int>()); BOOST_CHECK_EQUAL(a[0], 1); BOOST_CHECK_EQUAL(a[1], 3); BOOST_CHECK_EQUAL(a[2], 5); BOOST_CHECK_EQUAL(a[3], 7); BOOST_CHECK_EQUAL(a[4], 9); } enum id { foo, bar, baz }; typedef std::pair<int, id> pair_t; bool less_in_first(pair_t x, pair_t y) { return x.first < y.first; } BOOST_AUTO_TEST_CASE( stability ) { std::vector< pair_t > a; for(int i = 100; i >= 0; --i) { a.push_back( std::make_pair(i, foo) ); a.push_back( std::make_pair(i, bar) ); a.push_back( std::make_pair(i, baz) ); } timsort(a.begin(), a.end(), &less_in_first); BOOST_CHECK_EQUAL(a[0].first, 0); BOOST_CHECK_EQUAL(a[0].second, foo); BOOST_CHECK_EQUAL(a[1].first, 0); BOOST_CHECK_EQUAL(a[1].second, bar); BOOST_CHECK_EQUAL(a[2].first, 0); BOOST_CHECK_EQUAL(a[2].second, baz); BOOST_CHECK_EQUAL(a[3].first, 1); BOOST_CHECK_EQUAL(a[3].second, foo); BOOST_CHECK_EQUAL(a[4].first, 1); BOOST_CHECK_EQUAL(a[4].second, bar); BOOST_CHECK_EQUAL(a[5].first, 1); BOOST_CHECK_EQUAL(a[5].second, baz); BOOST_CHECK_EQUAL(a[6].first, 2); BOOST_CHECK_EQUAL(a[6].second, foo); BOOST_CHECK_EQUAL(a[7].first, 2); BOOST_CHECK_EQUAL(a[7].second, bar); BOOST_CHECK_EQUAL(a[8].first, 2); BOOST_CHECK_EQUAL(a[8].second, baz); BOOST_CHECK_EQUAL(a[9].first, 3); BOOST_CHECK_EQUAL(a[9].second, foo); BOOST_CHECK_EQUAL(a[10].first, 3); BOOST_CHECK_EQUAL(a[10].second, bar); BOOST_CHECK_EQUAL(a[11].first, 3); BOOST_CHECK_EQUAL(a[11].second, baz); } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include "totient.hpp" #include "test_extras.hpp" class Test { public: static bool passed; static void eval(bool (Test::*test)(bool), Test &testClass, std::string name, bool verbose); bool numeric(mpz_class x, mpz_class y, int n = 50, bool verbose = true); bool range(bool verbose); bool largeNumber(bool verbose); }; bool Test::passed = true; void Test::eval(bool (Test::*test)(bool), Test &testClass, std::string name, bool verbose) { if ((testClass.*test)(verbose)) { std::cout << color::green << name << " Test OK\n"; } else { Test::passed = false; std::cout << color::red << name << " Test Failed\n"; } } bool Test::numeric(mpz_class x, mpz_class y, int n, bool verbose) { mpz_class phi_res; bool res = true; for (int z = 1; z <= n; z++) { phi_res = phi(x); res = (phi_res == y); } if (verbose) { if (res) { std::cout << color::green << "----phi(" << x.get_str(10) << ") = " << phi_res.get_str(10) << "\n"; } else { std::cout << color::red << "----phi(" << x.get_str(10) << ") = " << phi_res.get_str(10) << "\n"; } } return res; } bool Test::range(bool verbose) { bool passed = true; io::CSVReader<2> in("phi_results.csv"); in.read_header(io::ignore_extra_column, "n", "phi"); int n; int phi; while (in.read_row(n, phi)) { if (Test::numeric(n, phi, 10, verbose)) { } else { passed = false; } } return passed; } bool Test::largeNumber(bool verbose) { bool passed = true; std::array<std::pair<mpz_class, mpz_class>, 3> pairs = {{ {mpz_class("985763284578345834"), mpz_class("298498582277498400")}, {mpz_class("98576328457834581423412342334"), mpz_class("45827308937045311626868162560")}, {mpz_class("958324857389475983274569823476558973245"), mpz_class( "644667608743795154660944983332241662208")} }}; for (const auto &v: pairs) { // XXX: Better way to do this? if (Test::numeric(v.first, v.second, 1, verbose)) { } else { passed = false; } } return passed; } int main(int argc, char* argv[]) { int opt; opterr = 0; bool verbose = false; while ((opt = getopt(argc, argv, "hvt:")) != -1) { switch (opt) { case 'v': verbose = true; break; case 't': Test tClass; switch (optarg[0]) { case 'r': Test::eval(&Test::range, tClass, "Range", verbose); break; case 'l': Test::eval(&Test::largeNumber, tClass, "Large Number", verbose); break; default: Test::eval(&Test::range, tClass, "Range", verbose); Test::eval(&Test::largeNumber, tClass, "Large Number", verbose); break; } break; case 'h': std::cout << "No option specified" << "\n" << "-v : Enables verbose" << "\n" << "-t arg: Performs test" << "\n" << " a : All tests" << "\n" << " r : Range test" << "\n" << " l : Large number test" << "\n"; break; case '?': default: std::cerr << "Unknown option '" << char(opt) << "'\n"; break; } } return Test::passed; }<commit_msg>Replaced auto for explitic typing<commit_after>#include <iostream> #include <unistd.h> #include "totient.hpp" #include "test_extras.hpp" class Test { public: static bool passed; static void eval(bool (Test::*test)(bool), Test &testClass, std::string name, bool verbose); bool numeric(mpz_class x, mpz_class y, int n = 50, bool verbose = true); bool range(bool verbose); bool largeNumber(bool verbose); }; bool Test::passed = true; void Test::eval(bool (Test::*test)(bool), Test &testClass, std::string name, bool verbose) { if ((testClass.*test)(verbose)) { std::cout << color::green << name << " Test OK\n"; } else { Test::passed = false; std::cout << color::red << name << " Test Failed\n"; } } bool Test::numeric(mpz_class x, mpz_class y, int n, bool verbose) { mpz_class phi_res; bool res = true; for (int z = 1; z <= n; z++) { phi_res = phi(x); res = (phi_res == y); } if (verbose) { if (res) { std::cout << color::green << "----phi(" << x.get_str(10) << ") = " << phi_res.get_str(10) << "\n"; } else { std::cout << color::red << "----phi(" << x.get_str(10) << ") = " << phi_res.get_str(10) << "\n"; } } return res; } bool Test::range(bool verbose) { bool passed = true; io::CSVReader<2> in("phi_results.csv"); in.read_header(io::ignore_extra_column, "n", "phi"); int n; int phi; while (in.read_row(n, phi)) { if (Test::numeric(n, phi, 10, verbose)) { } else { passed = false; } } return passed; } bool Test::largeNumber(bool verbose) { bool passed = true; std::array<std::pair<mpz_class, mpz_class>, 3> pairs = {{ {mpz_class("985763284578345834"), mpz_class("298498582277498400")}, {mpz_class("98576328457834581423412342334"), mpz_class("45827308937045311626868162560")}, {mpz_class("958324857389475983274569823476558973245"), mpz_class( "644667608743795154660944983332241662208")} }}; for (const std::pair<mpz_class, mpz_class> &v: pairs) { // XXX: Better way to do this? if (Test::numeric(v.first, v.second, 1, verbose)) { } else { passed = false; } } return passed; } int main(int argc, char* argv[]) { int opt; opterr = 0; bool verbose = false; while ((opt = getopt(argc, argv, "hvt:")) != -1) { switch (opt) { case 'v': verbose = true; break; case 't': Test tClass; switch (optarg[0]) { case 'r': Test::eval(&Test::range, tClass, "Range", verbose); break; case 'l': Test::eval(&Test::largeNumber, tClass, "Large Number", verbose); break; default: Test::eval(&Test::range, tClass, "Range", verbose); Test::eval(&Test::largeNumber, tClass, "Large Number", verbose); break; } break; case 'h': std::cout << "No option specified" << "\n" << "-v : Enables verbose" << "\n" << "-t arg: Performs test" << "\n" << " a : All tests" << "\n" << " r : Range test" << "\n" << " l : Large number test" << "\n"; break; case '?': default: std::cerr << "Unknown option '" << char(opt) << "'\n"; break; } } return Test::passed; } <|endoftext|>
<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #include "test.hpp" #include <luabind/luabind.hpp> #include <luabind/detail/debug.hpp> #include <luabind/operator.hpp> #include <utility> using namespace luabind; struct test_param : counted_type<test_param>, wrap_base { luabind::object obj; luabind::object obj2; bool operator==(test_param const& rhs) const { return obj == rhs.obj && obj2 == rhs.obj2; } }; COUNTER_GUARD(test_param); static test_param * s_ptr = NULL; void store_ptr(test_param * ptr) { s_ptr = ptr; } test_param * get_ptr() { return s_ptr; } void test_main(lua_State* L) { using namespace luabind; module(L) [ class_<test_param>("test_param") .def(constructor<>()) .def_readwrite("obj", &test_param::obj) .def_readonly("obj2", &test_param::obj2) .def(const_self == const_self) , def("store_ptr", &store_ptr), def("get_ptr", &get_ptr) ]; test_param temp_object; globals(L)["temp"] = temp_object; object tab = newtable(L); tab[temp_object] = 1; TEST_CHECK( tab[temp_object] == 1 ); TEST_CHECK( tab[globals(L)["temp"]] == 1 ); DOSTRING(L, "local tab = {}\n" "tab[temp] = 1\n" "assert(tab[temp] == 1)"); DOSTRING(L, "t = test_param()\n" "tab = {}\n" "tab[t] = 1\n" "store_ptr(t)\n" "assert(tab[get_ptr()] == 1)"); } <commit_msg>Added: more through tests to test_object_identity<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #include "test.hpp" #include <luabind/luabind.hpp> #include <luabind/detail/debug.hpp> #include <luabind/operator.hpp> #include <utility> using namespace luabind; struct test_param : counted_type<test_param>, wrap_base { luabind::object obj; luabind::object obj2; bool operator==(test_param const& rhs) const { return obj == rhs.obj && obj2 == rhs.obj2; } }; COUNTER_GUARD(test_param); static test_param * s_ptr = NULL; void store_ptr(test_param * ptr) { s_ptr = ptr; } test_param * get_ptr() { return s_ptr; } void test_main(lua_State* L) { assert(boost::is_polymorphic<test_param>()); using namespace luabind; module(L) [ class_<test_param>("test_param") .def(constructor<>()) .def_readwrite("obj", &test_param::obj) .def_readonly("obj2", &test_param::obj2) .def(const_self == const_self) , def("store_ptr", &store_ptr), def("get_ptr", &get_ptr) ]; test_param temp_object; globals(L)["temp"] = temp_object; object tab = newtable(L); tab[temp_object] = 1; TEST_CHECK( tab[temp_object] == 1 ); TEST_CHECK( tab[globals(L)["temp"]] == 1 ); // Test lua-based value copying DOSTRING(L, "a = test_param()\n"); DOSTRING(L, "assert(a == a)\n"); DOSTRING(L, "store_ptr(a)\n" "b = get_ptr()\n"); DOSTRING(L, "assert(a == b)\n"); // Test luabind object copying luabind::object o = luabind::globals(L)["a"]; luabind::globals(L)["b"] = o; TEST_CHECK(luabind::globals(L)["b"] == luabind::globals(L)["a"]); DOSTRING(L, "assert(a == b)\n"); DOSTRING(L, "assert(rawequal(a, b))\n"); // Test luabind conversion and rewrapping-based copying test_param* tp_ptr = luabind::object_cast<test_param*>(luabind::globals(L)["a"]); luabind::globals(L)["b"] = tp_ptr; TEST_CHECK(luabind::globals(L)["b"] == luabind::globals(L)["a"]); DOSTRING(L, "assert(a == b)\n"); DOSTRING(L, "tab = {}\n" "tab[temp] = 1\n"); DOSTRING(L, "assert(rawequal(temp, temp))\n"); DOSTRING(L, "assert(tab[temp] == 1)"); DOSTRING(L, "t = test_param()\n" "tab = {}\n" "tab[t] = 1\n" "store_ptr(t)\n" "tc = get_ptr()\n"); DOSTRING(L, "assert(rawequal(t, tc))\n"); DOSTRING(L, "assert(tab[t] == 1)\n"); DOSTRING(L, "assert(tab[tc] == 1)"); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/testsupport/fileutils.h" #ifdef WIN32 #include <direct.h> #define GET_CURRENT_DIR _getcwd #else #include <unistd.h> #define GET_CURRENT_DIR getcwd #endif #include <sys/stat.h> // To check for directory existence. #ifndef S_ISDIR // Not defined in stat.h on Windows. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) #endif #include <cstdio> #include "typedefs.h" // For architecture defines namespace webrtc { namespace test { #ifdef WIN32 static const char* kPathDelimiter = "\\"; #else static const char* kPathDelimiter = "/"; #endif // The file we're looking for to identify the project root dir. static const char* kProjectRootFileName = "DEPS"; static const char* kOutputDirName = "out"; static const char* kFallbackPath = "./"; static const char* kResourcesDirName = "resources"; const char* kCannotFindProjectRootDir = "ERROR_CANNOT_FIND_PROJECT_ROOT_DIR"; std::string ProjectRootPath() { std::string working_dir = WorkingDir(); if (working_dir == kFallbackPath) { return kCannotFindProjectRootDir; } // Check for our file that verifies the root dir. std::string current_path(working_dir); FILE* file = NULL; int path_delimiter_index = current_path.find_last_of(kPathDelimiter); while (path_delimiter_index > -1) { std::string root_filename = current_path + kPathDelimiter + kProjectRootFileName; file = fopen(root_filename.c_str(), "r"); if (file != NULL) { fclose(file); return current_path + kPathDelimiter; } // Move up one directory in the directory tree. current_path = current_path.substr(0, path_delimiter_index); path_delimiter_index = current_path.find_last_of(kPathDelimiter); } // Reached the root directory. fprintf(stderr, "Cannot find project root directory!\n"); return kCannotFindProjectRootDir; } #ifdef WEBRTC_ANDROID std::string OutputPath() { // We need to touch this variable so it doesn't get flagged as unused. (void)kOutputDirName; return "/sdcard/"; } #else // WEBRTC_ANDROID std::string OutputPath() { std::string path = ProjectRootPath(); if (path == kCannotFindProjectRootDir) { return kFallbackPath; } path += kOutputDirName; if (!CreateDirectory(path)) { return kFallbackPath; } return path + kPathDelimiter; } #endif // !WEBRTC_ANDROID std::string WorkingDir() { char path_buffer[FILENAME_MAX]; if (!GET_CURRENT_DIR(path_buffer, sizeof(path_buffer))) { fprintf(stderr, "Cannot get current directory!\n"); return kFallbackPath; } else { return std::string(path_buffer); } } bool CreateDirectory(std::string directory_name) { struct stat path_info = {0}; // Check if the path exists already: if (stat(directory_name.c_str(), &path_info) == 0) { if (!S_ISDIR(path_info.st_mode)) { fprintf(stderr, "Path %s exists but is not a directory! Remove this " "file and re-run to create the directory.\n", directory_name.c_str()); return false; } } else { #ifdef WIN32 return _mkdir(directory_name.c_str()) == 0; #else return mkdir(directory_name.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0; #endif } return true; } bool FileExists(std::string file_name) { struct stat file_info = {0}; return stat(file_name.c_str(), &file_info) == 0; } std::string ResourcePath(std::string name, std::string extension) { std::string platform = "win"; #ifdef WEBRTC_LINUX platform = "linux"; #endif // WEBRTC_LINUX #ifdef WEBRTC_MAC platform = "mac"; #endif // WEBRTC_MAC #ifdef WEBRTC_ARCH_64_BITS std::string architecture = "64"; #else std::string architecture = "32"; #endif // WEBRTC_ARCH_64_BITS std::string resources_path = ProjectRootPath() + kResourcesDirName + kPathDelimiter; std::string resource_file = resources_path + name + "_" + platform + "_" + architecture + "." + extension; if (FileExists(resource_file)) { return resource_file; } // Try without architecture. resource_file = resources_path + name + "_" + platform + "." + extension; if (FileExists(resource_file)) { return resource_file; } // Try without platform. resource_file = resources_path + name + "_" + architecture + "." + extension; if (FileExists(resource_file)) { return resource_file; } // Fall back on name without architecture or platform. return resources_path + name + "." + extension; } size_t GetFileSize(std::string filename) { FILE* f = fopen(filename.c_str(), "rb"); size_t size = 0; if (f != NULL) { if (fseek(f, 0, SEEK_END) == 0) { size = ftell(f); } fclose(f); } return size; } } // namespace test } // namespace webrtc <commit_msg>Change file path to make it work on android<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/testsupport/fileutils.h" #ifdef WIN32 #include <direct.h> #define GET_CURRENT_DIR _getcwd #else #include <unistd.h> #define GET_CURRENT_DIR getcwd #endif #include <sys/stat.h> // To check for directory existence. #ifndef S_ISDIR // Not defined in stat.h on Windows. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) #endif #include <cstdio> #include "typedefs.h" // For architecture defines namespace webrtc { namespace test { #ifdef WIN32 static const char* kPathDelimiter = "\\"; #else static const char* kPathDelimiter = "/"; #endif // The file we're looking for to identify the project root dir. static const char* kProjectRootFileName = "DEPS"; static const char* kOutputDirName = "out"; static const char* kFallbackPath = "./"; #ifdef WEBRTC_ANDROID static const char* kResourcesDirName = "/sdcard/"; #else static const char* kResourcesDirName = "resources"; #endif const char* kCannotFindProjectRootDir = "ERROR_CANNOT_FIND_PROJECT_ROOT_DIR"; std::string ProjectRootPath() { std::string working_dir = WorkingDir(); if (working_dir == kFallbackPath) { return kCannotFindProjectRootDir; } // Check for our file that verifies the root dir. std::string current_path(working_dir); FILE* file = NULL; int path_delimiter_index = current_path.find_last_of(kPathDelimiter); while (path_delimiter_index > -1) { std::string root_filename = current_path + kPathDelimiter + kProjectRootFileName; file = fopen(root_filename.c_str(), "r"); if (file != NULL) { fclose(file); return current_path + kPathDelimiter; } // Move up one directory in the directory tree. current_path = current_path.substr(0, path_delimiter_index); path_delimiter_index = current_path.find_last_of(kPathDelimiter); } // Reached the root directory. fprintf(stderr, "Cannot find project root directory!\n"); return kCannotFindProjectRootDir; } #ifdef WEBRTC_ANDROID std::string OutputPath() { // We need to touch this variable so it doesn't get flagged as unused. (void)kOutputDirName; return "/sdcard/"; } #else // WEBRTC_ANDROID std::string OutputPath() { std::string path = ProjectRootPath(); if (path == kCannotFindProjectRootDir) { return kFallbackPath; } path += kOutputDirName; if (!CreateDirectory(path)) { return kFallbackPath; } return path + kPathDelimiter; } #endif // !WEBRTC_ANDROID std::string WorkingDir() { char path_buffer[FILENAME_MAX]; if (!GET_CURRENT_DIR(path_buffer, sizeof(path_buffer))) { fprintf(stderr, "Cannot get current directory!\n"); return kFallbackPath; } else { return std::string(path_buffer); } } bool CreateDirectory(std::string directory_name) { struct stat path_info = {0}; // Check if the path exists already: if (stat(directory_name.c_str(), &path_info) == 0) { if (!S_ISDIR(path_info.st_mode)) { fprintf(stderr, "Path %s exists but is not a directory! Remove this " "file and re-run to create the directory.\n", directory_name.c_str()); return false; } } else { #ifdef WIN32 return _mkdir(directory_name.c_str()) == 0; #else return mkdir(directory_name.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0; #endif } return true; } bool FileExists(std::string file_name) { struct stat file_info = {0}; return stat(file_name.c_str(), &file_info) == 0; } std::string ResourcePath(std::string name, std::string extension) { std::string platform = "win"; #ifdef WEBRTC_LINUX platform = "linux"; #endif // WEBRTC_LINUX #ifdef WEBRTC_MAC platform = "mac"; #endif // WEBRTC_MAC #ifdef WEBRTC_ARCH_64_BITS std::string architecture = "64"; #else std::string architecture = "32"; #endif // WEBRTC_ARCH_64_BITS #ifdef WEBRTC_ANDROID std::string resources_path = kResourcesDirName; #else std::string resources_path = ProjectRootPath() + kResourcesDirName + kPathDelimiter; std::string resource_file = resources_path + name + "_" + platform + "_" + architecture + "." + extension; if (FileExists(resource_file)) { return resource_file; } // Try without architecture. resource_file = resources_path + name + "_" + platform + "." + extension; if (FileExists(resource_file)) { return resource_file; } // Try without platform. resource_file = resources_path + name + "_" + architecture + "." + extension; if (FileExists(resource_file)) { return resource_file; } #endif // Fall back on name without architecture or platform. return resources_path + name + "." + extension; } size_t GetFileSize(std::string filename) { FILE* f = fopen(filename.c_str(), "rb"); size_t size = 0; if (f != NULL) { if (fseek(f, 0, SEEK_END) == 0) { size = ftell(f); } fclose(f); } return size; } } // namespace test } // namespace webrtc <|endoftext|>
<commit_before>#include "fly/types/string/string.hpp" #include "fly/types/string/string_exception.hpp" #include "fly/types/string/string_literal.hpp" #include "test/types/string_test.hpp" #include <gtest/gtest.h> //================================================================================================== TYPED_TEST(BasicStringTest, InvalidSequences) { DECLARE_ALIASES auto validate_fail = [](string_type &&test) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); EXPECT_THROW(StringClass::unescape_unicode_character(begin, end), fly::UnicodeException); }; validate_fail(FLY_STR(char_type, "")); validate_fail(FLY_STR(char_type, "f")); validate_fail(FLY_STR(char_type, "\\f")); } //================================================================================================== TYPED_TEST(BasicStringTest, Utf8CharacterConversion) { DECLARE_ALIASES auto validate_fail = [](string_type &&test) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); EXPECT_THROW(StringClass::unescape_unicode_character(begin, end), fly::UnicodeException); }; auto validate_pass = [](string_type &&test, string_type &&expected) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); string_type actual; EXPECT_NO_THROW(actual = StringClass::unescape_unicode_character(begin, end)); EXPECT_EQ(actual, expected); }; validate_fail(FLY_STR(char_type, "\\u")); validate_fail(FLY_STR(char_type, "\\u0")); validate_fail(FLY_STR(char_type, "\\u00")); validate_fail(FLY_STR(char_type, "\\u000")); validate_fail(FLY_STR(char_type, "\\u000z")); validate_pass(FLY_STR(char_type, "\\u0040"), FLY_STR(char_type, "\u0040")); validate_pass(FLY_STR(char_type, "\\u007A"), FLY_STR(char_type, "\u007A")); validate_pass(FLY_STR(char_type, "\\u007a"), FLY_STR(char_type, "\u007a")); validate_pass(FLY_STR(char_type, "\\u00c4"), FLY_STR(char_type, "\u00c4")); validate_pass(FLY_STR(char_type, "\\u00e4"), FLY_STR(char_type, "\u00e4")); validate_pass(FLY_STR(char_type, "\\u0298"), FLY_STR(char_type, "\u0298")); validate_pass(FLY_STR(char_type, "\\u0800"), FLY_STR(char_type, "\u0800")); validate_pass(FLY_STR(char_type, "\\uffff"), FLY_STR(char_type, "\uffff")); validate_fail(FLY_STR(char_type, "\\uDC00")); validate_fail(FLY_STR(char_type, "\\uDFFF")); validate_fail(FLY_STR(char_type, "\\uD800")); validate_fail(FLY_STR(char_type, "\\uDBFF")); } //================================================================================================== TYPED_TEST(BasicStringTest, Utf16CharacterConversion) { DECLARE_ALIASES auto validate_fail = [](string_type &&test) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); EXPECT_THROW(StringClass::unescape_unicode_character(begin, end), fly::UnicodeException); }; auto validate_pass = [](string_type &&test, string_type &&expected) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); string_type actual; EXPECT_NO_THROW(actual = StringClass::unescape_unicode_character(begin, end)); EXPECT_EQ(actual, expected); }; validate_fail(FLY_STR(char_type, "\\uD800\\u")); validate_fail(FLY_STR(char_type, "\\uD800\\z")); validate_fail(FLY_STR(char_type, "\\uD800\\u0")); validate_fail(FLY_STR(char_type, "\\uD800\\u00")); validate_fail(FLY_STR(char_type, "\\uD800\\u000")); validate_fail(FLY_STR(char_type, "\\uD800\\u0000")); validate_fail(FLY_STR(char_type, "\\uD800\\u000z")); validate_fail(FLY_STR(char_type, "\\uD800\\uDBFF")); validate_fail(FLY_STR(char_type, "\\uD800\\uE000")); validate_fail(FLY_STR(char_type, "\\uD800\\uFFFF")); validate_pass(FLY_STR(char_type, "\\uD800\\uDC00"), FLY_STR(char_type, "\U00010000")); validate_pass(FLY_STR(char_type, "\\uD803\\uDE6D"), FLY_STR(char_type, "\U00010E6D")); validate_pass(FLY_STR(char_type, "\\uD834\\uDD1E"), FLY_STR(char_type, "\U0001D11E")); validate_pass(FLY_STR(char_type, "\\uDBFF\\uDFFF"), FLY_STR(char_type, "\U0010FFFF")); } //================================================================================================== TYPED_TEST(BasicStringTest, Utf32CharacterConversion) { DECLARE_ALIASES auto validate_fail = [](string_type &&test) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); EXPECT_THROW(StringClass::unescape_unicode_character(begin, end), fly::UnicodeException); }; auto validate_pass = [](string_type &&test, string_type &&expected) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); string_type actual; EXPECT_NO_THROW(actual = StringClass::unescape_unicode_character(begin, end)); EXPECT_EQ(actual, expected); }; validate_fail(FLY_STR(char_type, "\\U")); validate_fail(FLY_STR(char_type, "\\U0")); validate_fail(FLY_STR(char_type, "\\U00")); validate_fail(FLY_STR(char_type, "\\U000")); validate_fail(FLY_STR(char_type, "\\U0000")); validate_fail(FLY_STR(char_type, "\\U00000")); validate_fail(FLY_STR(char_type, "\\U000000")); validate_fail(FLY_STR(char_type, "\\U0000000")); validate_fail(FLY_STR(char_type, "\\U0000000z")); validate_pass(FLY_STR(char_type, "\\U00010000"), FLY_STR(char_type, "\U00010000")); validate_pass(FLY_STR(char_type, "\\U00010E6D"), FLY_STR(char_type, "\U00010E6D")); validate_pass(FLY_STR(char_type, "\\U0001D11E"), FLY_STR(char_type, "\U0001D11E")); validate_pass(FLY_STR(char_type, "\\U0010FFFF"), FLY_STR(char_type, "\U0010FFFF")); } //================================================================================================== TYPED_TEST(BasicStringTest, UnicodeStringConversion) { DECLARE_ALIASES auto validate_fail = [](const string_type &test) { SCOPED_TRACE(test.c_str()); EXPECT_THROW(StringClass::unescape_unicode_string(test), fly::UnicodeException); }; auto validate_pass = [](const string_type &test, string_type &&expected) { SCOPED_TRACE(test.c_str()); string_type actual; EXPECT_NO_THROW(actual = StringClass::unescape_unicode_string(test)); EXPECT_EQ(actual, expected); }; validate_fail(FLY_STR(char_type, "\\U")); validate_fail(FLY_STR(char_type, "\\U0")); validate_fail(FLY_STR(char_type, "\\U00")); validate_fail(FLY_STR(char_type, "\\U000")); validate_fail(FLY_STR(char_type, "\\U0000")); validate_fail(FLY_STR(char_type, "\\U00000")); validate_fail(FLY_STR(char_type, "\\U000000")); validate_fail(FLY_STR(char_type, "\\U0000000")); validate_fail(FLY_STR(char_type, "\\U0000000z")); validate_fail(FLY_STR(char_type, "text \\U0000000z text")); validate_pass(FLY_STR(char_type, "No unicode!"), FLY_STR(char_type, "No unicode!")); validate_pass(FLY_STR(char_type, "Other escape \t"), FLY_STR(char_type, "Other escape \t")); validate_pass(FLY_STR(char_type, "\\U00010000"), FLY_STR(char_type, "\U00010000")); validate_pass(FLY_STR(char_type, "\\U00010E6D"), FLY_STR(char_type, "\U00010E6D")); validate_pass(FLY_STR(char_type, "\\U0001D11E"), FLY_STR(char_type, "\U0001D11E")); validate_pass(FLY_STR(char_type, "\\U0010FFFF"), FLY_STR(char_type, "\U0010FFFF")); validate_pass( FLY_STR(char_type, "\\U0001f355 in the morning, \\U0001f355 in the evening"), FLY_STR(char_type, "\U0001f355 in the morning, \U0001f355 in the evening")); } <commit_msg>Fix missing coverage in unescape_unicode_string (#134)<commit_after>#include "fly/types/string/string.hpp" #include "fly/types/string/string_exception.hpp" #include "fly/types/string/string_literal.hpp" #include "test/types/string_test.hpp" #include <gtest/gtest.h> //================================================================================================== TYPED_TEST(BasicStringTest, InvalidSequences) { DECLARE_ALIASES auto validate_fail = [](string_type &&test) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); EXPECT_THROW(StringClass::unescape_unicode_character(begin, end), fly::UnicodeException); }; validate_fail(FLY_STR(char_type, "")); validate_fail(FLY_STR(char_type, "f")); validate_fail(FLY_STR(char_type, "\\f")); } //================================================================================================== TYPED_TEST(BasicStringTest, Utf8CharacterConversion) { DECLARE_ALIASES auto validate_fail = [](string_type &&test) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); EXPECT_THROW(StringClass::unescape_unicode_character(begin, end), fly::UnicodeException); }; auto validate_pass = [](string_type &&test, string_type &&expected) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); string_type actual; EXPECT_NO_THROW(actual = StringClass::unescape_unicode_character(begin, end)); EXPECT_EQ(actual, expected); }; validate_fail(FLY_STR(char_type, "\\u")); validate_fail(FLY_STR(char_type, "\\u0")); validate_fail(FLY_STR(char_type, "\\u00")); validate_fail(FLY_STR(char_type, "\\u000")); validate_fail(FLY_STR(char_type, "\\u000z")); validate_pass(FLY_STR(char_type, "\\u0040"), FLY_STR(char_type, "\u0040")); validate_pass(FLY_STR(char_type, "\\u007A"), FLY_STR(char_type, "\u007A")); validate_pass(FLY_STR(char_type, "\\u007a"), FLY_STR(char_type, "\u007a")); validate_pass(FLY_STR(char_type, "\\u00c4"), FLY_STR(char_type, "\u00c4")); validate_pass(FLY_STR(char_type, "\\u00e4"), FLY_STR(char_type, "\u00e4")); validate_pass(FLY_STR(char_type, "\\u0298"), FLY_STR(char_type, "\u0298")); validate_pass(FLY_STR(char_type, "\\u0800"), FLY_STR(char_type, "\u0800")); validate_pass(FLY_STR(char_type, "\\uffff"), FLY_STR(char_type, "\uffff")); validate_fail(FLY_STR(char_type, "\\uDC00")); validate_fail(FLY_STR(char_type, "\\uDFFF")); validate_fail(FLY_STR(char_type, "\\uD800")); validate_fail(FLY_STR(char_type, "\\uDBFF")); } //================================================================================================== TYPED_TEST(BasicStringTest, Utf16CharacterConversion) { DECLARE_ALIASES auto validate_fail = [](string_type &&test) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); EXPECT_THROW(StringClass::unescape_unicode_character(begin, end), fly::UnicodeException); }; auto validate_pass = [](string_type &&test, string_type &&expected) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); string_type actual; EXPECT_NO_THROW(actual = StringClass::unescape_unicode_character(begin, end)); EXPECT_EQ(actual, expected); }; validate_fail(FLY_STR(char_type, "\\uD800\\u")); validate_fail(FLY_STR(char_type, "\\uD800\\z")); validate_fail(FLY_STR(char_type, "\\uD800\\u0")); validate_fail(FLY_STR(char_type, "\\uD800\\u00")); validate_fail(FLY_STR(char_type, "\\uD800\\u000")); validate_fail(FLY_STR(char_type, "\\uD800\\u0000")); validate_fail(FLY_STR(char_type, "\\uD800\\u000z")); validate_fail(FLY_STR(char_type, "\\uD800\\uDBFF")); validate_fail(FLY_STR(char_type, "\\uD800\\uE000")); validate_fail(FLY_STR(char_type, "\\uD800\\uFFFF")); validate_pass(FLY_STR(char_type, "\\uD800\\uDC00"), FLY_STR(char_type, "\U00010000")); validate_pass(FLY_STR(char_type, "\\uD803\\uDE6D"), FLY_STR(char_type, "\U00010E6D")); validate_pass(FLY_STR(char_type, "\\uD834\\uDD1E"), FLY_STR(char_type, "\U0001D11E")); validate_pass(FLY_STR(char_type, "\\uDBFF\\uDFFF"), FLY_STR(char_type, "\U0010FFFF")); } //================================================================================================== TYPED_TEST(BasicStringTest, Utf32CharacterConversion) { DECLARE_ALIASES auto validate_fail = [](string_type &&test) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); EXPECT_THROW(StringClass::unescape_unicode_character(begin, end), fly::UnicodeException); }; auto validate_pass = [](string_type &&test, string_type &&expected) { SCOPED_TRACE(test.c_str()); auto begin = test.cbegin(); const auto end = test.cend(); string_type actual; EXPECT_NO_THROW(actual = StringClass::unescape_unicode_character(begin, end)); EXPECT_EQ(actual, expected); }; validate_fail(FLY_STR(char_type, "\\U")); validate_fail(FLY_STR(char_type, "\\U0")); validate_fail(FLY_STR(char_type, "\\U00")); validate_fail(FLY_STR(char_type, "\\U000")); validate_fail(FLY_STR(char_type, "\\U0000")); validate_fail(FLY_STR(char_type, "\\U00000")); validate_fail(FLY_STR(char_type, "\\U000000")); validate_fail(FLY_STR(char_type, "\\U0000000")); validate_fail(FLY_STR(char_type, "\\U0000000z")); validate_pass(FLY_STR(char_type, "\\U00010000"), FLY_STR(char_type, "\U00010000")); validate_pass(FLY_STR(char_type, "\\U00010E6D"), FLY_STR(char_type, "\U00010E6D")); validate_pass(FLY_STR(char_type, "\\U0001D11E"), FLY_STR(char_type, "\U0001D11E")); validate_pass(FLY_STR(char_type, "\\U0010FFFF"), FLY_STR(char_type, "\U0010FFFF")); } //================================================================================================== TYPED_TEST(BasicStringTest, UnicodeStringConversion) { DECLARE_ALIASES auto validate_fail = [](const string_type &test) { SCOPED_TRACE(test.c_str()); EXPECT_THROW(StringClass::unescape_unicode_string(test), fly::UnicodeException); }; auto validate_pass = [](const string_type &test, string_type &&expected) { SCOPED_TRACE(test.c_str()); string_type actual; EXPECT_NO_THROW(actual = StringClass::unescape_unicode_string(test)); EXPECT_EQ(actual, expected); }; validate_fail(FLY_STR(char_type, "\\U")); validate_fail(FLY_STR(char_type, "\\U0")); validate_fail(FLY_STR(char_type, "\\U00")); validate_fail(FLY_STR(char_type, "\\U000")); validate_fail(FLY_STR(char_type, "\\U0000")); validate_fail(FLY_STR(char_type, "\\U00000")); validate_fail(FLY_STR(char_type, "\\U000000")); validate_fail(FLY_STR(char_type, "\\U0000000")); validate_fail(FLY_STR(char_type, "\\U0000000z")); validate_fail(FLY_STR(char_type, "text \\U0000000z text")); validate_pass(FLY_STR(char_type, "No unicode!"), FLY_STR(char_type, "No unicode!")); validate_pass(FLY_STR(char_type, "Other escape \t"), FLY_STR(char_type, "Other escape \t")); validate_pass(FLY_STR(char_type, "Other escape \\t"), FLY_STR(char_type, "Other escape \\t")); validate_pass(FLY_STR(char_type, "\\U00010000"), FLY_STR(char_type, "\U00010000")); validate_pass(FLY_STR(char_type, "\\U00010E6D"), FLY_STR(char_type, "\U00010E6D")); validate_pass(FLY_STR(char_type, "\\U0001D11E"), FLY_STR(char_type, "\U0001D11E")); validate_pass(FLY_STR(char_type, "\\U0010FFFF"), FLY_STR(char_type, "\U0010FFFF")); validate_pass( FLY_STR(char_type, "\\U0001f355 in the morning, \\U0001f355 in the evening"), FLY_STR(char_type, "\U0001f355 in the morning, \U0001f355 in the evening")); } <|endoftext|>
<commit_before>#include <test_helpers.hxx> #include <pqxx/except> using namespace std; using namespace pqxx; namespace { void test_exceptions(transaction_base &) { const string broken_query = "SELECT HORRIBLE ERROR", err = "Error message"; try { throw sql_error(err, broken_query); } catch (const pqxx_exception &e) { PQXX_CHECK_EQUAL(e.base().what(), err, "Exception contains wrong message."); const sql_error *downcast = dynamic_cast<const sql_error *>(&e.base()); PQXX_CHECK(downcast, "pqxx_exception-to-sql_error downcast is broken."); PQXX_CHECK_EQUAL( downcast->query(), broken_query, "Getting query from pqxx_exception is broken."); } } } // namespace PQXX_REGISTER_TEST_NODB(test_exceptions) <commit_msg>Test for sql_error::sqlstate().<commit_after>#include <test_helpers.hxx> #include <pqxx/except> using namespace std; using namespace pqxx; namespace { void test_exceptions(transaction_base &t) { const string broken_query = "SELECT HORRIBLE ERROR", err = "Error message"; try { throw sql_error(err, broken_query); } catch (const pqxx_exception &e) { PQXX_CHECK_EQUAL(e.base().what(), err, "Exception contains wrong message."); const sql_error *downcast = dynamic_cast<const sql_error *>(&e.base()); PQXX_CHECK(downcast, "pqxx_exception-to-sql_error downcast is broken."); PQXX_CHECK_EQUAL( downcast->query(), broken_query, "Getting query from pqxx_exception is broken."); } try { t.exec("INVALID QUERY HERE"); } catch (const syntax_error &e) { // SQL syntax error has sqlstate error 42601. PQXX_CHECK_EQUAL( e.sqlstate(), "42601", "Unexpected sqlstate on syntax error."); } } } // namespace PQXX_REGISTER_TEST(test_exceptions) <|endoftext|>
<commit_before>/*************************************************************************/ /* math_funcs.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "math_funcs.h" #include "core/os/os.h" pcg32_random_t Math::default_pcg = { 12047754176567800795ULL, PCG_DEFAULT_INC_64 }; #define PHI 0x9e3779b9 // TODO: we should eventually expose pcg.inc too uint32_t Math::rand_from_seed(uint64_t *seed) { pcg32_random_t pcg = { *seed, PCG_DEFAULT_INC_64 }; uint32_t r = pcg32_random_r(&pcg); *seed = pcg.state; return r; } void Math::seed(uint64_t x) { default_pcg.state = x; } void Math::randomize() { seed(OS::get_singleton()->get_ticks_usec() * default_pcg.state + PCG_DEFAULT_INC_64); } uint32_t Math::rand() { return pcg32_random_r(&default_pcg); } int Math::step_decimals(double p_step) { static const int maxn = 9; static const double sd[maxn] = { 0.9999, // somehow compensate for floating point error 0.09999, 0.009999, 0.0009999, 0.00009999, 0.000009999, 0.0000009999, 0.00000009999, 0.000000009999 }; double as = Math::abs(p_step); for (int i = 0; i < maxn; i++) { if (as >= sd[i]) { return i; } } return maxn; } double Math::dectime(double p_value, double p_amount, double p_step) { double sgn = p_value < 0 ? -1.0 : 1.0; double val = Math::abs(p_value); val -= p_amount * p_step; if (val < 0.0) val = 0.0; return val * sgn; } double Math::ease(double p_x, double p_c) { if (p_x < 0) p_x = 0; else if (p_x > 1.0) p_x = 1.0; if (p_c > 0) { if (p_c < 1.0) { return 1.0 - Math::pow(1.0 - p_x, 1.0 / p_c); } else { return Math::pow(p_x, p_c); } } else if (p_c < 0) { //inout ease if (p_x < 0.5) { return Math::pow(p_x * 2.0, -p_c) * 0.5; } else { return (1.0 - Math::pow(1.0 - (p_x - 0.5) * 2.0, -p_c)) * 0.5 + 0.5; } } else return 0; // no ease (raw) } double Math::stepify(double p_value, double p_step) { if (p_step != 0) { p_value = Math::floor(p_value / p_step + 0.5) * p_step; } return p_value; } uint32_t Math::larger_prime(uint32_t p_val) { static const uint32_t primes[] = { 5, 13, 23, 47, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741, 0, }; int idx = 0; while (true) { ERR_FAIL_COND_V(primes[idx] == 0, 0); if (primes[idx] > p_val) return primes[idx]; idx++; } return 0; } double Math::random(double from, double to) { unsigned int r = Math::rand(); double ret = (double)r / (double)RANDOM_MAX; return (ret) * (to - from) + from; } float Math::random(float from, float to) { unsigned int r = Math::rand(); float ret = (float)r / (float)RANDOM_MAX; return (ret) * (to - from) + from; } <commit_msg>Fix: Strip integer part in "decimals"<commit_after>/*************************************************************************/ /* math_funcs.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "math_funcs.h" #include "core/os/os.h" pcg32_random_t Math::default_pcg = { 12047754176567800795ULL, PCG_DEFAULT_INC_64 }; #define PHI 0x9e3779b9 // TODO: we should eventually expose pcg.inc too uint32_t Math::rand_from_seed(uint64_t *seed) { pcg32_random_t pcg = { *seed, PCG_DEFAULT_INC_64 }; uint32_t r = pcg32_random_r(&pcg); *seed = pcg.state; return r; } void Math::seed(uint64_t x) { default_pcg.state = x; } void Math::randomize() { seed(OS::get_singleton()->get_ticks_usec() * default_pcg.state + PCG_DEFAULT_INC_64); } uint32_t Math::rand() { return pcg32_random_r(&default_pcg); } int Math::step_decimals(double p_step) { static const int maxn = 10; static const double sd[maxn] = { 0.9999, // somehow compensate for floating point error 0.09999, 0.009999, 0.0009999, 0.00009999, 0.000009999, 0.0000009999, 0.00000009999, 0.000000009999, 0.0000000009999 }; double abs = Math::abs(p_step); double decs = abs - (int)abs; // Strip away integer part for (int i = 0; i < maxn; i++) { if (decs >= sd[i]) { return i; } } return 0; } double Math::dectime(double p_value, double p_amount, double p_step) { double sgn = p_value < 0 ? -1.0 : 1.0; double val = Math::abs(p_value); val -= p_amount * p_step; if (val < 0.0) val = 0.0; return val * sgn; } double Math::ease(double p_x, double p_c) { if (p_x < 0) p_x = 0; else if (p_x > 1.0) p_x = 1.0; if (p_c > 0) { if (p_c < 1.0) { return 1.0 - Math::pow(1.0 - p_x, 1.0 / p_c); } else { return Math::pow(p_x, p_c); } } else if (p_c < 0) { //inout ease if (p_x < 0.5) { return Math::pow(p_x * 2.0, -p_c) * 0.5; } else { return (1.0 - Math::pow(1.0 - (p_x - 0.5) * 2.0, -p_c)) * 0.5 + 0.5; } } else return 0; // no ease (raw) } double Math::stepify(double p_value, double p_step) { if (p_step != 0) { p_value = Math::floor(p_value / p_step + 0.5) * p_step; } return p_value; } uint32_t Math::larger_prime(uint32_t p_val) { static const uint32_t primes[] = { 5, 13, 23, 47, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741, 0, }; int idx = 0; while (true) { ERR_FAIL_COND_V(primes[idx] == 0, 0); if (primes[idx] > p_val) return primes[idx]; idx++; } return 0; } double Math::random(double from, double to) { unsigned int r = Math::rand(); double ret = (double)r / (double)RANDOM_MAX; return (ret) * (to - from) + from; } float Math::random(float from, float to) { unsigned int r = Math::rand(); float ret = (float)r / (float)RANDOM_MAX; return (ret) * (to - from) + from; } <|endoftext|>
<commit_before>#include <set> #include <cstdlib> #include <unsupported/Eigen/SparseExtra> #include "utils.h" #include "matrix_io.h" const static Eigen::IOFormat csvFormat(6, Eigen::DontAlignCols, ",", "\n"); void writeToCSVfile(std::string filename, Eigen::MatrixXd matrix) { std::ofstream file(filename.c_str()); file << matrix.rows() << std::endl; file << matrix.cols() << std::endl; file << matrix.format(csvFormat); } void readFromCSVfile(std::string filename, Eigen::MatrixXd &matrix) { std::ifstream file(filename.c_str()); std::string line; // rows and cols getline(file, line); int nrow = atol(line.c_str()); getline(file, line); int ncol = atol(line.c_str()); matrix.resize(nrow, ncol); int row = 0; int col = 0; while (getline(file, line)) { col = 0; std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { matrix(row, col++) = strtod(cell.c_str(), NULL); } row++; } assert(row == nrow); assert(col == ncol); } Macau::MatrixConfig read_csv(std::string filename) { Macau::MatrixConfig ret; std::ifstream file(filename.c_str()); std::string line; ret.dense = true; // rows and cols getline(file, line); ret.nrow = atol(line.c_str()); getline(file, line); ret.ncol = atol(line.c_str()); ret.nnz = ret.nrow * ret.ncol; ret.values = new double[ret.nnz]; int row = 0; int col = 0; while (getline(file, line)) { col = 0; std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { ret.values[row + (ret.nrow*col++)] = strtod(cell.c_str(), NULL); } row++; } assert(row == ret.nrow); assert(col == ret.ncol); return ret; } std::unique_ptr<SparseFeat> load_bcsr(const char* filename) { SparseBinaryMatrix* A = read_sbm(filename); SparseFeat* sf = new SparseFeat(A->nrow, A->ncol, A->nnz, A->rows, A->cols); free_sbm(A); std::unique_ptr<SparseFeat> sf_ptr(sf); return sf_ptr; } std::unique_ptr<SparseDoubleFeat> load_csr(const char* filename) { struct SparseDoubleMatrix* A = read_sdm(filename); SparseDoubleFeat* sf = new SparseDoubleFeat(A->nrow, A->ncol, A->nnz, A->rows, A->cols, A->vals); delete A; std::unique_ptr<SparseDoubleFeat> sf_ptr(sf); return sf_ptr; } Eigen::MatrixXd sparse_to_dense(SparseBinaryMatrix &in) { Eigen::MatrixXd out = Eigen::MatrixXd::Zero(in.nrow, in.ncol); for(int i=0; i<in.nnz; ++i) out(in.rows[i], in.cols[i]) = 1.; return out; } Eigen::MatrixXd sparse_to_dense(SparseDoubleMatrix &in) { Eigen::MatrixXd out = Eigen::MatrixXd::Zero(in.nrow, in.ncol); for(int i=0; i<in.nnz; ++i) out(in.rows[i], in.cols[i]) = in.vals[i]; return out; } static std::set<std::string> compact_matrix_fname_extensions = { ".sbm", ".sdm", ".ddm" }; static std::set<std::string> txt_matrix_fname_extensions = { ".mtx", ".mm", ".csv" }; static std::set<std::string> matrix_fname_extensions = { ".sbm", ".sdm", ".ddm", ".mtx", ".mm", ".csv" }; static std::set<std::string> sparse_fname_extensions = { ".sbm", ".sdm", ".mtx", ".mm" }; bool extension_in(std::string fname, const std::set<std::string> &extensions, bool = false); bool is_matrix_fname(std::string fname) { return extension_in(fname, matrix_fname_extensions); } bool extension_in(std::string fname, const std::set<std::string> &extensions, bool die_if_not_found) { std::string extension = fname.substr(fname.find_last_of(".")); if (extensions.find(extension) != extensions.end()) return true; if (die_if_not_found) { die("Unknown extension: " + extension + " of filename: " + fname); } return false; } bool is_sparse_fname(std::string fname) { return extension_in(fname, sparse_fname_extensions); } bool is_sparse_binary_fname(std::string fname) { return extension_in(fname, { ".sbm" }); } bool is_dense_fname(std::string fname) { return !is_sparse_fname(fname); } bool is_compact_fname(std::string fname) { return file_exists(fname) && extension_in(fname, compact_matrix_fname_extensions); } void read_dense(std::string fname, Eigen::VectorXd &V) { Eigen::MatrixXd X; read_dense(fname, X); V = X; // this will fail if X has more than one column } void read_dense(std::string fname, Eigen::MatrixXd &X) { die_unless_file_exists(fname); std::string extension = fname.substr(fname.size() - 4); if (extension == ".ddm") { read_ddm(fname.c_str(), X); } else if (extension == ".csv") { readFromCSVfile(fname, X); } else { die("Unknown filename in read_dense: " + fname); } } Macau::MatrixConfig read_dense(std::string fname) { die_unless_file_exists(fname); std::string extension = fname.substr(fname.size() - 4); if (extension == ".ddm") { return read_ddm(fname); } else if (extension == ".csv") { return read_csv(fname); } else { die("Unknown filename in read_dense: " + fname); } return Macau::MatrixConfig(); } void write_dense(std::string fname, const Eigen::MatrixXd &X) { assert(is_dense_fname(fname)); std::string extension = fname.substr(fname.size() - 4); if (extension == ".ddm") { write_ddm(fname.c_str(), X); } else if (extension == ".csv") { writeToCSVfile(fname, X); } else { die("Unknown filename in write_dense: " + fname); } } void write_ddm(std::string filename, const Eigen::MatrixXd& matrix) { std::ofstream out(filename,std::ios::out | std::ios::binary | std::ios::trunc); long rows = matrix.rows(); long cols = matrix.cols(); out.write((char*) (&rows), sizeof(long)); out.write((char*) (&cols), sizeof(long)); out.write((char*) matrix.data(), rows*cols*sizeof(typename Eigen::MatrixXd::Scalar) ); out.close(); } void read_ddm(std::string filename, Eigen::MatrixXd &matrix) { std::ifstream in(filename,std::ios::in | std::ios::binary); long rows=0, cols=0; in.read((char*) (&rows),sizeof(long)); in.read((char*) (&cols),sizeof(long)); matrix.resize(rows, cols); in.read( (char *) matrix.data() , rows*cols*sizeof(long) ); in.close(); } Macau::MatrixConfig read_ddm(std::string filename) { Macau::MatrixConfig ret; ret.dense = true; std::ifstream in(filename,std::ios::in | std::ios::binary); in.read((char*) (&ret.nrow),sizeof(long)); in.read((char*) (&ret.ncol),sizeof(long)); ret.nnz = ret.nrow * ret.ncol; ret.values = new double[ret.nnz]; in.read( (char *) ret.values, ret.nnz*sizeof(double) ); return ret; } Macau::MatrixConfig read_mtx(std::string fname) { Macau::MatrixConfig ret; ret.dense = false; std::ifstream fin(fname); // Ignore headers and comments: while (fin.peek() == '%') fin.ignore(2048, '\n'); // Read defining parameters: fin >> ret.nrow >> ret.ncol >> ret.nnz; fin.ignore(2048, '\n'); // skip to end of line ret.rows = new int[ret.nnz]; ret.cols = new int[ret.nnz]; ret.values = new double[ret.nnz]; // Read the data char line[2048]; int r,c; double v; for (int l = 0; l < ret.nnz; l++) { fin.getline(line, 2048); std::stringstream ls(line); ls >> r >> c; assert(!ls.fail()); ls >> v; if (ls.fail()) v = 1.0; r--; c--; assert(r < ret.nrow); assert(r >= 0); assert(c < ret.ncol); assert(c >= 0); ret.rows[l] = r; ret.cols[l] = c; ret.values[l] = v; } return ret; } Macau::MatrixConfig read_sparse(std::string fname) { assert(is_sparse_fname(fname)); std::string extension = fname.substr(fname.find_last_of(".")); if (extension == ".sdm") { auto p = read_sdm(fname.c_str()); auto m = Macau::MatrixConfig(p->nrow, p->ncol, p->nnz, p->rows, p->cols, p->vals); delete p; return m; } else if (extension == ".sbm") { auto p = read_sbm(fname.c_str()); auto m = Macau::MatrixConfig(p->nrow, p->ncol, p->nnz, p->rows, p->cols); delete p; return m; } else if (extension == ".mtx" || extension == ".mm") { return read_mtx(fname); } else { die("Unknown filename in read_sparse: " + fname); } return Macau::MatrixConfig(); } void read_sparse(std::string fname, Eigen::SparseMatrix<double> &M) { assert(is_sparse_fname(fname)); std::string extension = fname.substr(fname.find_last_of(".")); if (extension == ".sdm") { auto sdm_ptr = read_sdm(fname.c_str()); M = sparse_to_eigen(*sdm_ptr); delete sdm_ptr; } else if (extension == ".sbm") { auto sbm_ptr = read_sbm(fname.c_str()); M = sparse_to_eigen(*sbm_ptr); delete sbm_ptr; } else if (extension == ".mtx" || extension == ".mm") { loadMarket(M, fname.c_str()); } else { die("Unknown filename in read_sparse: " + fname); } } Macau::MatrixConfig read_matrix(std::string fname) { if (is_sparse_fname(fname)) return read_sparse(fname); else return read_dense(fname); } <commit_msg>newline at the end of csv file<commit_after>#include <set> #include <cstdlib> #include <unsupported/Eigen/SparseExtra> #include "utils.h" #include "matrix_io.h" const static Eigen::IOFormat csvFormat(6, Eigen::DontAlignCols, ",", "\n"); void writeToCSVfile(std::string filename, Eigen::MatrixXd matrix) { std::ofstream file(filename.c_str()); file << matrix.rows() << std::endl; file << matrix.cols() << std::endl; file << matrix.format(csvFormat) << std::endl; } void readFromCSVfile(std::string filename, Eigen::MatrixXd &matrix) { std::ifstream file(filename.c_str()); std::string line; // rows and cols getline(file, line); int nrow = atol(line.c_str()); getline(file, line); int ncol = atol(line.c_str()); matrix.resize(nrow, ncol); int row = 0; int col = 0; while (getline(file, line)) { col = 0; std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { matrix(row, col++) = strtod(cell.c_str(), NULL); } row++; } assert(row == nrow); assert(col == ncol); } Macau::MatrixConfig read_csv(std::string filename) { Macau::MatrixConfig ret; std::ifstream file(filename.c_str()); std::string line; ret.dense = true; // rows and cols getline(file, line); ret.nrow = atol(line.c_str()); getline(file, line); ret.ncol = atol(line.c_str()); ret.nnz = ret.nrow * ret.ncol; ret.values = new double[ret.nnz]; int row = 0; int col = 0; while (getline(file, line)) { col = 0; std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { ret.values[row + (ret.nrow*col++)] = strtod(cell.c_str(), NULL); } row++; } assert(row == ret.nrow); assert(col == ret.ncol); return ret; } std::unique_ptr<SparseFeat> load_bcsr(const char* filename) { SparseBinaryMatrix* A = read_sbm(filename); SparseFeat* sf = new SparseFeat(A->nrow, A->ncol, A->nnz, A->rows, A->cols); free_sbm(A); std::unique_ptr<SparseFeat> sf_ptr(sf); return sf_ptr; } std::unique_ptr<SparseDoubleFeat> load_csr(const char* filename) { struct SparseDoubleMatrix* A = read_sdm(filename); SparseDoubleFeat* sf = new SparseDoubleFeat(A->nrow, A->ncol, A->nnz, A->rows, A->cols, A->vals); delete A; std::unique_ptr<SparseDoubleFeat> sf_ptr(sf); return sf_ptr; } Eigen::MatrixXd sparse_to_dense(SparseBinaryMatrix &in) { Eigen::MatrixXd out = Eigen::MatrixXd::Zero(in.nrow, in.ncol); for(int i=0; i<in.nnz; ++i) out(in.rows[i], in.cols[i]) = 1.; return out; } Eigen::MatrixXd sparse_to_dense(SparseDoubleMatrix &in) { Eigen::MatrixXd out = Eigen::MatrixXd::Zero(in.nrow, in.ncol); for(int i=0; i<in.nnz; ++i) out(in.rows[i], in.cols[i]) = in.vals[i]; return out; } static std::set<std::string> compact_matrix_fname_extensions = { ".sbm", ".sdm", ".ddm" }; static std::set<std::string> txt_matrix_fname_extensions = { ".mtx", ".mm", ".csv" }; static std::set<std::string> matrix_fname_extensions = { ".sbm", ".sdm", ".ddm", ".mtx", ".mm", ".csv" }; static std::set<std::string> sparse_fname_extensions = { ".sbm", ".sdm", ".mtx", ".mm" }; bool extension_in(std::string fname, const std::set<std::string> &extensions, bool = false); bool is_matrix_fname(std::string fname) { return extension_in(fname, matrix_fname_extensions); } bool extension_in(std::string fname, const std::set<std::string> &extensions, bool die_if_not_found) { std::string extension = fname.substr(fname.find_last_of(".")); if (extensions.find(extension) != extensions.end()) return true; if (die_if_not_found) { die("Unknown extension: " + extension + " of filename: " + fname); } return false; } bool is_sparse_fname(std::string fname) { return extension_in(fname, sparse_fname_extensions); } bool is_sparse_binary_fname(std::string fname) { return extension_in(fname, { ".sbm" }); } bool is_dense_fname(std::string fname) { return !is_sparse_fname(fname); } bool is_compact_fname(std::string fname) { return file_exists(fname) && extension_in(fname, compact_matrix_fname_extensions); } void read_dense(std::string fname, Eigen::VectorXd &V) { Eigen::MatrixXd X; read_dense(fname, X); V = X; // this will fail if X has more than one column } void read_dense(std::string fname, Eigen::MatrixXd &X) { die_unless_file_exists(fname); std::string extension = fname.substr(fname.size() - 4); if (extension == ".ddm") { read_ddm(fname.c_str(), X); } else if (extension == ".csv") { readFromCSVfile(fname, X); } else { die("Unknown filename in read_dense: " + fname); } } Macau::MatrixConfig read_dense(std::string fname) { die_unless_file_exists(fname); std::string extension = fname.substr(fname.size() - 4); if (extension == ".ddm") { return read_ddm(fname); } else if (extension == ".csv") { return read_csv(fname); } else { die("Unknown filename in read_dense: " + fname); } return Macau::MatrixConfig(); } void write_dense(std::string fname, const Eigen::MatrixXd &X) { assert(is_dense_fname(fname)); std::string extension = fname.substr(fname.size() - 4); if (extension == ".ddm") { write_ddm(fname.c_str(), X); } else if (extension == ".csv") { writeToCSVfile(fname, X); } else { die("Unknown filename in write_dense: " + fname); } } void write_ddm(std::string filename, const Eigen::MatrixXd& matrix) { std::ofstream out(filename,std::ios::out | std::ios::binary | std::ios::trunc); long rows = matrix.rows(); long cols = matrix.cols(); out.write((char*) (&rows), sizeof(long)); out.write((char*) (&cols), sizeof(long)); out.write((char*) matrix.data(), rows*cols*sizeof(typename Eigen::MatrixXd::Scalar) ); out.close(); } void read_ddm(std::string filename, Eigen::MatrixXd &matrix) { std::ifstream in(filename,std::ios::in | std::ios::binary); long rows=0, cols=0; in.read((char*) (&rows),sizeof(long)); in.read((char*) (&cols),sizeof(long)); matrix.resize(rows, cols); in.read( (char *) matrix.data() , rows*cols*sizeof(long) ); in.close(); } Macau::MatrixConfig read_ddm(std::string filename) { Macau::MatrixConfig ret; ret.dense = true; std::ifstream in(filename,std::ios::in | std::ios::binary); in.read((char*) (&ret.nrow),sizeof(long)); in.read((char*) (&ret.ncol),sizeof(long)); ret.nnz = ret.nrow * ret.ncol; ret.values = new double[ret.nnz]; in.read( (char *) ret.values, ret.nnz*sizeof(double) ); return ret; } Macau::MatrixConfig read_mtx(std::string fname) { Macau::MatrixConfig ret; ret.dense = false; std::ifstream fin(fname); // Ignore headers and comments: while (fin.peek() == '%') fin.ignore(2048, '\n'); // Read defining parameters: fin >> ret.nrow >> ret.ncol >> ret.nnz; fin.ignore(2048, '\n'); // skip to end of line ret.rows = new int[ret.nnz]; ret.cols = new int[ret.nnz]; ret.values = new double[ret.nnz]; // Read the data char line[2048]; int r,c; double v; for (int l = 0; l < ret.nnz; l++) { fin.getline(line, 2048); std::stringstream ls(line); ls >> r >> c; assert(!ls.fail()); ls >> v; if (ls.fail()) v = 1.0; r--; c--; assert(r < ret.nrow); assert(r >= 0); assert(c < ret.ncol); assert(c >= 0); ret.rows[l] = r; ret.cols[l] = c; ret.values[l] = v; } return ret; } Macau::MatrixConfig read_sparse(std::string fname) { assert(is_sparse_fname(fname)); std::string extension = fname.substr(fname.find_last_of(".")); if (extension == ".sdm") { auto p = read_sdm(fname.c_str()); auto m = Macau::MatrixConfig(p->nrow, p->ncol, p->nnz, p->rows, p->cols, p->vals); delete p; return m; } else if (extension == ".sbm") { auto p = read_sbm(fname.c_str()); auto m = Macau::MatrixConfig(p->nrow, p->ncol, p->nnz, p->rows, p->cols); delete p; return m; } else if (extension == ".mtx" || extension == ".mm") { return read_mtx(fname); } else { die("Unknown filename in read_sparse: " + fname); } return Macau::MatrixConfig(); } void read_sparse(std::string fname, Eigen::SparseMatrix<double> &M) { assert(is_sparse_fname(fname)); std::string extension = fname.substr(fname.find_last_of(".")); if (extension == ".sdm") { auto sdm_ptr = read_sdm(fname.c_str()); M = sparse_to_eigen(*sdm_ptr); delete sdm_ptr; } else if (extension == ".sbm") { auto sbm_ptr = read_sbm(fname.c_str()); M = sparse_to_eigen(*sbm_ptr); delete sbm_ptr; } else if (extension == ".mtx" || extension == ".mm") { loadMarket(M, fname.c_str()); } else { die("Unknown filename in read_sparse: " + fname); } } Macau::MatrixConfig read_matrix(std::string fname) { if (is_sparse_fname(fname)) return read_sparse(fname); else return read_dense(fname); } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/Reply.h" namespace joynr { Reply::Reply() : requestReplyId(), error() { } Reply::Reply(BaseReply&& baseReply) : BaseReply::BaseReply(std::move(baseReply)), requestReplyId(), error() { } const std::string& Reply::getRequestReplyId() const { return requestReplyId; } void Reply::setRequestReplyId(const std::string& requestReplyId) { this->requestReplyId = requestReplyId; } std::shared_ptr<exceptions::JoynrException> Reply::getError() const { return error; } void Reply::setError(std::shared_ptr<exceptions::JoynrException> error) { this->error = std::move(error); } bool Reply::operator==(const Reply& other) const { return requestReplyId == other.getRequestReplyId() && error == other.getError() && BaseReply::operator==(other); } bool Reply::operator!=(const Reply& other) const { return !(*this == other); } } // namespace joynr <commit_msg>[C++] fix operator== in Reply<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/Reply.h" namespace joynr { Reply::Reply() : requestReplyId(), error() { } Reply::Reply(BaseReply&& baseReply) : BaseReply::BaseReply(std::move(baseReply)), requestReplyId(), error() { } const std::string& Reply::getRequestReplyId() const { return requestReplyId; } void Reply::setRequestReplyId(const std::string& requestReplyId) { this->requestReplyId = requestReplyId; } std::shared_ptr<exceptions::JoynrException> Reply::getError() const { return error; } void Reply::setError(std::shared_ptr<exceptions::JoynrException> error) { this->error = std::move(error); } bool Reply::operator==(const Reply& other) const { // if error ptr do not point to the same object if (error != other.getError()) { // if exactly one of error and other.getError() is a nullptr if (error == nullptr || other.getError() == nullptr) { return false; } // compare actual objects if (!(*error.get() == *other.getError().get())) { return false; } } return requestReplyId == other.getRequestReplyId() && BaseReply::operator==(other); } bool Reply::operator!=(const Reply& other) const { return !(*this == other); } } // namespace joynr <|endoftext|>
<commit_before>// A little calculator test #include <boost/algorithm/string.hpp> using std::cout; using std::cin; int main() { cout << "Press 1 to add, 2 to multiply, 3 to subtract, 4 to divide, or 5 to exit: "; int input; cin >> input; std::cin.ignore(); if (input < 5) { // Some variable declarations std::string numbers_str; std::vector<int> numbers_int; std::vector<std::string> numbers_vect; std::string op_names[] = {"added", "multiplied", "subtracted", "divided"}; cout << "Enter 2 or more numbers to be " << op_names[input - 1] << ": "; std::getline(cin, numbers_str); // Splits numbers_str by whitespace, then converts the string vector into an int vector boost::split(numbers_vect, numbers_str, boost::is_any_of("\t ")); std::transform(begin(numbers_vect), end(numbers_vect), std::back_inserter(numbers_int), [](const std::string& val) { return std::stoi(val); }); // The math part if (1 == input) { int sum = std::accumulate(numbers_int.begin(), numbers_int.end(), 0); cout << sum << std::endl; } else if (2 == input) { int multiply_ans = std::accumulate(numbers_int.begin(), numbers_int.end(), 1, std::multiplies<int>()); cout << multiply_ans << std::endl; } else if (3 == input) { int subtract_ans = std::accumulate(numbers_int.begin() + 1, numbers_int.end(), numbers_int[0], std::minus<int>()); cout << subtract_ans << std::endl; } else if (4 == input) { int division_ans = std::accumulate(numbers_int.begin() + 1, numbers_int.end(), numbers_int[0], std::divides<int>()); cout << division_ans << std::endl; } } else if (5 == input) { return 0; } else { cout << "Invalid option \"" << input << "\"" << std::endl; } } <commit_msg>Made a few workflow changes to calculator.cpp and added support for floating point arithmetic<commit_after>// A little calculator test #include <boost/algorithm/string.hpp> using std::cout; using std::cin; int main() { while (true) { cout << "Press 1 to add, 2 to multiply, 3 to subtract, 4 to divide, or 5 to exit: "; int input; cin >> input; std::cin.ignore(); if (input < 5) { // Some variable declarations std::string numbers_str; std::vector<float> numbers_float; std::vector<std::string> numbers_vect; std::string op_names[] = {"added", "multiplied", "subtracted", "divided"}; cout << "Enter 2 or more numbers to be " << op_names[input - 1] << ": "; std::getline(cin, numbers_str); // Split numbers_str by whitespace, then converts the string vector into an int vector boost::split(numbers_vect, numbers_str, boost::is_any_of("\t ")); std::transform(begin(numbers_vect), end(numbers_vect), std::back_inserter(numbers_float), [](const std::string& val) { return std::stof(val); }); // The math part if (1 == input) { float sum = std::accumulate(numbers_float.begin(), numbers_float.end(), 0.0); cout << sum << std::endl; continue; } else if (2 == input) { float multiply_ans = std::accumulate(numbers_float.begin(), numbers_float.end(), 1.0, std::multiplies<float>()); cout << multiply_ans << std::endl; continue; } else if (3 == input) { float subtract_ans = std::accumulate(numbers_float.begin() + 1, numbers_float.end(), numbers_float[0], std::minus<float>()); cout << subtract_ans << std::endl; continue; } else if (4 == input) { float division_ans = std::accumulate(numbers_float.begin() + 1, numbers_float.end(), numbers_float[0], std::divides<float>()); cout << division_ans << std::endl; continue; } } if (5 == input) { return 0; } else { cout << "Invalid option \"" << input << "\"" << std::endl; continue; } } } <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "nvs_flash.h" #include "driver/uart.h" #include "freertos/queue.h" #include "esp_log.h" #include "soc/uart_struct.h" #include "MFRC522.h" //------------------MFRC522 register --------------- #define COMMAND_WAIT 0x02 #define COMMAND_READBLOCK 0x03 #define COMMAND_WRITEBLOCK 0x04 #define MFRC522_HEADER 0xAB #define STATUS_ERROR 0 #define STATUS_OK 1 #define MIFARE_KEYA 0x00 #define MIFARE_KEYB 0x01 /** * Constructor. */ MFRC522::MFRC522() { } /** * Description: Obtiene control del Serial para controlar MFRC522. * Ademas, pone MFRC522 en modo de espera. */ void MFRC522::begin(void) { wait(); } /** * Description:Pone MFRC522 en modo espera. */ void MFRC522::wait() { } /** * Description:Returns true if detect card in MFRC522. */ bool MFRC522::available() { } /** * Description:Read the serial number of the card. */ void MFRC522::readCardSerial() { for (int i = 0; i < sizeof(cardSerial); ){ if (available()){ cardSerial[i] = read(); i++; } } } /** * Description:Returns a pointer to array with card serial. */ byte *MFRC522::getCardSerial() { return cardSerial; } /** * Description:Read a block data of the card. * Return:Return STATUS_OK if success. */ bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) { byte sendData[8] = { block, // block keyType, // key type 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key }; byte returnBlockLength; for (int i = 0; i < 6; ++i) { sendData[2 + i] = key[i]; } return communicate( COMMAND_READBLOCK, // command sendData, // sendData 0x0A, // length returnBlock, // returnData &returnBlockLength // returnDataLength ); } /** * Description:Write a block data in the card. * Return:Return STATUS_OK if success. */ bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) { byte sendData[24] = { block, // block keyType, // key type 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data }; byte returnBlock[3]; byte returnBlockLength; for (int i = 0; i < 6; ++i) { sendData[2 + i] = key[i]; } for (int i = 0; i < 16; ++i) { sendData[8 + i] = data[i]; } byte result = communicate( COMMAND_WRITEBLOCK, // command sendData, // sendData 0x1A, // length returnBlock, // returnData &returnBlockLength // returnDataLength ); return result; } /** * Description:Comunication between MFRC522 and ISO14443. * Return:Return STATUS_OK if success. */ bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) { // Send instruction to MFRC522 write(MFRC522_HEADER); // Header write(sendDataLength); // Length (Length + Command + Data) write(command); // Command for (int i = 0; i < sendDataLength - 2; i++) { write(sendData[i]); // Data } // Read response to MFRC522 while (!available()); byte header = read(); // Header while (!available()); *returnDataLength = read(); // Length (Length + Command + Data) while (!available()); byte commandResult = read(); // Command result for (int i = 0; i < *returnDataLength - 2; i=i) { if (available()) { returnData[i] = read(); // Data i++; } } // Return if (command != commandResult) { return STATUS_ERROR; } return STATUS_OK; } /* * Description:Write a byte data into MFRC522. */ void MFRC522::write(byte value) { } /* * Description:Read a byte data of MFRC522 * Return:Return the read value. */ byte MFRC522::read() { } <commit_msg>Update MFRC522.cpp<commit_after>#include <stdio.h> #include <string.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "nvs_flash.h" #include "driver/uart.h" #include "freertos/queue.h" #include "esp_log.h" #include "soc/uart_struct.h" #include "MFRC522.h" //------------------MFRC522 register --------------- #define COMMAND_WAIT 0x02 #define COMMAND_READBLOCK 0x03 #define COMMAND_WRITEBLOCK 0x04 #define MFRC522_HEADER 0xAB #define STATUS_ERROR 0 #define STATUS_OK 1 #define MIFARE_KEYA 0x00 #define MIFARE_KEYB 0x01 /** * Constructor. */ MFRC522::MFRC522() { } /** * Description: Obtiene control del Serial para controlar MFRC522. * Ademas, pone MFRC522 en modo de espera. */ void MFRC522::begin(void) { wait(); } /** * Description:Pone MFRC522 en modo espera. */ void MFRC522::wait() { } /** * Description:Returns true if detect card in MFRC522. */ bool MFRC522::available() { return false; } /** * Description:Read the serial number of the card. */ void MFRC522::readCardSerial() { for (int i = 0; i < sizeof(cardSerial); ){ if (available()){ cardSerial[i] = read(); i++; } } } /** * Description:Returns a pointer to array with card serial. */ byte *MFRC522::getCardSerial() { return cardSerial; } /** * Description:Read a block data of the card. * Return:Return STATUS_OK if success. */ bool MFRC522::getBlock(byte block, byte keyType, byte *key, byte *returnBlock) { byte sendData[8] = { block, // block keyType, // key type 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // key }; byte returnBlockLength; for (int i = 0; i < 6; ++i) { sendData[2 + i] = key[i]; } return communicate( COMMAND_READBLOCK, // command sendData, // sendData 0x0A, // length returnBlock, // returnData &returnBlockLength // returnDataLength ); } /** * Description:Write a block data in the card. * Return:Return STATUS_OK if success. */ bool MFRC522::writeBlock(byte block, byte keyType, byte *key, byte *data) { byte sendData[24] = { block, // block keyType, // key type 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // key 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Data }; byte returnBlock[3]; byte returnBlockLength; for (int i = 0; i < 6; ++i) { sendData[2 + i] = key[i]; } for (int i = 0; i < 16; ++i) { sendData[8 + i] = data[i]; } byte result = communicate( COMMAND_WRITEBLOCK, // command sendData, // sendData 0x1A, // length returnBlock, // returnData &returnBlockLength // returnDataLength ); return result; } /** * Description:Comunication between MFRC522 and ISO14443. * Return:Return STATUS_OK if success. */ bool MFRC522::communicate(byte command, byte *sendData, byte sendDataLength, byte *returnData, byte *returnDataLength) { // Send instruction to MFRC522 write(MFRC522_HEADER); // Header write(sendDataLength); // Length (Length + Command + Data) write(command); // Command for (int i = 0; i < sendDataLength - 2; i++) { write(sendData[i]); // Data } // Read response to MFRC522 while (!available()); byte header = read(); // Header while (!available()); *returnDataLength = read(); // Length (Length + Command + Data) while (!available()); byte commandResult = read(); // Command result for (int i = 0; i < *returnDataLength - 2; i=i) { if (available()) { returnData[i] = read(); // Data i++; } } // Return if (command != commandResult) { return STATUS_ERROR; } return STATUS_OK; } /* * Description:Write a byte data into MFRC522. */ void MFRC522::write(byte value) { } /* * Description:Read a byte data of MFRC522 * Return:Return the read value. */ byte MFRC522::read() { return 0; } <|endoftext|>
<commit_before>/***************************************************************************** * mkv.cpp : matroska demuxer ***************************************************************************** * Copyright (C) 2003-2005, 2008 the VideoLAN team * $Id$ * * Authors: Laurent Aimar <fenrir@via.ecp.fr> * Steve Lhomme <steve.lhomme@free.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _MKV_H_ #define _MKV_H_ /***************************************************************************** * Preamble *****************************************************************************/ /* config.h may include inttypes.h, so make sure we define that option * early enough. */ #define __STDC_FORMAT_MACROS 1 #define __STDC_CONSTANT_MACROS 1 #define __STDC_LIMIT_MACROS 1 #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <inttypes.h> #include <vlc_common.h> #include <vlc_plugin.h> #ifdef HAVE_TIME_H # include <time.h> /* time() */ #endif #include <vlc_meta.h> #include <vlc_charset.h> #include <vlc_input.h> #include <vlc_demux.h> #include <iostream> #include <cassert> #include <typeinfo> #include <string> #include <vector> #include <algorithm> /* libebml and matroska */ #include "ebml/EbmlHead.h" #include "ebml/EbmlSubHead.h" #include "ebml/EbmlStream.h" #include "ebml/EbmlContexts.h" #include "ebml/EbmlVoid.h" #include "ebml/EbmlVersion.h" #include "ebml/StdIOCallback.h" #include "matroska/KaxAttachments.h" #include "matroska/KaxAttached.h" #include "matroska/KaxBlock.h" #include "matroska/KaxBlockData.h" #include "matroska/KaxChapters.h" #include "matroska/KaxCluster.h" #include "matroska/KaxClusterData.h" #include "matroska/KaxContexts.h" #include "matroska/KaxCues.h" #include "matroska/KaxCuesData.h" #include "matroska/KaxInfo.h" #include "matroska/KaxInfoData.h" #include "matroska/KaxSeekHead.h" #include "matroska/KaxSegment.h" #include "matroska/KaxTag.h" #include "matroska/KaxTags.h" #include "matroska/KaxTagMulti.h" #include "matroska/KaxTracks.h" #include "matroska/KaxTrackAudio.h" #include "matroska/KaxTrackVideo.h" #include "matroska/KaxTrackEntryData.h" #include "matroska/KaxContentEncoding.h" #include "matroska/KaxVersion.h" #include "ebml/StdIOCallback.h" #include <vlc_keys.h> extern "C" { #include "../mp4/libmp4.h" } #ifdef HAVE_ZLIB_H # include <zlib.h> #endif #define MKV_DEBUG 0 #define MATROSKA_COMPRESSION_NONE -1 #define MATROSKA_COMPRESSION_ZLIB 0 #define MATROSKA_COMPRESSION_BLIB 1 #define MATROSKA_COMPRESSION_LZOX 2 #define MATROSKA_COMPRESSION_HEADER 3 #define MKVD_TIMECODESCALE 1000000 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId ) using namespace LIBMATROSKA_NAMESPACE; using namespace std; void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock, mtime_t i_pts, mtime_t i_duration, bool f_mandatory ); class attachment_c { public: attachment_c() :p_data(NULL) ,i_size(0) {} virtual ~attachment_c() { free( p_data ); } std::string psz_file_name; std::string psz_mime_type; void *p_data; int i_size; }; class matroska_segment_c; class matroska_stream_c { public: matroska_stream_c( demux_sys_t & demuxer ) :p_in(NULL) ,p_es(NULL) ,sys(demuxer) {} virtual ~matroska_stream_c() { delete p_in; delete p_es; } IOCallback *p_in; EbmlStream *p_es; std::vector<matroska_segment_c*> segments; demux_sys_t & sys; }; /***************************************************************************** * definitions of structures and functions used by this plugins *****************************************************************************/ typedef struct { // ~mkv_track_t(); bool b_default; bool b_enabled; unsigned int i_number; int i_extra_data; uint8_t *p_extra_data; char *psz_codec; bool b_dts_only; bool b_pts_only; uint64_t i_default_duration; float f_timecodescale; mtime_t i_last_dts; /* video */ es_format_t fmt; float f_fps; es_out_id_t *p_es; /* audio */ unsigned int i_original_rate; bool b_inited; /* data to be send first */ int i_data_init; uint8_t *p_data_init; /* hack : it's for seek */ bool b_search_keyframe; bool b_silent; /* informative */ const char *psz_codec_name; const char *psz_codec_settings; const char *psz_codec_info_url; const char *psz_codec_download_url; /* encryption/compression */ int i_compression_type; KaxContentCompSettings *p_compression_data; } mkv_track_t; typedef struct { int i_track; int i_block_number; int64_t i_position; int64_t i_time; bool b_key; } mkv_index_t; #endif /* _MKV_HPP_ */ <commit_msg>the ID could be OK but the class mismatching<commit_after>/***************************************************************************** * mkv.cpp : matroska demuxer ***************************************************************************** * Copyright (C) 2003-2005, 2008 the VideoLAN team * $Id$ * * Authors: Laurent Aimar <fenrir@via.ecp.fr> * Steve Lhomme <steve.lhomme@free.fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifndef _MKV_H_ #define _MKV_H_ /***************************************************************************** * Preamble *****************************************************************************/ /* config.h may include inttypes.h, so make sure we define that option * early enough. */ #define __STDC_FORMAT_MACROS 1 #define __STDC_CONSTANT_MACROS 1 #define __STDC_LIMIT_MACROS 1 #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <inttypes.h> #include <vlc_common.h> #include <vlc_plugin.h> #ifdef HAVE_TIME_H # include <time.h> /* time() */ #endif #include <vlc_meta.h> #include <vlc_charset.h> #include <vlc_input.h> #include <vlc_demux.h> #include <iostream> #include <cassert> #include <typeinfo> #include <string> #include <vector> #include <algorithm> /* libebml and matroska */ #include "ebml/EbmlHead.h" #include "ebml/EbmlSubHead.h" #include "ebml/EbmlStream.h" #include "ebml/EbmlContexts.h" #include "ebml/EbmlVoid.h" #include "ebml/EbmlVersion.h" #include "ebml/StdIOCallback.h" #include "matroska/KaxAttachments.h" #include "matroska/KaxAttached.h" #include "matroska/KaxBlock.h" #include "matroska/KaxBlockData.h" #include "matroska/KaxChapters.h" #include "matroska/KaxCluster.h" #include "matroska/KaxClusterData.h" #include "matroska/KaxContexts.h" #include "matroska/KaxCues.h" #include "matroska/KaxCuesData.h" #include "matroska/KaxInfo.h" #include "matroska/KaxInfoData.h" #include "matroska/KaxSeekHead.h" #include "matroska/KaxSegment.h" #include "matroska/KaxTag.h" #include "matroska/KaxTags.h" #include "matroska/KaxTagMulti.h" #include "matroska/KaxTracks.h" #include "matroska/KaxTrackAudio.h" #include "matroska/KaxTrackVideo.h" #include "matroska/KaxTrackEntryData.h" #include "matroska/KaxContentEncoding.h" #include "matroska/KaxVersion.h" #include "ebml/StdIOCallback.h" #include <vlc_keys.h> extern "C" { #include "../mp4/libmp4.h" } #ifdef HAVE_ZLIB_H # include <zlib.h> #endif #define MKV_DEBUG 0 #define MATROSKA_COMPRESSION_NONE -1 #define MATROSKA_COMPRESSION_ZLIB 0 #define MATROSKA_COMPRESSION_BLIB 1 #define MATROSKA_COMPRESSION_LZOX 2 #define MATROSKA_COMPRESSION_HEADER 3 #define MKVD_TIMECODESCALE 1000000 #define MKV_IS_ID( el, C ) ( el != NULL && typeid( *el ) == typeid( C ) ) using namespace LIBMATROSKA_NAMESPACE; using namespace std; void BlockDecode( demux_t *p_demux, KaxBlock *block, KaxSimpleBlock *simpleblock, mtime_t i_pts, mtime_t i_duration, bool f_mandatory ); class attachment_c { public: attachment_c() :p_data(NULL) ,i_size(0) {} virtual ~attachment_c() { free( p_data ); } std::string psz_file_name; std::string psz_mime_type; void *p_data; int i_size; }; class matroska_segment_c; class matroska_stream_c { public: matroska_stream_c( demux_sys_t & demuxer ) :p_in(NULL) ,p_es(NULL) ,sys(demuxer) {} virtual ~matroska_stream_c() { delete p_in; delete p_es; } IOCallback *p_in; EbmlStream *p_es; std::vector<matroska_segment_c*> segments; demux_sys_t & sys; }; /***************************************************************************** * definitions of structures and functions used by this plugins *****************************************************************************/ typedef struct { // ~mkv_track_t(); bool b_default; bool b_enabled; unsigned int i_number; int i_extra_data; uint8_t *p_extra_data; char *psz_codec; bool b_dts_only; bool b_pts_only; uint64_t i_default_duration; float f_timecodescale; mtime_t i_last_dts; /* video */ es_format_t fmt; float f_fps; es_out_id_t *p_es; /* audio */ unsigned int i_original_rate; bool b_inited; /* data to be send first */ int i_data_init; uint8_t *p_data_init; /* hack : it's for seek */ bool b_search_keyframe; bool b_silent; /* informative */ const char *psz_codec_name; const char *psz_codec_settings; const char *psz_codec_info_url; const char *psz_codec_download_url; /* encryption/compression */ int i_compression_type; KaxContentCompSettings *p_compression_data; } mkv_track_t; typedef struct { int i_track; int i_block_number; int64_t i_position; int64_t i_time; bool b_key; } mkv_index_t; #endif /* _MKV_HPP_ */ <|endoftext|>
<commit_before>/*************************************************************************/ /* image_etc.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "image_etc.h" #include "Etc.h" #include "EtcFilter.h" #include "image.h" #include "os/copymem.h" #include "os/os.h" #include "print_string.h" static Image::Format _get_etc2_mode(Image::DetectChannels format) { switch (format) { case Image::DETECTED_R: return Image::FORMAT_ETC2_R11; case Image::DETECTED_RG: return Image::FORMAT_ETC2_RG11; case Image::DETECTED_RGB: return Image::FORMAT_ETC2_RGB8; default: return Image::FORMAT_ETC2_RGBA8; // TODO: would be nice if we could use FORMAT_ETC2_RGB8A1 for FORMAT_RGBA5551 } ERR_FAIL_COND_V(true, Image::FORMAT_MAX); } static Etc::Image::Format _image_format_to_etc2comp_format(Image::Format format) { switch (format) { case Image::FORMAT_ETC: return Etc::Image::Format::ETC1; case Image::FORMAT_ETC2_R11: return Etc::Image::Format::R11; case Image::FORMAT_ETC2_R11S: return Etc::Image::Format::SIGNED_R11; case Image::FORMAT_ETC2_RG11: return Etc::Image::Format::RG11; case Image::FORMAT_ETC2_RG11S: return Etc::Image::Format::SIGNED_RG11; case Image::FORMAT_ETC2_RGB8: return Etc::Image::Format::RGB8; case Image::FORMAT_ETC2_RGBA8: return Etc::Image::Format::RGBA8; case Image::FORMAT_ETC2_RGB8A1: return Etc::Image::Format::RGB8A1; } ERR_FAIL_COND_V(true, Etc::Image::Format::UNKNOWN); } static void _decompress_etc1(Image *p_img) { // not implemented, to be removed } static void _decompress_etc2(Image *p_img) { // not implemented, to be removed } static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_format, Image::CompressSource p_source) { Image::Format img_format = p_img->get_format(); Image::DetectChannels detected_channels = p_img->get_detected_channels(); if (p_source == Image::COMPRESS_SOURCE_SRGB && (detected_channels == Image::DETECTED_R || detected_channels == Image::DETECTED_RG)) { //R and RG do not support SRGB detected_channels = Image::DETECTED_RGB; } if (p_source == Image::COMPRESS_SOURCE_NORMAL) { //use RG channels only for normal detected_channels = Image::DETECTED_RG; } if (img_format >= Image::FORMAT_DXT1) { return; //do not compress, already compressed } if (img_format > Image::FORMAT_RGBA8) { // TODO: we should be able to handle FORMAT_RGBA4444 and FORMAT_RGBA5551 eventually return; } uint32_t imgw = p_img->get_width(), imgh = p_img->get_height(); ERR_FAIL_COND(next_power_of_2(imgw) != imgw || next_power_of_2(imgh) != imgh); Image::Format etc_format = force_etc1_format ? Image::FORMAT_ETC : _get_etc2_mode(detected_channels); Ref<Image> img = p_img->duplicate(); if (img->get_format() != Image::FORMAT_RGBA8) img->convert(Image::FORMAT_RGBA8); //still uses RGBA to convert PoolVector<uint8_t>::Read r = img->get_data().read(); int target_size = Image::get_image_data_size(imgw, imgh, etc_format, p_img->has_mipmaps() ? -1 : 0); int mmc = 1 + (p_img->has_mipmaps() ? Image::get_image_required_mipmaps(imgw, imgh, etc_format) : 0); PoolVector<uint8_t> dst_data; dst_data.resize(target_size); PoolVector<uint8_t>::Write w = dst_data.write(); // prepare parameters to be passed to etc2comp int num_cpus = OS::get_singleton()->get_processor_count(); int encoding_time = 0; float effort = 0.0; //default, reasonable time if (p_lossy_quality > 0.75) effort = 0.4; else if (p_lossy_quality > 0.85) effort = 0.6; else if (p_lossy_quality > 0.95) effort = 0.8; Etc::ErrorMetric error_metric = Etc::ErrorMetric::RGBX; // NOTE: we can experiment with other error metrics Etc::Image::Format etc2comp_etc_format = _image_format_to_etc2comp_format(etc_format); int wofs = 0; print_line("begin encoding, format: " + Image::get_format_name(etc_format)); uint64_t t = OS::get_singleton()->get_ticks_msec(); for (int i = 0; i < mmc; i++) { // convert source image to internal etc2comp format (which is equivalent to Image::FORMAT_RGBAF) // NOTE: We can alternatively add a case to Image::convert to handle Image::FORMAT_RGBAF conversion. int mipmap_ofs = 0, mipmap_size = 0, mipmap_w = 0, mipmap_h = 0; img->get_mipmap_offset_size_and_dimensions(i, mipmap_ofs, mipmap_size, mipmap_w, mipmap_h); const uint8_t *src = &r[mipmap_ofs]; Etc::ColorFloatRGBA *src_rgba_f = new Etc::ColorFloatRGBA[mipmap_w * mipmap_h]; for (int j = 0; j < mipmap_w * mipmap_h; j++) { int si = j * 4; // RGBA8 src_rgba_f[j] = Etc::ColorFloatRGBA::ConvertFromRGBA8(src[si], src[si + 1], src[si + 2], src[si + 3]); } unsigned char *etc_data = NULL; unsigned int etc_data_len = 0; unsigned int extended_width = 0, extended_height = 0; Etc::Encode((float *)src_rgba_f, mipmap_w, mipmap_h, etc2comp_etc_format, error_metric, effort, num_cpus, num_cpus, &etc_data, &etc_data_len, &extended_width, &extended_height, &encoding_time); CRASH_COND(wofs + etc_data_len > target_size); memcpy(&w[wofs], etc_data, etc_data_len); wofs += etc_data_len; delete[] etc_data; delete[] src_rgba_f; } print_line("time encoding: " + rtos(OS::get_singleton()->get_ticks_msec() - t)); p_img->create(imgw, imgh, p_img->has_mipmaps(), etc_format, dst_data); } static void _compress_etc1(Image *p_img, float p_lossy_quality) { _compress_etc(p_img, p_lossy_quality, true, Image::COMPRESS_SOURCE_GENERIC); } static void _compress_etc2(Image *p_img, float p_lossy_quality, Image::CompressSource p_source) { _compress_etc(p_img, p_lossy_quality, false, p_source); } void _register_etc_compress_func() { Image::_image_compress_etc1_func = _compress_etc1; //Image::_image_decompress_etc1 = _decompress_etc1; Image::_image_compress_etc2_func = _compress_etc2; //Image::_image_decompress_etc2 = _decompress_etc2; } <commit_msg>Properly resize textures so they can be ETC compressed, fixes #15139 this may make import times slower though, will have to wait for 3.1 for background texture import and compressonator.<commit_after>/*************************************************************************/ /* image_etc.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "image_etc.h" #include "Etc.h" #include "EtcFilter.h" #include "image.h" #include "os/copymem.h" #include "os/os.h" #include "print_string.h" static Image::Format _get_etc2_mode(Image::DetectChannels format) { switch (format) { case Image::DETECTED_R: return Image::FORMAT_ETC2_R11; case Image::DETECTED_RG: return Image::FORMAT_ETC2_RG11; case Image::DETECTED_RGB: return Image::FORMAT_ETC2_RGB8; default: return Image::FORMAT_ETC2_RGBA8; // TODO: would be nice if we could use FORMAT_ETC2_RGB8A1 for FORMAT_RGBA5551 } ERR_FAIL_COND_V(true, Image::FORMAT_MAX); } static Etc::Image::Format _image_format_to_etc2comp_format(Image::Format format) { switch (format) { case Image::FORMAT_ETC: return Etc::Image::Format::ETC1; case Image::FORMAT_ETC2_R11: return Etc::Image::Format::R11; case Image::FORMAT_ETC2_R11S: return Etc::Image::Format::SIGNED_R11; case Image::FORMAT_ETC2_RG11: return Etc::Image::Format::RG11; case Image::FORMAT_ETC2_RG11S: return Etc::Image::Format::SIGNED_RG11; case Image::FORMAT_ETC2_RGB8: return Etc::Image::Format::RGB8; case Image::FORMAT_ETC2_RGBA8: return Etc::Image::Format::RGBA8; case Image::FORMAT_ETC2_RGB8A1: return Etc::Image::Format::RGB8A1; } ERR_FAIL_COND_V(true, Etc::Image::Format::UNKNOWN); } static void _decompress_etc1(Image *p_img) { // not implemented, to be removed } static void _decompress_etc2(Image *p_img) { // not implemented, to be removed } static void _compress_etc(Image *p_img, float p_lossy_quality, bool force_etc1_format, Image::CompressSource p_source) { Image::Format img_format = p_img->get_format(); Image::DetectChannels detected_channels = p_img->get_detected_channels(); if (p_source == Image::COMPRESS_SOURCE_SRGB && (detected_channels == Image::DETECTED_R || detected_channels == Image::DETECTED_RG)) { //R and RG do not support SRGB detected_channels = Image::DETECTED_RGB; } if (p_source == Image::COMPRESS_SOURCE_NORMAL) { //use RG channels only for normal detected_channels = Image::DETECTED_RG; } if (img_format >= Image::FORMAT_DXT1) { return; //do not compress, already compressed } if (img_format > Image::FORMAT_RGBA8) { // TODO: we should be able to handle FORMAT_RGBA4444 and FORMAT_RGBA5551 eventually return; } uint32_t imgw = p_img->get_width(), imgh = p_img->get_height(); Image::Format etc_format = force_etc1_format ? Image::FORMAT_ETC : _get_etc2_mode(detected_channels); Ref<Image> img = p_img->duplicate(); if (img->get_format() != Image::FORMAT_RGBA8) img->convert(Image::FORMAT_RGBA8); //still uses RGBA to convert if (img->has_mipmaps()) { if (next_power_of_2(imgw) != imgw || next_power_of_2(imgh) != imgh) { img->resize_to_po2(); imgw = img->get_width(); imgh = img->get_height(); } } else { if (imgw % 4 != 0 || imgh % 4 != 0) { if (imgw % 4) { imgw += 4 - imgw % 4; } if (imgh % 4) { imgh += 4 - imgh % 4; } img->resize(imgw, imgh); } } PoolVector<uint8_t>::Read r = img->get_data().read(); int target_size = Image::get_image_data_size(imgw, imgh, etc_format, p_img->has_mipmaps() ? -1 : 0); int mmc = 1 + (p_img->has_mipmaps() ? Image::get_image_required_mipmaps(imgw, imgh, etc_format) : 0); PoolVector<uint8_t> dst_data; dst_data.resize(target_size); PoolVector<uint8_t>::Write w = dst_data.write(); // prepare parameters to be passed to etc2comp int num_cpus = OS::get_singleton()->get_processor_count(); int encoding_time = 0; float effort = 0.0; //default, reasonable time if (p_lossy_quality > 0.75) effort = 0.4; else if (p_lossy_quality > 0.85) effort = 0.6; else if (p_lossy_quality > 0.95) effort = 0.8; Etc::ErrorMetric error_metric = Etc::ErrorMetric::RGBX; // NOTE: we can experiment with other error metrics Etc::Image::Format etc2comp_etc_format = _image_format_to_etc2comp_format(etc_format); int wofs = 0; print_line("begin encoding, format: " + Image::get_format_name(etc_format)); uint64_t t = OS::get_singleton()->get_ticks_msec(); for (int i = 0; i < mmc; i++) { // convert source image to internal etc2comp format (which is equivalent to Image::FORMAT_RGBAF) // NOTE: We can alternatively add a case to Image::convert to handle Image::FORMAT_RGBAF conversion. int mipmap_ofs = 0, mipmap_size = 0, mipmap_w = 0, mipmap_h = 0; img->get_mipmap_offset_size_and_dimensions(i, mipmap_ofs, mipmap_size, mipmap_w, mipmap_h); const uint8_t *src = &r[mipmap_ofs]; Etc::ColorFloatRGBA *src_rgba_f = new Etc::ColorFloatRGBA[mipmap_w * mipmap_h]; for (int j = 0; j < mipmap_w * mipmap_h; j++) { int si = j * 4; // RGBA8 src_rgba_f[j] = Etc::ColorFloatRGBA::ConvertFromRGBA8(src[si], src[si + 1], src[si + 2], src[si + 3]); } unsigned char *etc_data = NULL; unsigned int etc_data_len = 0; unsigned int extended_width = 0, extended_height = 0; Etc::Encode((float *)src_rgba_f, mipmap_w, mipmap_h, etc2comp_etc_format, error_metric, effort, num_cpus, num_cpus, &etc_data, &etc_data_len, &extended_width, &extended_height, &encoding_time); CRASH_COND(wofs + etc_data_len > target_size); memcpy(&w[wofs], etc_data, etc_data_len); wofs += etc_data_len; delete[] etc_data; delete[] src_rgba_f; } print_line("time encoding: " + rtos(OS::get_singleton()->get_ticks_msec() - t)); p_img->create(imgw, imgh, p_img->has_mipmaps(), etc_format, dst_data); } static void _compress_etc1(Image *p_img, float p_lossy_quality) { _compress_etc(p_img, p_lossy_quality, true, Image::COMPRESS_SOURCE_GENERIC); } static void _compress_etc2(Image *p_img, float p_lossy_quality, Image::CompressSource p_source) { _compress_etc(p_img, p_lossy_quality, false, p_source); } void _register_etc_compress_func() { Image::_image_compress_etc1_func = _compress_etc1; //Image::_image_decompress_etc1 = _decompress_etc1; Image::_image_compress_etc2_func = _compress_etc2; //Image::_image_decompress_etc2 = _decompress_etc2; } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do // this #include <catch.hpp> #include <string> #include "inline_visitor/inline_visitor.h" using namespace std::string_literals; namespace { struct ShapeVisitor; struct Shape { virtual ~Shape() = default; virtual void Accept(ShapeVisitor &v) const = 0; }; struct Circle; struct Triangle; struct Square; struct ShapeVisitor { virtual ~ShapeVisitor() = default; virtual void Visit(const Circle &) = 0; virtual void Visit(const Triangle &) = 0; virtual void Visit(const Square &) = 0; }; struct Square : Shape { void Accept(ShapeVisitor &v) const final { v.Visit(*this); } }; struct Circle : Shape { void Accept(ShapeVisitor &v) const final { v.Visit(*this); } }; struct Triangle : Shape { void Accept(ShapeVisitor &v) const final { v.Visit(*this); } }; } // end namespace TEST_CASE("Inline visitor can identify all types", "[inline_visitor]") { int sides = 1; auto v = begin_visitor<ShapeVisitor>() .on<const Circle>([&sides](const Circle &) { sides = 1; }) .on<const Square>([&sides](const Square &) { sides = 4; }) .on<const Triangle>([&sides](const Triangle &) { sides = 3; }) .end_visitor(); Circle().Accept(v); REQUIRE(sides == 1); Square().Accept(v); REQUIRE(sides == 4); Triangle().Accept(v); REQUIRE(sides == 3); } <commit_msg>remove spurious partial comment<commit_after>#define CATCH_CONFIG_MAIN #include <catch.hpp> #include <string> #include "inline_visitor/inline_visitor.h" using namespace std::string_literals; namespace { struct ShapeVisitor; struct Shape { virtual ~Shape() = default; virtual void Accept(ShapeVisitor &v) const = 0; }; struct Circle; struct Triangle; struct Square; struct ShapeVisitor { virtual ~ShapeVisitor() = default; virtual void Visit(const Circle &) = 0; virtual void Visit(const Triangle &) = 0; virtual void Visit(const Square &) = 0; }; struct Square : Shape { void Accept(ShapeVisitor &v) const final { v.Visit(*this); } }; struct Circle : Shape { void Accept(ShapeVisitor &v) const final { v.Visit(*this); } }; struct Triangle : Shape { void Accept(ShapeVisitor &v) const final { v.Visit(*this); } }; } // end namespace TEST_CASE("Inline visitor can identify all types", "[inline_visitor]") { int sides = 1; auto v = begin_visitor<ShapeVisitor>() .on<const Circle>([&sides](const Circle &) { sides = 1; }) .on<const Square>([&sides](const Square &) { sides = 4; }) .on<const Triangle>([&sides](const Triangle &) { sides = 3; }) .end_visitor(); Circle().Accept(v); REQUIRE(sides == 1); Square().Accept(v); REQUIRE(sides == 4); Triangle().Accept(v); REQUIRE(sides == 3); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <gtest/gtest.h> #include "ssl_impl.h" #include "utilities.h" #include "testapp.h" static SSL_CTX *ssl_ctx = nullptr; static SSL *ssl = nullptr; static BIO *bio = nullptr; static BIO *ssl_bio_r = nullptr; static BIO *ssl_bio_w = nullptr; SOCKET create_connect_ssl_socket(in_port_t port) { char port_str[32]; snprintf(port_str, 32, "%d", port); ssl_ctx = nullptr; EXPECT_EQ(nullptr, bio); EXPECT_EQ(0, create_ssl_connection(&ssl_ctx, &bio, "127.0.0.1", port_str, NULL, NULL, 1)); /* SSL "trickery". To ensure we have full control over send/receive of data. create_ssl_connection will have negotiated the SSL connection, now: 1. steal the underlying FD 2. Switch out the BIO_ssl_connect BIO for a plain memory BIO Now send/receive is done under our control. byte by byte, large chunks etc... */ int sfd = BIO_get_fd(bio, NULL); BIO_get_ssl(bio, &ssl); EXPECT_EQ(nullptr, ssl_bio_r); ssl_bio_r = BIO_new(BIO_s_mem()); EXPECT_EQ(nullptr, ssl_bio_w); ssl_bio_w = BIO_new(BIO_s_mem()); // Note: previous BIOs attached to 'bio' freed as a result of this call. SSL_set_bio(ssl, ssl_bio_r, ssl_bio_w); return sfd; } void destroy_ssl_socket() { BIO_free_all(bio); bio = nullptr; ssl_bio_r = nullptr; ssl_bio_w = nullptr; SSL_CTX_free(ssl_ctx); ssl_ctx = nullptr; if (sock_ssl != INVALID_SOCKET) { closesocket(sock_ssl); sock_ssl = INVALID_SOCKET; } } void reset_bio_mem() { ssl_bio_r = nullptr; ssl_bio_w = nullptr; if (bio) { BIO_free_all(bio); bio = nullptr; } } ssize_t phase_send_ssl(const void *buf, size_t len) { ssize_t rv = 0, send_rv = 0; long send_len = 0; char* send_buf = NULL; /* push the data through SSL into the BIO */ rv = (ssize_t)SSL_write(ssl, (const char*)buf, (int)len); send_len = BIO_get_mem_data(ssl_bio_w, &send_buf); send_rv = socket_send(sock_ssl, send_buf, send_len); if (send_rv > 0) { EXPECT_EQ(send_len, send_rv); (void)BIO_reset(ssl_bio_w); } else { /* flag failure to user */ rv = send_rv; } return rv; } ssize_t phase_recv_ssl(void* buf, size_t len) { ssize_t rv; /* can we read some data? */ while ((rv = SSL_peek(ssl, buf, (int)len)) == -1) { /* nope, keep feeding SSL until we can */ rv = socket_recv(sock_ssl, reinterpret_cast<char*>(buf), len); if (rv > 0) { /* write into the BIO what came off the network */ BIO_write(ssl_bio_r, buf, rv); } else if (rv == 0) { return rv; /* peer closed */ } } /* now pull the data out and return */ return SSL_read(ssl, buf, (int)len); } <commit_msg>MB-24567: Check for success connect over SSL in testapp<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <gtest/gtest.h> #include "ssl_impl.h" #include "utilities.h" #include "testapp.h" static SSL_CTX *ssl_ctx = nullptr; static SSL *ssl = nullptr; static BIO *bio = nullptr; static BIO *ssl_bio_r = nullptr; static BIO *ssl_bio_w = nullptr; SOCKET create_connect_ssl_socket(in_port_t port) { char port_str[32]; snprintf(port_str, 32, "%d", port); ssl_ctx = nullptr; EXPECT_EQ(nullptr, bio); if (create_ssl_connection(&ssl_ctx, &bio, "127.0.0.1", port_str, NULL, NULL, 1) != 0) { ADD_FAILURE() << "Failed to connect over ssl to port: " << port; return INVALID_SOCKET; } /* SSL "trickery". To ensure we have full control over send/receive of data. create_ssl_connection will have negotiated the SSL connection, now: 1. steal the underlying FD 2. Switch out the BIO_ssl_connect BIO for a plain memory BIO Now send/receive is done under our control. byte by byte, large chunks etc... */ int sfd = BIO_get_fd(bio, NULL); BIO_get_ssl(bio, &ssl); EXPECT_EQ(nullptr, ssl_bio_r); ssl_bio_r = BIO_new(BIO_s_mem()); EXPECT_EQ(nullptr, ssl_bio_w); ssl_bio_w = BIO_new(BIO_s_mem()); // Note: previous BIOs attached to 'bio' freed as a result of this call. SSL_set_bio(ssl, ssl_bio_r, ssl_bio_w); return sfd; } void destroy_ssl_socket() { BIO_free_all(bio); bio = nullptr; ssl_bio_r = nullptr; ssl_bio_w = nullptr; SSL_CTX_free(ssl_ctx); ssl_ctx = nullptr; if (sock_ssl != INVALID_SOCKET) { closesocket(sock_ssl); sock_ssl = INVALID_SOCKET; } } void reset_bio_mem() { ssl_bio_r = nullptr; ssl_bio_w = nullptr; if (bio) { BIO_free_all(bio); bio = nullptr; } } ssize_t phase_send_ssl(const void *buf, size_t len) { ssize_t rv = 0, send_rv = 0; long send_len = 0; char* send_buf = NULL; /* push the data through SSL into the BIO */ rv = (ssize_t)SSL_write(ssl, (const char*)buf, (int)len); send_len = BIO_get_mem_data(ssl_bio_w, &send_buf); send_rv = socket_send(sock_ssl, send_buf, send_len); if (send_rv > 0) { EXPECT_EQ(send_len, send_rv); (void)BIO_reset(ssl_bio_w); } else { /* flag failure to user */ rv = send_rv; } return rv; } ssize_t phase_recv_ssl(void* buf, size_t len) { ssize_t rv; /* can we read some data? */ while ((rv = SSL_peek(ssl, buf, (int)len)) == -1) { /* nope, keep feeding SSL until we can */ rv = socket_recv(sock_ssl, reinterpret_cast<char*>(buf), len); if (rv > 0) { /* write into the BIO what came off the network */ BIO_write(ssl_bio_r, buf, rv); } else if (rv == 0) { return rv; /* peer closed */ } } /* now pull the data out and return */ return SSL_read(ssl, buf, (int)len); } <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "catch.hpp" #include "mfem.hpp" #include <fstream> #include <iostream> #include "../../../fem/libceed/ceed.hpp" using namespace mfem; namespace ceed_test { double coeff_function(const Vector &x) { return 1.0 + x[0]*x[0]; } static std::string getString(AssemblyLevel assembly) { switch (assembly) { case AssemblyLevel::NONE: return "NONE"; break; case AssemblyLevel::PARTIAL: return "PARTIAL"; break; case AssemblyLevel::ELEMENT: return "ELEMENT"; break; case AssemblyLevel::FULL: return "FULL"; break; case AssemblyLevel::LEGACYFULL: return "LEGACYFULL"; break; } mfem_error("Unknown AssemblyLevel."); return ""; } static std::string getString(CeedCoeff coeff_type) { switch (coeff_type) { case CeedCoeff::Const: return "Const"; break; case CeedCoeff::Grid: return "Grid"; break; case CeedCoeff::Quad: return "Quad"; break; } mfem_error("Unknown CeedCoeff."); return ""; } enum class Problem {Mass, Diffusion, VectorMass, VectorDiffusion}; static std::string getString(Problem pb) { switch (pb) { case Problem::Mass: return "Mass"; break; case Problem::Diffusion: return "Diffusion"; break; case Problem::VectorMass: return "VectorMass"; break; case Problem::VectorDiffusion: return "VectorDiffusion"; break; } mfem_error("Unknown Problem."); return ""; } void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type, const Problem pb, const AssemblyLevel assembly) { std::string section = "assembly: " + getString(assembly) + "\n" + "coeff_type: " + getString(coeff_type) + "\n" + "pb: " + getString(pb) + "\n" + "order: " + std::to_string(order) + "\n" + "mesh: " + input; INFO(section); Mesh mesh(input, 1, 1); mesh.EnsureNodes(); int dim = mesh.Dimension(); H1_FECollection fec(order, dim); bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion; const int vdim = vecOp ? dim : 1; FiniteElementSpace fes(&mesh, &fec, vdim); BilinearForm k_test(&fes); BilinearForm k_ref(&fes); FiniteElementSpace coeff_fes(&mesh, &fec); GridFunction gf(&coeff_fes); FunctionCoefficient f_coeff(coeff_function); Coefficient *coeff = nullptr; switch (coeff_type) { case CeedCoeff::Const: coeff = new ConstantCoefficient(1.0); break; case CeedCoeff::Grid: gf.ProjectCoefficient(f_coeff); coeff = new GridFunctionCoefficient(&gf); break; case CeedCoeff::Quad: coeff = &f_coeff; break; } switch (pb) { case Problem::Mass: k_ref.AddDomainIntegrator(new MassIntegrator(*coeff)); k_test.AddDomainIntegrator(new MassIntegrator(*coeff)); break; case Problem::Diffusion: k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); break; case Problem::VectorMass: k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff)); k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff)); break; case Problem::VectorDiffusion: k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff)); k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff)); break; } k_ref.Assemble(); k_ref.Finalize(); k_test.SetAssemblyLevel(assembly); k_test.Assemble(); GridFunction x(&fes), y_ref(&fes), y_test(&fes); x.Randomize(1); k_ref.Mult(x,y_ref); k_test.Mult(x,y_test); y_test -= y_ref; REQUIRE(y_test.Norml2() < 1.e-12); } TEST_CASE("CEED", "[CEED]") { auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE); auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad); auto pb = GENERATE(Problem::Mass,Problem::Diffusion, Problem::VectorMass,Problem::VectorDiffusion); auto order = GENERATE(1,2,3); auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh", "../../data/periodic-square.mesh", "../../data/star-q2.mesh","../../data/fichera-q2.mesh", "../../data/amr-quad.mesh","../../data/fichera-amr.mesh"); test_ceed_operator(mesh, order, coeff_type, pb, assembly); } // test case } // namespace ceed_test <commit_msg>Create FunctionCoefficient only when needed.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "catch.hpp" #include "mfem.hpp" #include <fstream> #include <iostream> #include "../../../fem/libceed/ceed.hpp" using namespace mfem; namespace ceed_test { double coeff_function(const Vector &x) { return 1.0 + x[0]*x[0]; } static std::string getString(AssemblyLevel assembly) { switch (assembly) { case AssemblyLevel::NONE: return "NONE"; break; case AssemblyLevel::PARTIAL: return "PARTIAL"; break; case AssemblyLevel::ELEMENT: return "ELEMENT"; break; case AssemblyLevel::FULL: return "FULL"; break; case AssemblyLevel::LEGACYFULL: return "LEGACYFULL"; break; } mfem_error("Unknown AssemblyLevel."); return ""; } static std::string getString(CeedCoeff coeff_type) { switch (coeff_type) { case CeedCoeff::Const: return "Const"; break; case CeedCoeff::Grid: return "Grid"; break; case CeedCoeff::Quad: return "Quad"; break; } mfem_error("Unknown CeedCoeff."); return ""; } enum class Problem {Mass, Diffusion, VectorMass, VectorDiffusion}; static std::string getString(Problem pb) { switch (pb) { case Problem::Mass: return "Mass"; break; case Problem::Diffusion: return "Diffusion"; break; case Problem::VectorMass: return "VectorMass"; break; case Problem::VectorDiffusion: return "VectorDiffusion"; break; } mfem_error("Unknown Problem."); return ""; } void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type, const Problem pb, const AssemblyLevel assembly) { std::string section = "assembly: " + getString(assembly) + "\n" + "coeff_type: " + getString(coeff_type) + "\n" + "pb: " + getString(pb) + "\n" + "order: " + std::to_string(order) + "\n" + "mesh: " + input; INFO(section); Mesh mesh(input, 1, 1); mesh.EnsureNodes(); int dim = mesh.Dimension(); H1_FECollection fec(order, dim); bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion; const int vdim = vecOp ? dim : 1; FiniteElementSpace fes(&mesh, &fec, vdim); BilinearForm k_test(&fes); BilinearForm k_ref(&fes); FiniteElementSpace coeff_fes(&mesh, &fec); GridFunction gf(&coeff_fes); Coefficient *coeff = nullptr; switch (coeff_type) { case CeedCoeff::Const: coeff = new ConstantCoefficient(1.0); break; case CeedCoeff::Grid: { FunctionCoefficient f_coeff(coeff_function);; gf.ProjectCoefficient(f_coeff); coeff = new GridFunctionCoefficient(&gf); break; } case CeedCoeff::Quad: coeff = new FunctionCoefficient(coeff_function);; break; } switch (pb) { case Problem::Mass: k_ref.AddDomainIntegrator(new MassIntegrator(*coeff)); k_test.AddDomainIntegrator(new MassIntegrator(*coeff)); break; case Problem::Diffusion: k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); break; case Problem::VectorMass: k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff)); k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff)); break; case Problem::VectorDiffusion: k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff)); k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff)); break; } k_ref.Assemble(); k_ref.Finalize(); k_test.SetAssemblyLevel(assembly); k_test.Assemble(); GridFunction x(&fes), y_ref(&fes), y_test(&fes); x.Randomize(1); k_ref.Mult(x,y_ref); k_test.Mult(x,y_test); y_test -= y_ref; REQUIRE(y_test.Norml2() < 1.e-12); } TEST_CASE("CEED", "[CEED]") { auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE); auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad); auto pb = GENERATE(Problem::Mass,Problem::Diffusion, Problem::VectorMass,Problem::VectorDiffusion); auto order = GENERATE(1,2,3); auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh", "../../data/periodic-square.mesh", "../../data/star-q2.mesh","../../data/fichera-q2.mesh", "../../data/amr-quad.mesh","../../data/fichera-amr.mesh"); test_ceed_operator(mesh, order, coeff_type, pb, assembly); } // test case } // namespace ceed_test <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: terminate.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_testshl2.hxx" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #ifdef SOLARIS #include <sys/time.h> #include <sys/types.h> #endif #include <signal.h> #include <iostream> #include <string> #include "testshl/getopt.hxx" #if (defined UNX) || (defined OS2) #include <unistd.h> /* usleep */ #include <sys/types.h> #include <signal.h> #endif #ifdef WNT # include "testshl/winstuff.hxx" #endif using namespace std; // ----------------------------------------------------------------------------- class ProcessHandler { std::string m_sProcessIDFilename; int m_nPID; int getPID(); int readPIDFromFile(); void sendSignal(int _nPID); void write(int); public: ProcessHandler(); void setName(std::string const& _sFilename); ~ProcessHandler(); void waitForPIDFile(int); void waitForTimeout(int); }; void my_sleep(int sec) { #ifdef WNT WinSleep(sec * 1000); #else usleep(sec * 1000000); // 10 ms #endif } // ------------------------------- ProcessHelper ------------------------------- ProcessHandler::ProcessHandler():m_nPID(0) {} void ProcessHandler::setName(std::string const& _sPIDFilename) { m_sProcessIDFilename = _sPIDFilename; } int ProcessHandler::getPID() { return m_nPID; } int ProcessHandler::readPIDFromFile() { // get own PID int nPID = 0; if (m_sProcessIDFilename.size() > 0) { FILE* in; in = fopen(m_sProcessIDFilename.c_str(), "r"); if (!in) { // fprintf(stderr, "warning: (testshl.cxx) can't read own pid.\n"); return 0; // exit(0); } // if file exist, wait short, maybe the other tool writes it down. if (fscanf(in, "%d", &nPID) != 1) { // fprintf(stderr, "warning: (testshl.cxx) can't read own pid.\n"); return 0; // exit(0); } fclose(in); } else { fprintf(stderr, "error: (terminate.cxx) PID Filename empty, must set.\n"); exit(0); } return nPID; } ProcessHandler::~ProcessHandler() { } void ProcessHandler::sendSignal(int _nPID) { if (_nPID != 0) { #ifdef WNT WinTerminateApp(_nPID, 100); #else kill(_nPID, SIGKILL); #endif } } // ----------------------------------------------------------------------------- void ProcessHandler::waitForPIDFile(int _nTimeout) { int nWaitforTimeout = _nTimeout; while (getPID() == 0 && nWaitforTimeout > 0) { int nPID = readPIDFromFile(); if (nPID != 0) { m_nPID = nPID; break; } my_sleep(1); fprintf(stderr, "wait for pid file\n"); nWaitforTimeout--; } if (nWaitforTimeout <= 0) { fprintf(stderr, "No PID found, time runs out\n"); exit(1); } } // ----------------------------------------------------------------------------- void ProcessHandler::waitForTimeout(int _nTimeout) { int nTimeout = _nTimeout; while (nTimeout > 0) { my_sleep(1); fprintf(stderr, "%d \r", nTimeout); int nNewPID = readPIDFromFile(); if ( nNewPID != getPID() ) { fprintf(stderr, "PID has changed.\n"); if ( nNewPID != 0) { fprintf(stderr, "new PID is not 0, maybe forgotten to delete old PID file, restart timeout.\n"); m_nPID = nNewPID; nTimeout = _nTimeout; } else { break; } } nTimeout --; } if (nTimeout <= 0) { fprintf(stderr, "PID: %d\n", getPID()); sendSignal(getPID()); write(0); } } void ProcessHandler::write(int _nPID) { // get own PID if (m_sProcessIDFilename.size() > 0) { FILE* out; out = fopen(m_sProcessIDFilename.c_str(), "w"); if (!out) { fprintf(stderr, "warning: (testshl.cxx) can't write own pid.\n"); return; // exit(0); } fprintf(out, "%d", _nPID); fclose(out); } else { fprintf(stderr, "warning: (testshl.cxx) PID Filename empty, must set.\n"); } } // ----------------------------------- Main ----------------------------------- #if (defined UNX) || (defined OS2) int main( int, char* argv[] ) #else int _cdecl main( int, char* argv[] ) #endif { static char const * optionSet[] = { "-version, shows current program version and exit.", "-pid=s, write current process id to file", "-time=s, timeout [default is 10 sec]", "-h:s, display help or help on option", "-help:s, see -h", NULL }; ProcessHandler aCurrentProcess; GetOpt opt( argv, optionSet ); if ( opt.hasOpt("-pid") ) { aCurrentProcess.setName(opt.getOpt("-pid").getStr()); } int nTimeout = 10; if ( opt.hasOpt("-time")) { // nTimeout = opt.getOpt("-time").toInt32(); if (nTimeout == 0) { nTimeout = 10; } } if ( opt.hasOpt("-version") ) { fprintf(stderr, "testshl2_timeout $Revision: 1.9 $\n"); exit(0); } // someone indicates that he needs help if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) ) { opt.showUsage(); exit(0); } // wait until pid file exist ============================== aCurrentProcess.waitForPIDFile(10); printf("Found PID file, wait for timeout %d sec.\n", nTimeout); // timeout ================================================== aCurrentProcess.waitForTimeout(nTimeout); return 0; } <commit_msg>#cmcfixes65: #i106455# fix fortify warnings<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: terminate.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_testshl2.hxx" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #ifdef SOLARIS #include <sys/time.h> #include <sys/types.h> #endif #include <signal.h> #include <iostream> #include <string> #include "testshl/getopt.hxx" #if (defined UNX) || (defined OS2) #include <unistd.h> /* usleep */ #include <sys/types.h> #include <signal.h> #endif #ifdef WNT # include "testshl/winstuff.hxx" #endif using namespace std; // ----------------------------------------------------------------------------- class ProcessHandler { std::string m_sProcessIDFilename; int m_nPID; int getPID(); int readPIDFromFile(); void sendSignal(int _nPID); void write(int); public: ProcessHandler(); void setName(std::string const& _sFilename); ~ProcessHandler(); void waitForPIDFile(int); void waitForTimeout(int); }; void my_sleep(int sec) { #ifdef WNT WinSleep(sec * 1000); #else usleep(sec * 1000000); // 10 ms #endif } // ------------------------------- ProcessHelper ------------------------------- ProcessHandler::ProcessHandler():m_nPID(0) {} void ProcessHandler::setName(std::string const& _sPIDFilename) { m_sProcessIDFilename = _sPIDFilename; } int ProcessHandler::getPID() { return m_nPID; } int ProcessHandler::readPIDFromFile() { // get own PID int nPID = 0; if (m_sProcessIDFilename.size() > 0) { FILE* in; in = fopen(m_sProcessIDFilename.c_str(), "r"); if (!in) { // fprintf(stderr, "warning: (testshl.cxx) can't read own pid.\n"); return 0; // exit(0); } // if file exist, wait short, maybe the other tool writes it down. if (fscanf(in, "%d", &nPID) != 1) { // fprintf(stderr, "warning: (testshl.cxx) can't read own pid.\n"); fclose(in); return 0; // exit(0); } fclose(in); } else { fprintf(stderr, "error: (terminate.cxx) PID Filename empty, must set.\n"); exit(0); } return nPID; } ProcessHandler::~ProcessHandler() { } void ProcessHandler::sendSignal(int _nPID) { if (_nPID != 0) { #ifdef WNT WinTerminateApp(_nPID, 100); #else kill(_nPID, SIGKILL); #endif } } // ----------------------------------------------------------------------------- void ProcessHandler::waitForPIDFile(int _nTimeout) { int nWaitforTimeout = _nTimeout; while (getPID() == 0 && nWaitforTimeout > 0) { int nPID = readPIDFromFile(); if (nPID != 0) { m_nPID = nPID; break; } my_sleep(1); fprintf(stderr, "wait for pid file\n"); nWaitforTimeout--; } if (nWaitforTimeout <= 0) { fprintf(stderr, "No PID found, time runs out\n"); exit(1); } } // ----------------------------------------------------------------------------- void ProcessHandler::waitForTimeout(int _nTimeout) { int nTimeout = _nTimeout; while (nTimeout > 0) { my_sleep(1); fprintf(stderr, "%d \r", nTimeout); int nNewPID = readPIDFromFile(); if ( nNewPID != getPID() ) { fprintf(stderr, "PID has changed.\n"); if ( nNewPID != 0) { fprintf(stderr, "new PID is not 0, maybe forgotten to delete old PID file, restart timeout.\n"); m_nPID = nNewPID; nTimeout = _nTimeout; } else { break; } } nTimeout --; } if (nTimeout <= 0) { fprintf(stderr, "PID: %d\n", getPID()); sendSignal(getPID()); write(0); } } void ProcessHandler::write(int _nPID) { // get own PID if (m_sProcessIDFilename.size() > 0) { FILE* out; out = fopen(m_sProcessIDFilename.c_str(), "w"); if (!out) { fprintf(stderr, "warning: (testshl.cxx) can't write own pid.\n"); return; // exit(0); } fprintf(out, "%d", _nPID); fclose(out); } else { fprintf(stderr, "warning: (testshl.cxx) PID Filename empty, must set.\n"); } } // ----------------------------------- Main ----------------------------------- #if (defined UNX) || (defined OS2) int main( int, char* argv[] ) #else int _cdecl main( int, char* argv[] ) #endif { static char const * optionSet[] = { "-version, shows current program version and exit.", "-pid=s, write current process id to file", "-time=s, timeout [default is 10 sec]", "-h:s, display help or help on option", "-help:s, see -h", NULL }; ProcessHandler aCurrentProcess; GetOpt opt( argv, optionSet ); if ( opt.hasOpt("-pid") ) { aCurrentProcess.setName(opt.getOpt("-pid").getStr()); } int nTimeout = 10; if ( opt.hasOpt("-time")) { // nTimeout = opt.getOpt("-time").toInt32(); if (nTimeout == 0) { nTimeout = 10; } } if ( opt.hasOpt("-version") ) { fprintf(stderr, "testshl2_timeout $Revision: 1.9 $\n"); exit(0); } // someone indicates that he needs help if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) ) { opt.showUsage(); exit(0); } // wait until pid file exist ============================== aCurrentProcess.waitForPIDFile(10); printf("Found PID file, wait for timeout %d sec.\n", nTimeout); // timeout ================================================== aCurrentProcess.waitForTimeout(nTimeout); return 0; } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "EditOperatorDialog.h" #include "DataSource.h" #include "EditOperatorWidget.h" #include "Operator.h" #include <pqApplicationCore.h> #include <pqPythonSyntaxHighlighter.h> #include <pqSettings.h> #include <QDebug> #include <QDialogButtonBox> #include <QMessageBox> #include <QPointer> #include <QPushButton> #include <QVBoxLayout> #include <QVariant> namespace tomviz { class EditOperatorDialog::EODInternals { public: QPointer<Operator> Op; EditOperatorWidget* Widget; bool needsToBeAdded; DataSource* dataSource; void saveGeometry(const QRect& geometry) { if (Op.isNull()) { return; } QSettings* settings = pqApplicationCore::instance()->settings(); QString settingName = QString("Edit%1OperatorDialogGeometry").arg(Op->label()); settings->setValue(settingName, QVariant(geometry)); } QVariant loadGeometry() { if (Op.isNull()) { return QVariant(); } QSettings* settings = pqApplicationCore::instance()->settings(); QString settingName = QString("Edit%1OperatorDialogGeometry").arg(Op->label()); return settings->value(settingName); } }; EditOperatorDialog::EditOperatorDialog(Operator* op, DataSource* dataSource, bool needToAddOperator, QWidget* p) : Superclass(p), Internals(new EditOperatorDialog::EODInternals()) { Q_ASSERT(op); this->Internals->Op = op; this->Internals->dataSource = dataSource; this->Internals->needsToBeAdded = needToAddOperator; if (needToAddOperator) { op->setParent(this); } QVariant geometry = this->Internals->loadGeometry(); if (!geometry.isNull()) { this->setGeometry(geometry.toRect()); } if (op->hasCustomUI()) { EditOperatorWidget* opWidget = op->getEditorContents(this); if (opWidget != nullptr) { this->setupUI(opWidget); } // We need the image data for call the datasource to run the pipeline else { DataSource::ImageFuture* future = dataSource->getCopyOfImagePriorTo(op); connect(future, SIGNAL(finished(bool)), this, SLOT(getCopyOfImagePriorToFinished(bool))); } } else { this->setupUI(); } } EditOperatorDialog::~EditOperatorDialog() { } Operator* EditOperatorDialog::op() { return this->Internals->Op; } void EditOperatorDialog::onApply() { if (this->Internals->Op.isNull()) { return; } if (this->Internals->Widget) { // If we are modifying an operator that is already part of a pipeline and // the pipeline is running it has to cancel the currently running pipeline first. // Warn the user rather that just canceling potentially long-running operations. if (this->Internals->dataSource->isRunningAnOperator() && !this->Internals->needsToBeAdded) { auto result = QMessageBox::question(this, "Cancel running operation?", "Applying changes to an opertor that is part of a running pipeline will cancel the current running operator and restart the pipeline run. Proceed anyway?"); if (result == QMessageBox::No) { return; } else { this->Internals->dataSource->cancelPipeline(); } } this->Internals->Widget->applyChangesToOperator(); } if (this->Internals->needsToBeAdded) { this->Internals->dataSource->addOperator(this->Internals->Op); this->Internals->needsToBeAdded = false; } } void EditOperatorDialog::onClose() { this->Internals->saveGeometry(this->geometry()); } void EditOperatorDialog::setupUI(EditOperatorWidget* opWidget) { if (this->Internals->Op.isNull()) { return; } QVBoxLayout* vLayout = new QVBoxLayout(this); vLayout->setContentsMargins(5, 5, 5, 5); vLayout->setSpacing(5); if (this->Internals->Op->hasCustomUI()) { vLayout->addWidget(opWidget); this->Internals->Widget = opWidget; const double* dsPosition = this->Internals->dataSource->displayPosition(); opWidget->dataSourceMoved(dsPosition[0], dsPosition[1], dsPosition[2]); QObject::connect(this->Internals->dataSource, &DataSource::displayPositionChanged, opWidget, &EditOperatorWidget::dataSourceMoved); } else { this->Internals->Widget = nullptr; } QDialogButtonBox* dialogButtons = new QDialogButtonBox( QDialogButtonBox::Apply | QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this); vLayout->addWidget(dialogButtons); dialogButtons->button(QDialogButtonBox::Ok)->setDefault(false); this->setLayout(vLayout); this->connect(dialogButtons, SIGNAL(accepted()), SLOT(accept())); this->connect(dialogButtons, SIGNAL(rejected()), SLOT(reject())); this->connect(dialogButtons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApply())); this->connect(this, SIGNAL(accepted()), SLOT(onApply())); this->connect(this, SIGNAL(accepted()), SLOT(onClose())); this->connect(this, SIGNAL(rejected()), SLOT(onClose())); } void EditOperatorDialog::getCopyOfImagePriorToFinished(bool result) { if (this->Internals->Op.isNull()) { return; } DataSource::ImageFuture* future = qobject_cast<DataSource::ImageFuture*>(this->sender()); if (result) { auto opWidget = this->Internals->Op->getEditorContentsWithData(this, future->result()); this->setupUI(opWidget); } else { qWarning() << "Error occured running operators."; } future->deleteLater(); } } <commit_msg>Fix type opertor => operator<commit_after>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "EditOperatorDialog.h" #include "DataSource.h" #include "EditOperatorWidget.h" #include "Operator.h" #include <pqApplicationCore.h> #include <pqPythonSyntaxHighlighter.h> #include <pqSettings.h> #include <QDebug> #include <QDialogButtonBox> #include <QMessageBox> #include <QPointer> #include <QPushButton> #include <QVBoxLayout> #include <QVariant> namespace tomviz { class EditOperatorDialog::EODInternals { public: QPointer<Operator> Op; EditOperatorWidget* Widget; bool needsToBeAdded; DataSource* dataSource; void saveGeometry(const QRect& geometry) { if (Op.isNull()) { return; } QSettings* settings = pqApplicationCore::instance()->settings(); QString settingName = QString("Edit%1OperatorDialogGeometry").arg(Op->label()); settings->setValue(settingName, QVariant(geometry)); } QVariant loadGeometry() { if (Op.isNull()) { return QVariant(); } QSettings* settings = pqApplicationCore::instance()->settings(); QString settingName = QString("Edit%1OperatorDialogGeometry").arg(Op->label()); return settings->value(settingName); } }; EditOperatorDialog::EditOperatorDialog(Operator* op, DataSource* dataSource, bool needToAddOperator, QWidget* p) : Superclass(p), Internals(new EditOperatorDialog::EODInternals()) { Q_ASSERT(op); this->Internals->Op = op; this->Internals->dataSource = dataSource; this->Internals->needsToBeAdded = needToAddOperator; if (needToAddOperator) { op->setParent(this); } QVariant geometry = this->Internals->loadGeometry(); if (!geometry.isNull()) { this->setGeometry(geometry.toRect()); } if (op->hasCustomUI()) { EditOperatorWidget* opWidget = op->getEditorContents(this); if (opWidget != nullptr) { this->setupUI(opWidget); } // We need the image data for call the datasource to run the pipeline else { DataSource::ImageFuture* future = dataSource->getCopyOfImagePriorTo(op); connect(future, SIGNAL(finished(bool)), this, SLOT(getCopyOfImagePriorToFinished(bool))); } } else { this->setupUI(); } } EditOperatorDialog::~EditOperatorDialog() { } Operator* EditOperatorDialog::op() { return this->Internals->Op; } void EditOperatorDialog::onApply() { if (this->Internals->Op.isNull()) { return; } if (this->Internals->Widget) { // If we are modifying an operator that is already part of a pipeline and // the pipeline is running it has to cancel the currently running pipeline first. // Warn the user rather that just canceling potentially long-running operations. if (this->Internals->dataSource->isRunningAnOperator() && !this->Internals->needsToBeAdded) { auto result = QMessageBox::question(this, "Cancel running operation?", "Applying changes to an operator that is part of a running pipeline will cancel the current running operator and restart the pipeline run. Proceed anyway?"); if (result == QMessageBox::No) { return; } else { this->Internals->dataSource->cancelPipeline(); } } this->Internals->Widget->applyChangesToOperator(); } if (this->Internals->needsToBeAdded) { this->Internals->dataSource->addOperator(this->Internals->Op); this->Internals->needsToBeAdded = false; } } void EditOperatorDialog::onClose() { this->Internals->saveGeometry(this->geometry()); } void EditOperatorDialog::setupUI(EditOperatorWidget* opWidget) { if (this->Internals->Op.isNull()) { return; } QVBoxLayout* vLayout = new QVBoxLayout(this); vLayout->setContentsMargins(5, 5, 5, 5); vLayout->setSpacing(5); if (this->Internals->Op->hasCustomUI()) { vLayout->addWidget(opWidget); this->Internals->Widget = opWidget; const double* dsPosition = this->Internals->dataSource->displayPosition(); opWidget->dataSourceMoved(dsPosition[0], dsPosition[1], dsPosition[2]); QObject::connect(this->Internals->dataSource, &DataSource::displayPositionChanged, opWidget, &EditOperatorWidget::dataSourceMoved); } else { this->Internals->Widget = nullptr; } QDialogButtonBox* dialogButtons = new QDialogButtonBox( QDialogButtonBox::Apply | QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this); vLayout->addWidget(dialogButtons); dialogButtons->button(QDialogButtonBox::Ok)->setDefault(false); this->setLayout(vLayout); this->connect(dialogButtons, SIGNAL(accepted()), SLOT(accept())); this->connect(dialogButtons, SIGNAL(rejected()), SLOT(reject())); this->connect(dialogButtons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApply())); this->connect(this, SIGNAL(accepted()), SLOT(onApply())); this->connect(this, SIGNAL(accepted()), SLOT(onClose())); this->connect(this, SIGNAL(rejected()), SLOT(onClose())); } void EditOperatorDialog::getCopyOfImagePriorToFinished(bool result) { if (this->Internals->Op.isNull()) { return; } DataSource::ImageFuture* future = qobject_cast<DataSource::ImageFuture*>(this->sender()); if (result) { auto opWidget = this->Internals->Op->getEditorContentsWithData(this, future->result()); this->setupUI(opWidget); } else { qWarning() << "Error occured running operators."; } future->deleteLater(); } } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "EditOperatorDialog.h" #include "DataSource.h" #include "EditOperatorWidget.h" #include "Operator.h" #include "pqApplicationCore.h" #include "pqPythonSyntaxHighlighter.h" #include "pqSettings.h" #include <QDialogButtonBox> #include <QPointer> #include <QPushButton> #include <QVariant> #include <QVBoxLayout> namespace tomviz { class EditOperatorDialog::EODInternals { public: QSharedPointer<Operator> Op; EditOperatorWidget *Widget; bool needsToBeAdded; DataSource *dataSource; void savePosition(const QPoint& pos) { QSettings *settings = pqApplicationCore::instance()->settings(); QString settingName = QString("Edit%1OperatorDialogPosition") .arg(Op->label()); settings->setValue(settingName, QVariant(pos)); } QVariant loadPosition() { QSettings *settings = pqApplicationCore::instance()->settings(); QString settingName = QString("Edit%1OperatorDialogPosition") .arg(Op->label()); return settings->value(settingName); } }; //----------------------------------------------------------------------------- EditOperatorDialog::EditOperatorDialog( QSharedPointer<Operator> &o, DataSource *dataSource, QWidget* parentObject) : Superclass(parentObject), Internals (new EditOperatorDialog::EODInternals()) { Q_ASSERT(o); this->Internals->Op = o; this->Internals->dataSource = dataSource; this->Internals->needsToBeAdded = (dataSource != nullptr); QVariant position = this->Internals->loadPosition(); if (!position.isNull()) { this->move(position.toPoint()); } QVBoxLayout* vLayout = new QVBoxLayout(this); EditOperatorWidget* opWidget = o->getEditorContents(this); vLayout->addWidget(opWidget); QDialogButtonBox* dialogButtons = new QDialogButtonBox( QDialogButtonBox::Apply|QDialogButtonBox::Cancel|QDialogButtonBox::Ok, Qt::Horizontal, this); vLayout->addWidget(dialogButtons); this->Internals->Widget = opWidget; this->setLayout(vLayout); this->connect(dialogButtons, SIGNAL(accepted()), SLOT(accept())); this->connect(dialogButtons, SIGNAL(rejected()), SLOT(reject())); this->connect(dialogButtons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApply())); this->connect(this, SIGNAL(accepted()), SLOT(onApply())); this->connect(this, SIGNAL(accepted()), SLOT(onClose())); this->connect(this, SIGNAL(rejected()), SLOT(onClose())); } //----------------------------------------------------------------------------- EditOperatorDialog::~EditOperatorDialog() { } QSharedPointer<Operator>& EditOperatorDialog::op() { return this->Internals->Op; } void EditOperatorDialog::onApply() { this->Internals->Widget->applyChangesToOperator(); if (this->Internals->needsToBeAdded && this->Internals->dataSource != nullptr) { this->Internals->dataSource->addOperator(this->Internals->Op); this->Internals->needsToBeAdded = false; } } void EditOperatorDialog::onClose() { this->Internals->savePosition(this->pos()); } } <commit_msg>Add separators in code<commit_after>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "EditOperatorDialog.h" #include "DataSource.h" #include "EditOperatorWidget.h" #include "Operator.h" #include "pqApplicationCore.h" #include "pqPythonSyntaxHighlighter.h" #include "pqSettings.h" #include <QDialogButtonBox> #include <QPointer> #include <QPushButton> #include <QVariant> #include <QVBoxLayout> namespace tomviz { class EditOperatorDialog::EODInternals { public: QSharedPointer<Operator> Op; EditOperatorWidget *Widget; bool needsToBeAdded; DataSource *dataSource; void savePosition(const QPoint& pos) { QSettings *settings = pqApplicationCore::instance()->settings(); QString settingName = QString("Edit%1OperatorDialogPosition") .arg(Op->label()); settings->setValue(settingName, QVariant(pos)); } QVariant loadPosition() { QSettings *settings = pqApplicationCore::instance()->settings(); QString settingName = QString("Edit%1OperatorDialogPosition") .arg(Op->label()); return settings->value(settingName); } }; //----------------------------------------------------------------------------- EditOperatorDialog::EditOperatorDialog( QSharedPointer<Operator> &o, DataSource *dataSource, QWidget* parentObject) : Superclass(parentObject), Internals (new EditOperatorDialog::EODInternals()) { Q_ASSERT(o); this->Internals->Op = o; this->Internals->dataSource = dataSource; this->Internals->needsToBeAdded = (dataSource != nullptr); QVariant position = this->Internals->loadPosition(); if (!position.isNull()) { this->move(position.toPoint()); } QVBoxLayout* vLayout = new QVBoxLayout(this); EditOperatorWidget* opWidget = o->getEditorContents(this); vLayout->addWidget(opWidget); QDialogButtonBox* dialogButtons = new QDialogButtonBox( QDialogButtonBox::Apply|QDialogButtonBox::Cancel|QDialogButtonBox::Ok, Qt::Horizontal, this); vLayout->addWidget(dialogButtons); this->Internals->Widget = opWidget; this->setLayout(vLayout); this->connect(dialogButtons, SIGNAL(accepted()), SLOT(accept())); this->connect(dialogButtons, SIGNAL(rejected()), SLOT(reject())); this->connect(dialogButtons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApply())); this->connect(this, SIGNAL(accepted()), SLOT(onApply())); this->connect(this, SIGNAL(accepted()), SLOT(onClose())); this->connect(this, SIGNAL(rejected()), SLOT(onClose())); } //----------------------------------------------------------------------------- EditOperatorDialog::~EditOperatorDialog() { } //----------------------------------------------------------------------------- QSharedPointer<Operator>& EditOperatorDialog::op() { return this->Internals->Op; } //----------------------------------------------------------------------------- void EditOperatorDialog::onApply() { this->Internals->Widget->applyChangesToOperator(); if (this->Internals->needsToBeAdded && this->Internals->dataSource != nullptr) { this->Internals->dataSource->addOperator(this->Internals->Op); this->Internals->needsToBeAdded = false; } } //----------------------------------------------------------------------------- void EditOperatorDialog::onClose() { this->Internals->savePosition(this->pos()); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: connctrl.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:22:47 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_CONNCTRL_HXX #define _SVX_CONNCTRL_HXX // include --------------------------------------------------------------- #ifndef _CTRL_HXX //autogen #include <vcl/ctrl.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SfxItemSet; class XOutputDevice; class SdrEdgeObj; class SdrView; class SdrObjList; /************************************************************************* |* |* SvxXConnectionPreview |* \************************************************************************/ class SVX_DLLPUBLIC SvxXConnectionPreview : public Control { friend class SvxConnectionPage; private: const SfxItemSet& rAttrs; XOutputDevice* pExtOutDev; SdrEdgeObj* pEdgeObj; SdrObjList* pObjList; const SdrView* pView; SVX_DLLPRIVATE void SetStyles(); public: SvxXConnectionPreview( Window* pParent, const ResId& rResId, const SfxItemSet& rInAttrs ); ~SvxXConnectionPreview(); virtual void Paint( const Rectangle& rRect ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); void SetAttributes( const SfxItemSet& rInAttrs ); USHORT GetLineDeltaAnz(); void Construct(); void SetView( const SdrView* pSdrView ) { pView = pSdrView; } virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; #endif // _SVX_CONNCTRL_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.5.1256); FILE MERGED 2008/04/01 12:46:18 thb 1.5.1256.2: #i85898# Stripping all external header guards 2008/03/31 14:17:53 rt 1.5.1256.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: connctrl.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SVX_CONNCTRL_HXX #define _SVX_CONNCTRL_HXX // include --------------------------------------------------------------- #ifndef _CTRL_HXX //autogen #include <vcl/ctrl.hxx> #endif #include "svx/svxdllapi.h" class SfxItemSet; class XOutputDevice; class SdrEdgeObj; class SdrView; class SdrObjList; /************************************************************************* |* |* SvxXConnectionPreview |* \************************************************************************/ class SVX_DLLPUBLIC SvxXConnectionPreview : public Control { friend class SvxConnectionPage; private: const SfxItemSet& rAttrs; XOutputDevice* pExtOutDev; SdrEdgeObj* pEdgeObj; SdrObjList* pObjList; const SdrView* pView; SVX_DLLPRIVATE void SetStyles(); public: SvxXConnectionPreview( Window* pParent, const ResId& rResId, const SfxItemSet& rInAttrs ); ~SvxXConnectionPreview(); virtual void Paint( const Rectangle& rRect ); virtual void MouseButtonDown( const MouseEvent& rMEvt ); void SetAttributes( const SfxItemSet& rInAttrs ); USHORT GetLineDeltaAnz(); void Construct(); void SetView( const SdrView* pSdrView ) { pView = pSdrView; } virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; #endif // _SVX_CONNCTRL_HXX <|endoftext|>
<commit_before>//===- Configuration.cpp - Configuration Data Mgmt --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the parsing of configuration files for the LLVM Compiler // Driver (llvmc). // //===------------------------------------------------------------------------=== #include "Configuration.h" #include "ConfigLexer.h" #include "CompilerDriver.h" #include "Config/config.h" #include "Support/CommandLine.h" #include "Support/StringExtras.h" #include <iostream> #include <fstream> using namespace llvm; namespace sys { // From CompilerDriver.cpp (for now) extern bool FileReadable(const std::string& fname); } namespace llvm { ConfigLexerInfo ConfigLexerState; InputProvider* ConfigLexerInput = 0; InputProvider::~InputProvider() {} void InputProvider::error(const std::string& msg) { std::cerr << name << ":" << ConfigLexerState.lineNum << ": Error: " << msg << "\n"; errCount++; } void InputProvider::checkErrors() { if (errCount > 0) { std::cerr << name << " had " << errCount << " errors. Terminating.\n"; exit(errCount); } } } namespace { class FileInputProvider : public InputProvider { public: FileInputProvider(const std::string & fname) : InputProvider(fname) , F(fname.c_str()) { ConfigLexerInput = this; } virtual ~FileInputProvider() { F.close(); ConfigLexerInput = 0; } virtual unsigned read(char *buffer, unsigned max_size) { if (F.good()) { F.read(buffer,max_size); if ( F.gcount() ) return F.gcount() - 1; } return 0; } bool okay() { return F.good(); } private: std::ifstream F; }; cl::opt<bool> DumpTokens("dump-tokens", cl::Optional, cl::Hidden, cl::init(false), cl::desc("Dump lexical tokens (debug use only).")); struct Parser { Parser() { token = EOFTOK; provider = 0; confDat = 0; ConfigLexerState.lineNum = 1; ConfigLexerState.in_value = false; ConfigLexerState.StringVal.clear(); ConfigLexerState.IntegerVal = 0; }; ConfigLexerTokens token; InputProvider* provider; CompilerDriver::ConfigData* confDat; int next() { token = Configlex(); if (DumpTokens) std::cerr << token << "\n"; return token; } bool next_is_real() { next(); return (token != EOLTOK) && (token != ERRORTOK) && (token != 0); } void eatLineRemnant() { while (next_is_real()) ; } void error(const std::string& msg, bool skip = true) { provider->error(msg); if (skip) eatLineRemnant(); } std::string parseName() { std::string result; if (next() == EQUALS) { while (next_is_real()) { switch (token ) { case STRING : case OPTION : result += ConfigLexerState.StringVal + " "; break; default: error("Invalid name"); break; } } if (result.empty()) error("Name exepected"); else result.erase(result.size()-1,1); } else error("= expected"); return result; } bool parseBoolean() { bool result = true; if (next() == EQUALS) { if (next() == FALSETOK) { result = false; } else if (token != TRUETOK) { error("Expecting boolean value"); return false; } if (next() != EOLTOK && token != 0) { error("Extraneous tokens after boolean"); } } else error("Expecting '='"); return result; } bool parseSubstitution(CompilerDriver::StringVector& optList) { switch (token) { case IN_SUBST: optList.push_back("%in%"); break; case OUT_SUBST: optList.push_back("%out%"); break; case TIME_SUBST: optList.push_back("%time%"); break; case STATS_SUBST: optList.push_back("%stats%"); break; case OPT_SUBST: optList.push_back("%opt%"); break; case TARGET_SUBST: optList.push_back("%target%"); break; default: return false; } return true; } void parseOptionList(CompilerDriver::StringVector& optList ) { if (next() == EQUALS) { while (next_is_real()) { if (token == STRING || token == OPTION) optList.push_back(ConfigLexerState.StringVal); else if (!parseSubstitution(optList)) { error("Expecting a program argument or substitution", false); break; } } } else error("Expecting '='"); } void parseVersion() { if (next() == EQUALS) { while (next_is_real()) { if (token == STRING || token == OPTION) confDat->version = ConfigLexerState.StringVal; else error("Expecting a version string"); } } else error("Expecting '='"); } void parseLang() { switch (next() ) { case NAME: confDat->langName = parseName(); break; case OPT1: parseOptionList(confDat->opts[CompilerDriver::OPT_FAST_COMPILE]); break; case OPT2: parseOptionList(confDat->opts[CompilerDriver::OPT_SIMPLE]); break; case OPT3: parseOptionList(confDat->opts[CompilerDriver::OPT_AGGRESSIVE]); break; case OPT4: parseOptionList(confDat->opts[CompilerDriver::OPT_LINK_TIME]); break; case OPT5: parseOptionList( confDat->opts[CompilerDriver::OPT_AGGRESSIVE_LINK_TIME]); break; default: error("Expecting 'name' or 'optN' after 'lang.'"); break; } } void parseCommand(CompilerDriver::Action& action) { if (next() == EQUALS) { if (next() == EOLTOK) { // no value (valid) action.program.clear(); action.args.clear(); } else { if (token == STRING || token == OPTION) { action.program = ConfigLexerState.StringVal; } else { error("Expecting a program name"); } while (next_is_real()) { if (token == STRING || token == OPTION) { action.args.push_back(ConfigLexerState.StringVal); } else if (!parseSubstitution(action.args)) { error("Expecting a program argument or substitution", false); break; } } } } } void parsePreprocessor() { switch (next()) { case COMMAND: parseCommand(confDat->PreProcessor); break; case REQUIRED: if (parseBoolean()) confDat->PreProcessor.set(CompilerDriver::REQUIRED_FLAG); else confDat->PreProcessor.clear(CompilerDriver::REQUIRED_FLAG); break; default: error("Expecting 'command' or 'required'"); break; } } void parseTranslator() { switch (next()) { case COMMAND: parseCommand(confDat->Translator); break; case REQUIRED: if (parseBoolean()) confDat->Translator.set(CompilerDriver::REQUIRED_FLAG); else confDat->Translator.clear(CompilerDriver::REQUIRED_FLAG); break; case PREPROCESSES: if (parseBoolean()) confDat->Translator.set(CompilerDriver::PREPROCESSES_FLAG); else confDat->Translator.clear(CompilerDriver::PREPROCESSES_FLAG); break; case OPTIMIZES: if (parseBoolean()) confDat->Translator.set(CompilerDriver::OPTIMIZES_FLAG); else confDat->Translator.clear(CompilerDriver::OPTIMIZES_FLAG); break; case GROKS_DASH_O: if (parseBoolean()) confDat->Translator.set(CompilerDriver::GROKS_DASH_O_FLAG); else confDat->Translator.clear(CompilerDriver::GROKS_DASH_O_FLAG); break; case OUTPUT_IS_ASM: if (parseBoolean()) confDat->Translator.set(CompilerDriver::OUTPUT_IS_ASM_FLAG); else confDat->Translator.clear(CompilerDriver::OUTPUT_IS_ASM_FLAG); break; default: error("Expecting 'command', 'required', 'preprocesses', " "'groks_dash_O' or 'optimizes'"); break; } } void parseOptimizer() { switch (next()) { case COMMAND: parseCommand(confDat->Optimizer); break; case PREPROCESSES: if (parseBoolean()) confDat->Optimizer.set(CompilerDriver::PREPROCESSES_FLAG); else confDat->Optimizer.clear(CompilerDriver::PREPROCESSES_FLAG); break; case TRANSLATES: if (parseBoolean()) confDat->Optimizer.set(CompilerDriver::TRANSLATES_FLAG); else confDat->Optimizer.clear(CompilerDriver::TRANSLATES_FLAG); break; case GROKS_DASH_O: if (parseBoolean()) confDat->Optimizer.set(CompilerDriver::GROKS_DASH_O_FLAG); else confDat->Optimizer.clear(CompilerDriver::GROKS_DASH_O_FLAG); break; case OUTPUT_IS_ASM: if (parseBoolean()) confDat->Translator.set(CompilerDriver::OUTPUT_IS_ASM_FLAG); else confDat->Translator.clear(CompilerDriver::OUTPUT_IS_ASM_FLAG); break; default: error("Expecting 'command' or 'groks_dash_O'"); break; } } void parseAssembler() { switch(next()) { case COMMAND: parseCommand(confDat->Assembler); break; default: error("Expecting 'command'"); break; } } void parseLinker() { switch(next()) { case COMMAND: parseCommand(confDat->Linker); break; case GROKS_DASH_O: if (parseBoolean()) confDat->Linker.set(CompilerDriver::GROKS_DASH_O_FLAG); else confDat->Linker.clear(CompilerDriver::GROKS_DASH_O_FLAG); break; default: error("Expecting 'command'"); break; } } void parseAssignment() { switch (token) { case VERSION: parseVersion(); break; case LANG: parseLang(); break; case PREPROCESSOR: parsePreprocessor(); break; case TRANSLATOR: parseTranslator(); break; case OPTIMIZER: parseOptimizer(); break; case ASSEMBLER: parseAssembler(); break; case LINKER: parseLinker(); break; case EOLTOK: break; // just ignore case ERRORTOK: default: error("Invalid top level configuration item"); break; } } void parseFile() { while ( next() != EOFTOK ) { if (token == ERRORTOK) error("Invalid token"); else if (token != EOLTOK) parseAssignment(); } provider->checkErrors(); } }; void ParseConfigData(InputProvider& provider, CompilerDriver::ConfigData& confDat) { Parser p; p.token = EOFTOK; p.provider = &provider; p.confDat = &confDat; p.parseFile(); } } CompilerDriver::ConfigData* LLVMC_ConfigDataProvider::ReadConfigData(const std::string& ftype) { CompilerDriver::ConfigData* result = 0; std::string dir_name; if (configDir.empty()) { // Try the environment variable const char* conf = getenv("LLVM_CONFIG_DIR"); if (conf) { dir_name = conf; dir_name += "/"; if (!::sys::FileReadable(dir_name + ftype)) throw "Configuration file for '" + ftype + "' is not available."; } else { // Try the user's home directory const char* home = getenv("HOME"); if (home) { dir_name = home; dir_name += "/.llvm/etc/"; if (!::sys::FileReadable(dir_name + ftype)) { // Okay, try the LLVM installation directory dir_name = LLVM_ETCDIR; dir_name += "/"; if (!::sys::FileReadable(dir_name + ftype)) { // Okay, try the "standard" place dir_name = "/etc/llvm/"; if (!::sys::FileReadable(dir_name + ftype)) { throw "Configuration file for '" + ftype + "' is not available."; } } } } } } else { dir_name = configDir + "/"; if (!::sys::FileReadable(dir_name + ftype)) { throw "Configuration file for '" + ftype + "' is not available."; } } FileInputProvider fip( dir_name + ftype ); if (!fip.okay()) { throw "Configuration file for '" + ftype + "' is not available."; } result = new CompilerDriver::ConfigData(); ParseConfigData(fip,*result); return result; } LLVMC_ConfigDataProvider::LLVMC_ConfigDataProvider() : Configurations() , configDir() { Configurations.clear(); } LLVMC_ConfigDataProvider::~LLVMC_ConfigDataProvider() { ConfigDataMap::iterator cIt = Configurations.begin(); while (cIt != Configurations.end()) { CompilerDriver::ConfigData* cd = cIt->second; ++cIt; delete cd; } Configurations.clear(); } CompilerDriver::ConfigData* LLVMC_ConfigDataProvider::ProvideConfigData(const std::string& filetype) { CompilerDriver::ConfigData* result = 0; if (!Configurations.empty()) { ConfigDataMap::iterator cIt = Configurations.find(filetype); if ( cIt != Configurations.end() ) { // We found one in the case, return it. result = cIt->second; } } if (result == 0) { // The configuration data doesn't exist, we have to go read it. result = ReadConfigData(filetype); // If we got one, cache it if ( result != 0 ) Configurations.insert(std::make_pair(filetype,result)); } return result; // Might return 0 } // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab <commit_msg>- Implement the %args% substitution - Implement parsing of the .output={bytecode|assembly} item. - Drop parsing support for translator.optimizes, translator.groks_dash_O, optimizer.groks_dash_O, translator.output_is_asm, optimizer.output_is_asm - Add parsing support for translator.output and optimizer.output - Add optimizer.required parsing support - Add linker.libs and linker.libpaths parsing support - Fix error messages to list correct set of tokens expected. - Rename FileReadable -> FileIsReadable (changed in CompilerDriver.cpp)<commit_after>//===- Configuration.cpp - Configuration Data Mgmt --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the parsing of configuration files for the LLVM Compiler // Driver (llvmc). // //===------------------------------------------------------------------------=== #include "Configuration.h" #include "ConfigLexer.h" #include "CompilerDriver.h" #include "Config/config.h" #include "Support/CommandLine.h" #include "Support/StringExtras.h" #include <iostream> #include <fstream> using namespace llvm; namespace sys { // From CompilerDriver.cpp (for now) extern bool FileIsReadable(const std::string& fname); } namespace llvm { ConfigLexerInfo ConfigLexerState; InputProvider* ConfigLexerInput = 0; InputProvider::~InputProvider() {} void InputProvider::error(const std::string& msg) { std::cerr << name << ":" << ConfigLexerState.lineNum << ": Error: " << msg << "\n"; errCount++; } void InputProvider::checkErrors() { if (errCount > 0) { std::cerr << name << " had " << errCount << " errors. Terminating.\n"; exit(errCount); } } } namespace { class FileInputProvider : public InputProvider { public: FileInputProvider(const std::string & fname) : InputProvider(fname) , F(fname.c_str()) { ConfigLexerInput = this; } virtual ~FileInputProvider() { F.close(); ConfigLexerInput = 0; } virtual unsigned read(char *buffer, unsigned max_size) { if (F.good()) { F.read(buffer,max_size); if ( F.gcount() ) return F.gcount() - 1; } return 0; } bool okay() { return F.good(); } private: std::ifstream F; }; cl::opt<bool> DumpTokens("dump-tokens", cl::Optional, cl::Hidden, cl::init(false), cl::desc("Dump lexical tokens (debug use only).")); struct Parser { Parser() { token = EOFTOK; provider = 0; confDat = 0; ConfigLexerState.lineNum = 1; ConfigLexerState.in_value = false; ConfigLexerState.StringVal.clear(); ConfigLexerState.IntegerVal = 0; }; ConfigLexerTokens token; InputProvider* provider; CompilerDriver::ConfigData* confDat; int next() { token = Configlex(); if (DumpTokens) std::cerr << token << "\n"; return token; } bool next_is_real() { next(); return (token != EOLTOK) && (token != ERRORTOK) && (token != 0); } void eatLineRemnant() { while (next_is_real()) ; } void error(const std::string& msg, bool skip = true) { provider->error(msg); if (skip) eatLineRemnant(); } std::string parseName() { std::string result; if (next() == EQUALS) { while (next_is_real()) { switch (token ) { case STRING : case OPTION : result += ConfigLexerState.StringVal + " "; break; default: error("Invalid name"); break; } } if (result.empty()) error("Name exepected"); else result.erase(result.size()-1,1); } else error("= expected"); return result; } bool parseBoolean() { bool result = true; if (next() == EQUALS) { if (next() == FALSETOK) { result = false; } else if (token != TRUETOK) { error("Expecting boolean value"); return false; } if (next() != EOLTOK && token != 0) { error("Extraneous tokens after boolean"); } } else error("Expecting '='"); return result; } bool parseSubstitution(CompilerDriver::StringVector& optList) { switch (token) { case ARGS_SUBST: optList.push_back("%args%"); break; case IN_SUBST: optList.push_back("%in%"); break; case OUT_SUBST: optList.push_back("%out%"); break; case TIME_SUBST: optList.push_back("%time%"); break; case STATS_SUBST: optList.push_back("%stats%"); break; case OPT_SUBST: optList.push_back("%opt%"); break; case TARGET_SUBST: optList.push_back("%target%"); break; default: return false; } return true; } void parseOptionList(CompilerDriver::StringVector& optList ) { if (next() == EQUALS) { while (next_is_real()) { if (token == STRING || token == OPTION) optList.push_back(ConfigLexerState.StringVal); else if (!parseSubstitution(optList)) { error("Expecting a program argument or substitution", false); break; } } } else error("Expecting '='"); } void parseVersion() { if (next() == EQUALS) { while (next_is_real()) { if (token == STRING || token == OPTION) confDat->version = ConfigLexerState.StringVal; else error("Expecting a version string"); } } else error("Expecting '='"); } void parseLang() { switch (next() ) { case NAME: confDat->langName = parseName(); break; case OPT1: parseOptionList(confDat->opts[CompilerDriver::OPT_FAST_COMPILE]); break; case OPT2: parseOptionList(confDat->opts[CompilerDriver::OPT_SIMPLE]); break; case OPT3: parseOptionList(confDat->opts[CompilerDriver::OPT_AGGRESSIVE]); break; case OPT4: parseOptionList(confDat->opts[CompilerDriver::OPT_LINK_TIME]); break; case OPT5: parseOptionList( confDat->opts[CompilerDriver::OPT_AGGRESSIVE_LINK_TIME]); break; default: error("Expecting 'name' or 'optN' after 'lang.'"); break; } } void parseCommand(CompilerDriver::Action& action) { if (next() == EQUALS) { if (next() == EOLTOK) { // no value (valid) action.program.clear(); action.args.clear(); } else { if (token == STRING || token == OPTION) { action.program = ConfigLexerState.StringVal; } else { error("Expecting a program name"); } while (next_is_real()) { if (token == STRING || token == OPTION) { action.args.push_back(ConfigLexerState.StringVal); } else if (!parseSubstitution(action.args)) { error("Expecting a program argument or substitution", false); break; } } } } } void parsePreprocessor() { switch (next()) { case COMMAND: parseCommand(confDat->PreProcessor); break; case REQUIRED: if (parseBoolean()) confDat->PreProcessor.set(CompilerDriver::REQUIRED_FLAG); else confDat->PreProcessor.clear(CompilerDriver::REQUIRED_FLAG); break; default: error("Expecting 'command' or 'required' but found '" + ConfigLexerState.StringVal); break; } } bool parseOutputFlag() { if (next() == EQUALS) { if (next() == ASSEMBLY) { return true; } else if (token == BYTECODE) { return false; } else { error("Expecting output type value"); return false; } if (next() != EOLTOK && token != 0) { error("Extraneous tokens after output value"); } } else error("Expecting '='"); return false; } void parseTranslator() { switch (next()) { case COMMAND: parseCommand(confDat->Translator); break; case REQUIRED: if (parseBoolean()) confDat->Translator.set(CompilerDriver::REQUIRED_FLAG); else confDat->Translator.clear(CompilerDriver::REQUIRED_FLAG); break; case PREPROCESSES: if (parseBoolean()) confDat->Translator.set(CompilerDriver::PREPROCESSES_FLAG); else confDat->Translator.clear(CompilerDriver::PREPROCESSES_FLAG); break; case OUTPUT: if (parseOutputFlag()) confDat->Translator.set(CompilerDriver::OUTPUT_IS_ASM_FLAG); else confDat->Translator.clear(CompilerDriver::OUTPUT_IS_ASM_FLAG); break; default: error("Expecting 'command', 'required', 'preprocesses', or " "'output' but found '" + ConfigLexerState.StringVal + "' instead"); break; } } void parseOptimizer() { switch (next()) { case COMMAND: parseCommand(confDat->Optimizer); break; case PREPROCESSES: if (parseBoolean()) confDat->Optimizer.set(CompilerDriver::PREPROCESSES_FLAG); else confDat->Optimizer.clear(CompilerDriver::PREPROCESSES_FLAG); break; case TRANSLATES: if (parseBoolean()) confDat->Optimizer.set(CompilerDriver::TRANSLATES_FLAG); else confDat->Optimizer.clear(CompilerDriver::TRANSLATES_FLAG); break; case REQUIRED: if (parseBoolean()) confDat->Optimizer.set(CompilerDriver::REQUIRED_FLAG); else confDat->Optimizer.clear(CompilerDriver::REQUIRED_FLAG); break; case OUTPUT: if (parseOutputFlag()) confDat->Translator.set(CompilerDriver::OUTPUT_IS_ASM_FLAG); else confDat->Translator.clear(CompilerDriver::OUTPUT_IS_ASM_FLAG); break; default: error(std::string("Expecting 'command', 'preprocesses', ") + "'translates' or 'output' but found '" + ConfigLexerState.StringVal + "' instead"); break; } } void parseAssembler() { switch(next()) { case COMMAND: parseCommand(confDat->Assembler); break; default: error("Expecting 'command'"); break; } } void parseLinker() { switch(next()) { case LIBS: break; //FIXME case LIBPATHS: break; //FIXME default: error("Expecting 'libs' or 'libpaths'"); break; } } void parseAssignment() { switch (token) { case VERSION: parseVersion(); break; case LANG: parseLang(); break; case PREPROCESSOR: parsePreprocessor(); break; case TRANSLATOR: parseTranslator(); break; case OPTIMIZER: parseOptimizer(); break; case ASSEMBLER: parseAssembler(); break; case LINKER: parseLinker(); break; case EOLTOK: break; // just ignore case ERRORTOK: default: error("Invalid top level configuration item"); break; } } void parseFile() { while ( next() != EOFTOK ) { if (token == ERRORTOK) error("Invalid token"); else if (token != EOLTOK) parseAssignment(); } provider->checkErrors(); } }; void ParseConfigData(InputProvider& provider, CompilerDriver::ConfigData& confDat) { Parser p; p.token = EOFTOK; p.provider = &provider; p.confDat = &confDat; p.parseFile(); } } CompilerDriver::ConfigData* LLVMC_ConfigDataProvider::ReadConfigData(const std::string& ftype) { CompilerDriver::ConfigData* result = 0; std::string dir_name; if (configDir.empty()) { // Try the environment variable const char* conf = getenv("LLVM_CONFIG_DIR"); if (conf) { dir_name = conf; dir_name += "/"; if (!::sys::FileIsReadable(dir_name + ftype)) throw "Configuration file for '" + ftype + "' is not available."; } else { // Try the user's home directory const char* home = getenv("HOME"); if (home) { dir_name = home; dir_name += "/.llvm/etc/"; if (!::sys::FileIsReadable(dir_name + ftype)) { // Okay, try the LLVM installation directory dir_name = LLVM_ETCDIR; dir_name += "/"; if (!::sys::FileIsReadable(dir_name + ftype)) { // Okay, try the "standard" place dir_name = "/etc/llvm/"; if (!::sys::FileIsReadable(dir_name + ftype)) { throw "Configuration file for '" + ftype + "' is not available."; } } } } } } else { dir_name = configDir + "/"; if (!::sys::FileIsReadable(dir_name + ftype)) { throw "Configuration file for '" + ftype + "' is not available."; } } FileInputProvider fip( dir_name + ftype ); if (!fip.okay()) { throw "Configuration file for '" + ftype + "' is not available."; } result = new CompilerDriver::ConfigData(); ParseConfigData(fip,*result); return result; } LLVMC_ConfigDataProvider::LLVMC_ConfigDataProvider() : Configurations() , configDir() { Configurations.clear(); } LLVMC_ConfigDataProvider::~LLVMC_ConfigDataProvider() { ConfigDataMap::iterator cIt = Configurations.begin(); while (cIt != Configurations.end()) { CompilerDriver::ConfigData* cd = cIt->second; ++cIt; delete cd; } Configurations.clear(); } CompilerDriver::ConfigData* LLVMC_ConfigDataProvider::ProvideConfigData(const std::string& filetype) { CompilerDriver::ConfigData* result = 0; if (!Configurations.empty()) { ConfigDataMap::iterator cIt = Configurations.find(filetype); if ( cIt != Configurations.end() ) { // We found one in the case, return it. result = cIt->second; } } if (result == 0) { // The configuration data doesn't exist, we have to go read it. result = ReadConfigData(filetype); // If we got one, cache it if ( result != 0 ) Configurations.insert(std::make_pair(filetype,result)); } return result; // Might return 0 } // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include "util.h" using namespace std; void status(string message) { cout << "[+] " << message << "\n"; } void header() { cout << "SIC-Disassembler by Jay Bosamiya\n" "--------------------------------\n\n"; } void usage(string progname) { cerr << "Usage: " << progname << " input_object_file output_assembly_file\n"; exit(-2); } void error(string err) { cerr << "[!] Error: " << err << "\n"; } void fatal(string err, int code) { error(err); exit(code); } bool is_hex_digit(char c) { return (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'); } int hexchar2int(char c) { int ret = -1; if ( c >= '0' && c <= '9' ) { ret = (c-'0'); } else if ( c >= 'a' && c <= 'f' ) { ret = (c-'a')+10; } else if ( c >= 'A' && c <= 'F' ) { ret = (c-'A')+10; } return ret; } int hex2int(string s) { int ret = 0; for ( const char * cc = s.c_str() ; *cc ; cc++ ) { ret *= 16; const char &c = *cc; if ( is_hex_digit(c) ) { ret += hexchar2int(c); } else { fatal("Hex values need to be 0-9 or a-f"); } } } string byte2hex(int c) { string ret = ""; if ( c < 0 || c >= 256 ) { fatal("Illegal value for a byte"); } ret += (c/16 <= 10)?('0'+c/16):('A'+c/16-10); ret += (c/16 <= 10)?('0'+c/16):('A'+c/16-10); } string int2hex(int c, int bytes) { if ( c < 0 ) { return int2hex(c&0x7FFFFFFF,bytes); } if ( bytes <= 0 ) { return ""; } return int2hex(c/256,bytes-1)+byte2hex(c%256); }<commit_msg>Add missing returns<commit_after>#include <iostream> #include <cstdlib> #include "util.h" using namespace std; void status(string message) { cout << "[+] " << message << "\n"; } void header() { cout << "SIC-Disassembler by Jay Bosamiya\n" "--------------------------------\n\n"; } void usage(string progname) { cerr << "Usage: " << progname << " input_object_file output_assembly_file\n"; exit(-2); } void error(string err) { cerr << "[!] Error: " << err << "\n"; } void fatal(string err, int code) { error(err); exit(code); } bool is_hex_digit(char c) { return (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'); } int hexchar2int(char c) { int ret = -1; if ( c >= '0' && c <= '9' ) { ret = (c-'0'); } else if ( c >= 'a' && c <= 'f' ) { ret = (c-'a')+10; } else if ( c >= 'A' && c <= 'F' ) { ret = (c-'A')+10; } return ret; } int hex2int(string s) { int ret = 0; for ( const char * cc = s.c_str() ; *cc ; cc++ ) { ret *= 16; const char &c = *cc; if ( is_hex_digit(c) ) { ret += hexchar2int(c); } else { fatal("Hex values need to be 0-9 or a-f"); } } return ret; } string byte2hex(int c) { string ret = ""; if ( c < 0 || c >= 256 ) { fatal("Illegal value for a byte"); } ret += (c/16 <= 10)?('0'+c/16):('A'+c/16-10); ret += (c/16 <= 10)?('0'+c/16):('A'+c/16-10); return ret; } string int2hex(int c, int bytes) { if ( c < 0 ) { return int2hex(c&0x7FFFFFFF,bytes); } if ( bytes <= 0 ) { return ""; } return int2hex(c/256,bytes-1)+byte2hex(c%256); }<|endoftext|>
<commit_before>#include <stdexcept> #include "InputFeature.h" #include "moses/Util.h" #include "moses/ScoreComponentCollection.h" #include "moses/InputPath.h" #include "moses/StaticData.h" #include "moses/TranslationModel/PhraseDictionaryTreeAdaptor.h" using namespace std; namespace Moses { InputFeature *InputFeature::s_instance = NULL; InputFeature::InputFeature(const std::string &line) : StatelessFeatureFunction(line) , m_numRealWordCount(0) { m_numInputScores = this->m_numScoreComponents; ReadParameters(); UTIL_THROW_IF2(s_instance, "Can only have 1 input feature"); s_instance = this; } void InputFeature::Load() { const PhraseDictionary *pt = PhraseDictionary::GetColl()[0]; const PhraseDictionaryTreeAdaptor *ptBin = dynamic_cast<const PhraseDictionaryTreeAdaptor*>(pt); m_legacy = (ptBin != NULL); } void InputFeature::SetParameter(const std::string& key, const std::string& value) { if (key == "num-input-features") { m_numInputScores = Scan<size_t>(value); } else if (key == "real-word-count") { m_numRealWordCount = Scan<size_t>(value); } else { StatelessFeatureFunction::SetParameter(key, value); } } void InputFeature::EvaluateWithSourceContext(const InputType &input , const InputPath &inputPath , const TargetPhrase &targetPhrase , const StackVec *stackVec , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection *estimatedFutureScore) const { if (m_legacy) { //binary phrase-table does input feature itself return; } /* const ScorePair *scores = inputPath.GetInputScore(); if (scores) { scoreBreakdown.PlusEquals(this, *scores); } */ } } // namespace <commit_msg>set scores for lattice path<commit_after>#include <stdexcept> #include "InputFeature.h" #include "moses/Util.h" #include "moses/ScoreComponentCollection.h" #include "moses/InputPath.h" #include "moses/StaticData.h" #include "moses/TranslationModel/PhraseDictionaryTreeAdaptor.h" using namespace std; namespace Moses { InputFeature *InputFeature::s_instance = NULL; InputFeature::InputFeature(const std::string &line) : StatelessFeatureFunction(line) , m_numRealWordCount(0) { m_numInputScores = this->m_numScoreComponents; ReadParameters(); UTIL_THROW_IF2(s_instance, "Can only have 1 input feature"); s_instance = this; } void InputFeature::Load() { const PhraseDictionary *pt = PhraseDictionary::GetColl()[0]; const PhraseDictionaryTreeAdaptor *ptBin = dynamic_cast<const PhraseDictionaryTreeAdaptor*>(pt); m_legacy = (ptBin != NULL); } void InputFeature::SetParameter(const std::string& key, const std::string& value) { if (key == "num-input-features") { m_numInputScores = Scan<size_t>(value); } else if (key == "real-word-count") { m_numRealWordCount = Scan<size_t>(value); } else { StatelessFeatureFunction::SetParameter(key, value); } } void InputFeature::EvaluateWithSourceContext(const InputType &input , const InputPath &inputPath , const TargetPhrase &targetPhrase , const StackVec *stackVec , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection *estimatedFutureScore) const { if (m_legacy) { //binary phrase-table does input feature itself return; } else if (input.GetType() == WordLatticeInput){ const ScorePair *scores = inputPath.GetInputScore(); if (scores) { scoreBreakdown.PlusEquals(this, *scores); } } } } // namespace <|endoftext|>
<commit_before>#include <fstream> #include <string> #include <cassert> #include <cstdint> #include "errors.hpp" #include "ziploader.hpp" using namespace std; #define LFH_MAGIC UINT32_C(0x04034b50) #define EOCD_MAGIC UINT32_C(0x06054b50) #define CDFH_MAGIC UINT32_C(0x02014b50) #define CMT_MAX ((size_t)(1 << 16)) #define EOCD_SIZE ((size_t)22U) #define CDFH_SIZE ((size_t)46U) static void zipError(const string &filename, const string &message) { string err = "While loading '" + filename + "': " + message; logError("ZIP", err); } ZipFile::ZipFile() { num_files = 0; files_info.clear(); } bool ZipFile::Init(const string &path) { ifstream fp; fp.open(path.c_str(), ios_base::in | ios_base::binary); if (!fp.is_open() || !fp.good()) { zipError(path, "Open error"); return false; } /* set exceptions to catch all possible errors */ fp.exceptions(ifstream::failbit | ifstream::badbit | ifstream::eofbit); bool ret; try { ret = InitScan(fp, path); } catch (ifstream::failure e) { string err = "Init failure ("; err += e.what(); err += ")"; zipError(path, err); ret = false; } fp.close(); return ret; } /** * @throws std::ifstream::failure */ bool ZipFile::InitScan(ifstream &fp, const string &path) { uint32_t magic; /* The first word is always a Local File Header signature */ fp.read((char *)(&magic), sizeof(uint32_t)); if (magic != LFH_MAGIC) { zipError(path, "Bad Magic"); return false; } fp.seekg(0, ios_base::end); size_t total_size = fp.tellg(); /* Look for the End of Central Directory. It must be in the * last EOCD_SIZE + CMT_MAX bytes of the file */ int size = EOCD_SIZE + CMT_MAX; fp.seekg(-size, ios_base::end); unsigned char *buffer = new unsigned char[size]; unsigned char *buffer_end = buffer + size; fp.read((char *)buffer, size); unsigned char *scan = buffer; uint32_t word; while ((scan + 4) < buffer_end) { word = *(uint32_t *)scan; if (word == EOCD_MAGIC) break; scan++; } if (word != EOCD_MAGIC) { zipError(path, "Can't find EOCD"); delete [] buffer; return false; } unsigned char *eocd = scan; scan += sizeof(uint32_t); /* Some heavy restrictions, at the moment * TODO: support more of ZIP format */ uint16_t nr_disk = *(uint16_t *)scan; scan += sizeof(uint16_t); assert(nr_disk == 0); uint16_t disk_start = *(uint16_t *)scan; scan += sizeof(uint16_t); assert(disk_start == 0); uint16_t nr_rec_on_disk = *(uint16_t *)scan; scan += sizeof(uint16_t); num_files = *(uint16_t *)scan; log(string("Number of files in the zip: ") + to_string(num_files)); scan += sizeof(uint16_t); assert(num_files = nr_rec_on_disk); uint32_t cd_size = *(uint32_t *)scan; scan += sizeof(uint32_t); uint32_t cd_offset = *(uint32_t *)scan; scan += sizeof(uint32_t); uint64_t comment_size = *(uint16_t *)scan; delete [] buffer; /* Sanity check */ assert(cd_offset + cd_size <= total_size); assert(eocd + EOCD_SIZE + comment_size == buffer_end); files_info.resize(num_files); fp.seekg(cd_offset, ios_base::beg); size_t bytes = 0; for (size_t nr = 0; nr < num_files; nr++) { ZipFileInfo *info = &(files_info[nr]); buffer = new unsigned char[CDFH_SIZE]; buffer_end = buffer + CDFH_SIZE; size_t start_pos = fp.tellg(); fp.read((char *)buffer, CDFH_SIZE); scan = buffer; word = *(uint32_t *)scan; if (word != CDFH_MAGIC) { zipError(path, string("Can't find CDFH - ") + to_string(nr)); delete [] buffer; return false; } scan += sizeof(uint32_t); scan += sizeof(uint16_t); // skip "Version made by" scan += sizeof(uint16_t); // skip "Version needed to extract (minimum) scan += sizeof(uint16_t); // skip "General purpose bit flag" uint16_t compression_method = *(uint16_t *)scan; scan += sizeof(uint16_t); if (compression_method != 0) { info->compressed = true; assert(compression_method == 8 /* deflate */); } else { info->compressed = false; } scan += sizeof(uint16_t); // skip "File last modification time" scan += sizeof(uint16_t); // skip "File last modification date" scan += sizeof(uint32_t); // skip "CRC32" info->compressed_size = *(uint32_t *)scan; scan += sizeof(uint32_t); info->size = *(uint32_t *)scan; scan += sizeof(uint32_t); uint16_t file_name_length = *(uint16_t *)scan; assert(file_name_length != 0); scan += sizeof(uint16_t); uint16_t extra_field_length = *(uint16_t *)scan; scan += sizeof(uint16_t); uint16_t comment_length = *(uint16_t *)scan; scan += sizeof(uint16_t); disk_start = *(uint16_t *)scan; scan += sizeof(uint16_t); assert(disk_start == 0); scan += sizeof(uint16_t); // skip "internal file attributes" scan += sizeof(uint32_t); // skip "external file attributes" info->offset = *(uint32_t *)scan; scan += sizeof(uint32_t); assert(scan == buffer_end); delete [] buffer; info->name.resize(file_name_length); fp.read((char *)&(info->name[0]), file_name_length); fp.seekg(extra_field_length + comment_length, ios_base::cur); size_t end_pos = fp.tellg(); bytes += end_pos - start_pos; if (info->size != 0) cout << files_info[nr] << endl; } assert(bytes == cd_size); return true; } <commit_msg>zip: replace raw array by vectors<commit_after>#include <fstream> #include <string> #include <cassert> #include <cstdint> #include <vector> #include "errors.hpp" #include "ziploader.hpp" using namespace std; #define LFH_MAGIC UINT32_C(0x04034b50) #define EOCD_MAGIC UINT32_C(0x06054b50) #define CDFH_MAGIC UINT32_C(0x02014b50) #define CMT_MAX ((size_t)(1 << 16)) #define EOCD_SIZE ((size_t)22U) #define CDFH_SIZE ((size_t)46U) static void zipError(const string &filename, const string &message) { string err = "While loading '" + filename + "': " + message; logError("ZIP", err); } ZipFile::ZipFile() { num_files = 0; files_info.clear(); } bool ZipFile::Init(const string &path) { ifstream fp; fp.open(path.c_str(), ios_base::in | ios_base::binary); if (!fp.is_open() || !fp.good()) { zipError(path, "Open error"); return false; } /* set exceptions to catch all possible errors */ fp.exceptions(ifstream::failbit | ifstream::badbit | ifstream::eofbit); bool ret; try { ret = InitScan(fp, path); } catch (ifstream::failure e) { string err = "Init failure ("; err += e.what(); err += ")"; zipError(path, err); ret = false; } fp.close(); return ret; } static uint16_t buf2u16(const vector<unsigned char>::iterator &it) { unsigned char c0 = *it; unsigned char c1 = *(it + 1); uint16_t ret = c0; ret |= ((uint16_t)c1) << 8; return ret; } static uint32_t buf2u32(const vector<unsigned char>::iterator &it) { unsigned char c0 = *it; unsigned char c1 = *(it + 1); unsigned char c2 = *(it + 2); unsigned char c3 = *(it + 3); uint32_t ret = c0; ret |= ((uint32_t)c1) << 8; ret |= ((uint32_t)c2) << 16; ret |= ((uint32_t)c3) << 24; return ret; } static uint16_t read_u16(vector<unsigned char>::iterator &it) { uint16_t val = buf2u16(it); it += sizeof(uint16_t); return val; } static uint32_t read_u32(vector<unsigned char>::iterator &it) { uint32_t val = buf2u32(it); it += sizeof(uint32_t); return val; } /** * @throws std::ifstream::failure */ bool ZipFile::InitScan(ifstream &fp, const string &path) { uint32_t magic; /* The first word is always a Local File Header signature */ fp.read((char *)(&magic), sizeof(uint32_t)); if (magic != LFH_MAGIC) { zipError(path, "Bad Magic"); return false; } fp.seekg(0, ios_base::end); size_t total_size = fp.tellg(); /* Look for the End of Central Directory. It must be in the * last EOCD_SIZE + CMT_MAX bytes of the file */ int size = EOCD_SIZE + CMT_MAX; fp.seekg(-size, ios_base::end); vector<unsigned char> buffer(size); fp.read((char *)&(buffer[0]), size); vector<unsigned char>::iterator scan = buffer.begin(); vector<unsigned char>::iterator last_possible = buffer.end() - 4; uint32_t word; while (scan != last_possible) { word = buf2u32(scan); if (word == EOCD_MAGIC) break; scan++; } if (word != EOCD_MAGIC) { zipError(path, "Can't find EOCD"); return false; } scan += sizeof(uint32_t); /* Some heavy restrictions, at the moment * TODO: support more of ZIP format */ uint16_t nr_disk = read_u16(scan); assert(nr_disk == 0); uint16_t disk_start = read_u16(scan); assert(disk_start == 0); uint16_t nr_rec_on_disk = read_u16(scan); num_files = read_u16(scan); log(string("Number of files in the zip: ") + to_string(num_files)); assert(num_files == nr_rec_on_disk); uint32_t cd_size = read_u32(scan); uint32_t cd_offset = read_u32(scan); uint64_t comment_size = read_u16(scan); scan += comment_size; assert(scan == buffer.end()); buffer.clear(); /* Sanity check */ assert(cd_offset + cd_size <= total_size); files_info.resize(num_files); fp.seekg(cd_offset, ios_base::beg); size_t bytes = 0; buffer.resize(CDFH_SIZE); for (size_t nr = 0; nr < num_files; nr++) { log(string("Parsing file ") + to_string(nr)); ZipFileInfo *info = &(files_info[nr]); size_t start_pos = fp.tellg(); fp.read((char *)&(buffer[0]), CDFH_SIZE); scan = buffer.begin(); word = read_u32(scan); if (word != CDFH_MAGIC) { zipError(path, string("Can't find CDFH - ") + to_string(nr)); return false; } scan += sizeof(uint16_t); // skip "Version made by" scan += sizeof(uint16_t); // skip "Version needed to extract (minimum) scan += sizeof(uint16_t); // skip "General purpose bit flag" uint16_t compression_method = read_u16(scan); if (compression_method != 0) { info->compressed = true; assert(compression_method == 8 /* deflate */); } else { info->compressed = false; } scan += sizeof(uint16_t); // skip "File last modification time" scan += sizeof(uint16_t); // skip "File last modification date" scan += sizeof(uint32_t); // skip "CRC32" info->compressed_size = read_u32(scan); info->size = read_u32(scan); uint16_t file_name_length = read_u16(scan); assert(file_name_length != 0); uint16_t extra_field_length = read_u16(scan); uint16_t comment_length = read_u16(scan); disk_start = read_u16(scan); assert(disk_start == 0); scan += sizeof(uint16_t); // skip "internal file attributes" scan += sizeof(uint32_t); // skip "external file attributes" info->offset = read_u32(scan); assert(scan == buffer.end()); info->name.resize(file_name_length); fp.read((char *)&(info->name[0]), file_name_length); fp.seekg(extra_field_length + comment_length, ios_base::cur); size_t end_pos = fp.tellg(); bytes += end_pos - start_pos; if (info->size != 0) cout << files_info[nr] << endl; } assert(bytes == cd_size); return true; } <|endoftext|>
<commit_before>/* kopeteaccount.cpp - Kopete Account Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be> Copyright (c) 2003 by Martijn Klingens <klingens@kde.org> Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include <qlineedit.h> #include <qcheckbox.h> #include <qlabel.h> #include <qapplication.h> #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kdialogbase.h> #include <qtimer.h> #include "kopetecontactlist.h" #include "kopeteaccount.h" #include "kopeteaccountmanager.h" #include "kopetemetacontact.h" #include "kopetepassworddialog.h" #include "kopeteprotocol.h" #include "pluginloader.h" /* * Function for (en/de)crypting strings for config file, taken from KMail * Author: Stefan Taferner <taferner@alpin.or.at> */ QString cryptStr(const QString &aStr) { QString result; for (unsigned int i = 0; i < aStr.length(); i++) result += (aStr[i].unicode() < 0x20) ? aStr[i] : QChar(0x1001F - aStr[i].unicode()); return result; } struct KopeteAccountPrivate { KopeteProtocol *protocol; QString id; QString password; bool autologin; QDict<KopeteContact> contacts; QColor color; }; KopeteAccount::KopeteAccount(KopeteProtocol *parent, const QString& _accountId , const char *name): KopetePluginDataObject (parent, name) { d = new KopeteAccountPrivate; d->protocol = parent; d->id = _accountId; d->autologin = false; d->password = QString::null; d->color = QColor(); KopeteAccountManager::manager()->registerAccount( this ); QTimer::singleShot( 0, this, SLOT( slotAccountReady() ) ); } KopeteAccount::~KopeteAccount() { // Delete all registered child contacts first while ( !d->contacts.isEmpty() ) delete *QDictIterator<KopeteContact>( d->contacts ); KopeteAccountManager::manager()->unregisterAccount( this ); // Let the protocol know that one of its accounts // is no longer there d->protocol->refreshAccounts(); delete d; } void KopeteAccount::slotAccountReady() { KopeteAccountManager::manager()->notifyAccountReady( this ); } KopeteProtocol *KopeteAccount::protocol() const { return d->protocol; } QString KopeteAccount::accountId() const { return d->id; } const QColor KopeteAccount::color() const { return d->color; } void KopeteAccount::setColor( const QColor &color ) { d->color = color; } void KopeteAccount::setAccountId( const QString &accountId ) { if(d->id!=accountId) { d->id = accountId; emit ( accountIdChanged() ); } } QString KopeteAccount::configGroup() const { #if QT_VERSION < 0x030200 return QString::fromLatin1( "Account_%2_%1" ).arg( accountId() ).arg( protocol()->pluginId() ); #else return QString::fromLatin1( "Account_%2_%1" ).arg( accountId(), protocol()->pluginId() ); #endif } void KopeteAccount::writeConfig( const QString &configGroupName ) { KConfig *config = KGlobal::config(); config->setGroup( configGroupName ); config->writeEntry( "Protocol", d->protocol->pluginId() ); config->writeEntry( "AccountId", d->id ); if ( !d->password.isNull() ) config->writeEntry( "Password", cryptStr( d->password ) ); else config->deleteEntry( "Password" ); config->writeEntry( "AutoConnect", d->autologin ); if( d->color.isValid() ) config->writeEntry( "Color", d->color ); else config->deleteEntry( "Color" ); // Store other plugin data KopetePluginDataObject::writeConfig( configGroupName ); } void KopeteAccount::readConfig( const QString &configGroupName ) { KConfig *config = KGlobal::config(); config->setGroup( configGroupName ); d->password = cryptStr( config->readEntry( "Password" ) ); d->autologin = config->readBoolEntry( "AutoConnect", false ); d->color = config->readColorEntry( "Color", &d->color ); // Handle the plugin data, if any QMap<QString, QString> entries = config->entryMap( configGroupName ); QMap<QString, QString>::Iterator entryIt; QMap<QString, QMap<QString, QString> > pluginData; for ( entryIt = entries.begin(); entryIt != entries.end(); ++entryIt ) { if ( entryIt.key().startsWith( QString::fromLatin1( "PluginData_" ) ) ) { QStringList data = QStringList::split( '_', entryIt.key(), true ); data.pop_front(); // Strip "PluginData_" first QString pluginName = data.first(); data.pop_front(); // Join remainder and store it pluginData[ pluginName ][ data.join( QString::fromLatin1( "_" ) ) ] = entryIt.data(); } } // Lastly, pass on the plugin data to the account QMap<QString, QMap<QString, QString> >::Iterator pluginDataIt; for ( pluginDataIt = pluginData.begin(); pluginDataIt != pluginData.end(); ++pluginDataIt ) setPluginData( LibraryLoader::pluginLoader()->searchByID( pluginDataIt.key() ), pluginDataIt.data() ); loaded(); } void KopeteAccount::loaded() { /* do nothing in default implementation */ } QString KopeteAccount::password( bool error, bool *ok, unsigned int maxLength ) { if(ok) *ok=true; if ( !d->password.isNull() ) { //if the cached password was wrong, we remove it if ( error ) d->password = QString::null; else return d->password; } KDialogBase *passwdDialog = new KDialogBase( qApp->mainWidget() ,"passwdDialog", true, i18n( "Password Needed" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, true ); KopetePasswordDialog *view = new KopetePasswordDialog( passwdDialog ); if ( error ) view->m_text->setText(i18n("<b>The password was wrong! Please re-enter your password for %1</b>").arg(protocol()->displayName())); else view->m_text->setText(i18n("Please enter password for %1").arg(protocol()->displayName())); passwdDialog->setMainWidget(view); view->m_login->setText(d->id); view->m_autologin->setChecked( d->autologin ); if(maxLength!=0) view->m_password->setMaxLength(maxLength); view->adjustSize(); passwdDialog->adjustSize(); QString pass; if(passwdDialog->exec() == QDialog::Accepted ) { pass=view->m_password->text(); if(view->m_save_passwd->isChecked()) setPassword(pass); d->autologin=view->m_autologin->isChecked(); } else { if ( ok ) *ok = false; } passwdDialog->deleteLater(); return pass; } void KopeteAccount::setPassword( const QString &pass ) { d->password = pass; writeConfig( configGroup() ); } void KopeteAccount::setAutoLogin(bool b) { d->autologin=b; } bool KopeteAccount::autoLogin() const { return d->autologin; } bool KopeteAccount::rememberPassword() { return !d->password.isNull(); } void KopeteAccount::registerContact( KopeteContact *c ) { d->contacts.insert( c->contactId(), c ); QObject::connect( c, SIGNAL( contactDestroyed( KopeteContact * ) ), SLOT( slotKopeteContactDestroyed( KopeteContact * ) ) ); } void KopeteAccount::slotKopeteContactDestroyed( KopeteContact *c ) { // kdDebug(14010) << "KopeteProtocol::slotKopeteContactDestroyed: " << c->contactId() << endl; d->contacts.remove( c->contactId() ); } const QDict<KopeteContact>& KopeteAccount::contacts() { return d->contacts; } /*QDict<KopeteContact> KopeteAccount::contacts( KopeteMetaContact *mc ) { QDict<KopeteContact> result; QDictIterator<KopeteContact> it( d->contacts ); for ( ; it.current() ; ++it ) { if( ( *it )->metaContact() == mc ) result.insert( ( *it )->contactId(), *it ); } return result; }*/ bool KopeteAccount::addContact( const QString &contactId, const QString &displayName, KopeteMetaContact *parentContact, const QString &groupName, bool isTemporary ) { if(contactId==accountId()) { kdDebug(14010) << "KopeteAccount::addContact: WARNING: the user try to add myself to his contactlist - abort" << endl; return false; } KopeteContact *c=d->contacts[contactId]; if(c && c->metaContact()) { if(c->metaContact()->isTemporary() && !isTemporary) { kdDebug(14010) << "KopeteAccount::addContact: You are triying to add an existing temporary contact. Just add it on the list" << endl; parentContact->addToGroup( KopeteContactList::contactList()->getGroup( groupName ) ); } else // should we here add the contact to the parentContact if any? kdDebug(14010) << "KopeteAccount::addContact: Contact already exist" << endl; return false; } KopeteGroup *parentGroup=0L; //If this is a temporary contact, use the temporary group if(!groupName.isNull()) parentGroup = isTemporary ? KopeteGroup::temporary : KopeteContactList::contactList()->getGroup( groupName ); if( parentContact ) { //If we are given a MetaContact to add to that is marked as temporary. but //this contact is not temporary, then change the metacontact to non-temporary if( parentContact->isTemporary() && !isTemporary ) parentContact->setTemporary( false, parentGroup ); else parentContact->addToGroup( parentGroup ); } else { //Create a new MetaContact parentContact = new KopeteMetaContact(); parentContact->setDisplayName( displayName ); //Set it as a temporary contact if requested if( isTemporary ) parentContact->setTemporary(true); else parentContact->addToGroup( parentGroup ); KopeteContactList::contactList()->addMetaContact( parentContact ); } if( c ) { c->setMetaContact(parentContact); return true; } else return addContactToMetaContact( contactId, displayName, parentContact ); } KActionMenu* KopeteAccount::actionMenu() { //default implementation return 0L; } bool KopeteAccount::isConnected() const { return myself()->onlineStatus().status() != KopeteOnlineStatus::Offline; } bool KopeteAccount::isAway() const { return myself()->onlineStatus().status() == KopeteOnlineStatus::Away; } #include "kopeteaccount.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>CVS_SILENT cleaning up some coding style<commit_after>/* kopeteaccount.cpp - Kopete Account Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be> Copyright (c) 2003 by Martijn Klingens <klingens@kde.org> Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include <qlineedit.h> #include <qcheckbox.h> #include <qlabel.h> #include <qapplication.h> #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kdialogbase.h> #include <qtimer.h> #include "kopetecontactlist.h" #include "kopeteaccount.h" #include "kopeteaccountmanager.h" #include "kopetemetacontact.h" #include "kopetepassworddialog.h" #include "kopeteprotocol.h" #include "pluginloader.h" /* * Function for (en/de)crypting strings for config file, taken from KMail * Author: Stefan Taferner <taferner@alpin.or.at> */ QString cryptStr(const QString &aStr) { QString result; for (unsigned int i = 0; i < aStr.length(); i++) result += (aStr[i].unicode() < 0x20) ? aStr[i] : QChar(0x1001F - aStr[i].unicode()); return result; } struct KopeteAccountPrivate { KopeteProtocol *protocol; QString id; QString password; bool autologin; QDict<KopeteContact> contacts; QColor color; }; KopeteAccount::KopeteAccount(KopeteProtocol *parent, const QString& _accountId , const char *name): KopetePluginDataObject (parent, name) { d = new KopeteAccountPrivate; d->protocol = parent; d->id = _accountId; d->autologin = false; d->password = QString::null; d->color = QColor(); KopeteAccountManager::manager()->registerAccount( this ); QTimer::singleShot( 0, this, SLOT( slotAccountReady() ) ); } KopeteAccount::~KopeteAccount() { // Delete all registered child contacts first while ( !d->contacts.isEmpty() ) delete *QDictIterator<KopeteContact>( d->contacts ); KopeteAccountManager::manager()->unregisterAccount( this ); // Let the protocol know that one of its accounts // is no longer there d->protocol->refreshAccounts(); delete d; } void KopeteAccount::slotAccountReady() { KopeteAccountManager::manager()->notifyAccountReady( this ); } KopeteProtocol *KopeteAccount::protocol() const { return d->protocol; } QString KopeteAccount::accountId() const { return d->id; } const QColor KopeteAccount::color() const { return d->color; } void KopeteAccount::setColor( const QColor &color ) { d->color = color; } void KopeteAccount::setAccountId( const QString &accountId ) { if(d->id!=accountId) { d->id = accountId; emit ( accountIdChanged() ); } } QString KopeteAccount::configGroup() const { #if QT_VERSION < 0x030200 return QString::fromLatin1( "Account_%2_%1" ).arg( accountId() ).arg( protocol()->pluginId() ); #else return QString::fromLatin1( "Account_%2_%1" ).arg( accountId(), protocol()->pluginId() ); #endif } void KopeteAccount::writeConfig( const QString &configGroupName ) { KConfig *config = KGlobal::config(); config->setGroup( configGroupName ); config->writeEntry( "Protocol", d->protocol->pluginId() ); config->writeEntry( "AccountId", d->id ); if ( !d->password.isNull() ) config->writeEntry( "Password", cryptStr( d->password ) ); else config->deleteEntry( "Password" ); config->writeEntry( "AutoConnect", d->autologin ); if( d->color.isValid() ) config->writeEntry( "Color", d->color ); else config->deleteEntry( "Color" ); // Store other plugin data KopetePluginDataObject::writeConfig( configGroupName ); } void KopeteAccount::readConfig( const QString &configGroupName ) { KConfig *config = KGlobal::config(); config->setGroup( configGroupName ); d->password = cryptStr( config->readEntry( "Password" ) ); d->autologin = config->readBoolEntry( "AutoConnect", false ); d->color = config->readColorEntry( "Color", &d->color ); // Handle the plugin data, if any QMap<QString, QString> entries = config->entryMap( configGroupName ); QMap<QString, QString>::Iterator entryIt; QMap<QString, QMap<QString, QString> > pluginData; for ( entryIt = entries.begin(); entryIt != entries.end(); ++entryIt ) { if ( entryIt.key().startsWith( QString::fromLatin1( "PluginData_" ) ) ) { QStringList data = QStringList::split( '_', entryIt.key(), true ); data.pop_front(); // Strip "PluginData_" first QString pluginName = data.first(); data.pop_front(); // Join remainder and store it pluginData[ pluginName ][ data.join( QString::fromLatin1( "_" ) ) ] = entryIt.data(); } } // Lastly, pass on the plugin data to the account QMap<QString, QMap<QString, QString> >::Iterator pluginDataIt; for ( pluginDataIt = pluginData.begin(); pluginDataIt != pluginData.end(); ++pluginDataIt ) setPluginData( LibraryLoader::pluginLoader()->searchByID( pluginDataIt.key() ), pluginDataIt.data() ); loaded(); } void KopeteAccount::loaded() { /* do nothing in default implementation */ } QString KopeteAccount::password( bool error, bool *ok, unsigned int maxLength ) { if( ok ) *ok = true; if ( !d->password.isNull() ) { //if the cached password was wrong, we remove it if ( error ) d->password = QString::null; else return d->password; } KDialogBase *passwdDialog = new KDialogBase( qApp->mainWidget() ,"passwdDialog", true, i18n( "Password Needed" ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, true ); KopetePasswordDialog *view = new KopetePasswordDialog( passwdDialog ); if ( error ) { view->m_text->setText( i18n( "<b>The password was wrong! Please re-enter your password for %1</b>" ). arg( protocol()->displayName() ) ); } else { view->m_text->setText( i18n( "Please enter password for %1" ).arg( protocol()->displayName() ) ); } passwdDialog->setMainWidget( view ); view->m_login->setText( d->id ); view->m_autologin->setChecked( d->autologin ); if ( maxLength != 0 ) view->m_password->setMaxLength( maxLength ); view->adjustSize(); passwdDialog->adjustSize(); QString pass; if( passwdDialog->exec() == QDialog::Accepted ) { pass = view->m_password->text(); if ( view->m_save_passwd->isChecked() ) setPassword( pass ); d->autologin = view->m_autologin->isChecked(); } else { if ( ok ) *ok = false; } passwdDialog->deleteLater(); return pass; } void KopeteAccount::setPassword( const QString &pass ) { d->password = pass; writeConfig( configGroup() ); } void KopeteAccount::setAutoLogin(bool b) { d->autologin=b; } bool KopeteAccount::autoLogin() const { return d->autologin; } bool KopeteAccount::rememberPassword() { return !d->password.isNull(); } void KopeteAccount::registerContact( KopeteContact *c ) { d->contacts.insert( c->contactId(), c ); QObject::connect( c, SIGNAL( contactDestroyed( KopeteContact * ) ), SLOT( slotKopeteContactDestroyed( KopeteContact * ) ) ); } void KopeteAccount::slotKopeteContactDestroyed( KopeteContact *c ) { // kdDebug(14010) << "KopeteProtocol::slotKopeteContactDestroyed: " << c->contactId() << endl; d->contacts.remove( c->contactId() ); } const QDict<KopeteContact>& KopeteAccount::contacts() { return d->contacts; } /*QDict<KopeteContact> KopeteAccount::contacts( KopeteMetaContact *mc ) { QDict<KopeteContact> result; QDictIterator<KopeteContact> it( d->contacts ); for ( ; it.current() ; ++it ) { if( ( *it )->metaContact() == mc ) result.insert( ( *it )->contactId(), *it ); } return result; }*/ bool KopeteAccount::addContact( const QString &contactId, const QString &displayName, KopeteMetaContact *parentContact, const QString &groupName, bool isTemporary ) { if(contactId==accountId()) { kdDebug(14010) << "KopeteAccount::addContact: WARNING: the user try to add myself to his contactlist - abort" << endl; return false; } KopeteContact *c=d->contacts[contactId]; if(c && c->metaContact()) { if(c->metaContact()->isTemporary() && !isTemporary) { kdDebug(14010) << "KopeteAccount::addContact: You are triying to add an existing temporary contact. Just add it on the list" << endl; parentContact->addToGroup( KopeteContactList::contactList()->getGroup( groupName ) ); } else // should we here add the contact to the parentContact if any? kdDebug(14010) << "KopeteAccount::addContact: Contact already exist" << endl; return false; } KopeteGroup *parentGroup=0L; //If this is a temporary contact, use the temporary group if(!groupName.isNull()) parentGroup = isTemporary ? KopeteGroup::temporary : KopeteContactList::contactList()->getGroup( groupName ); if( parentContact ) { //If we are given a MetaContact to add to that is marked as temporary. but //this contact is not temporary, then change the metacontact to non-temporary if( parentContact->isTemporary() && !isTemporary ) parentContact->setTemporary( false, parentGroup ); else parentContact->addToGroup( parentGroup ); } else { //Create a new MetaContact parentContact = new KopeteMetaContact(); parentContact->setDisplayName( displayName ); //Set it as a temporary contact if requested if( isTemporary ) parentContact->setTemporary(true); else parentContact->addToGroup( parentGroup ); KopeteContactList::contactList()->addMetaContact( parentContact ); } if( c ) { c->setMetaContact(parentContact); return true; } else return addContactToMetaContact( contactId, displayName, parentContact ); } KActionMenu* KopeteAccount::actionMenu() { //default implementation return 0L; } bool KopeteAccount::isConnected() const { return myself()->onlineStatus().status() != KopeteOnlineStatus::Offline; } bool KopeteAccount::isAway() const { return myself()->onlineStatus().status() == KopeteOnlineStatus::Away; } #include "kopeteaccount.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/cert_verifier.h" #if defined(USE_NSS) #include <private/pprthred.h> // PR_DetatchThread #endif #include "base/message_loop.h" #include "base/worker_pool.h" #include "net/base/cert_verify_result.h" #include "net/base/net_errors.h" #include "net/base/x509_certificate.h" namespace net { class CertVerifier::Request : public base::RefCountedThreadSafe<CertVerifier::Request>, public MessageLoop::DestructionObserver { public: Request(CertVerifier* verifier, X509Certificate* cert, const std::string& hostname, int flags, CertVerifyResult* verify_result, CompletionCallback* callback) : cert_(cert), hostname_(hostname), flags_(flags), verifier_(verifier), verify_result_(verify_result), callback_(callback), origin_loop_(MessageLoop::current()), error_(OK) { if (origin_loop_) origin_loop_->AddDestructionObserver(this); } void DoVerify() { // Running on the worker thread error_ = cert_->Verify(hostname_, flags_, &result_); #if defined(USE_NSS) // Detach the thread from NSPR. // Calling NSS functions attaches the thread to NSPR, which stores // the NSPR thread ID in thread-specific data. // The threads in our thread pool terminate after we have called // PR_Cleanup. Unless we detach them from NSPR, net_unittests gets // segfaults on shutdown when the threads' thread-specific data // destructors run. PR_DetachThread(); #endif Task* reply = NewRunnableMethod(this, &Request::DoCallback); // The origin loop could go away while we are trying to post to it, so we // need to call its PostTask method inside a lock. See ~CertVerifier. { AutoLock locked(origin_loop_lock_); if (origin_loop_) { origin_loop_->PostTask(FROM_HERE, reply); reply = NULL; } } // Does nothing if it got posted. delete reply; } void DoCallback() { // Running on the origin thread. // We may have been cancelled! if (!verifier_) return; *verify_result_ = result_; // Drop the verifier's reference to us. Do this before running the // callback since the callback might result in the verifier being // destroyed. verifier_->request_ = NULL; callback_->Run(error_); } void Cancel() { verifier_ = NULL; AutoLock locked(origin_loop_lock_); if (origin_loop_) { origin_loop_->RemoveDestructionObserver(this); origin_loop_ = NULL; } } // MessageLoop::DestructionObserver override. virtual void WillDestroyCurrentMessageLoop() { LOG(ERROR) << "CertVerifier wasn't deleted before the thread was deleted."; AutoLock locked(origin_loop_lock_); origin_loop_ = NULL; } private: friend class base::RefCountedThreadSafe<CertVerifier::Request>; ~Request() { Cancel(); } // Set on the origin thread, read on the worker thread. scoped_refptr<X509Certificate> cert_; std::string hostname_; // bitwise OR'd of X509Certificate::VerifyFlags. int flags_; // Only used on the origin thread (where Verify was called). CertVerifier* verifier_; CertVerifyResult* verify_result_; CompletionCallback* callback_; // Used to post ourselves onto the origin thread. Lock origin_loop_lock_; MessageLoop* origin_loop_; // Assigned on the worker thread, read on the origin thread. int error_; CertVerifyResult result_; }; //----------------------------------------------------------------------------- CertVerifier::CertVerifier() { } CertVerifier::~CertVerifier() { if (request_) request_->Cancel(); } int CertVerifier::Verify(X509Certificate* cert, const std::string& hostname, int flags, CertVerifyResult* verify_result, CompletionCallback* callback) { DCHECK(!request_) << "verifier already in use"; // Do a synchronous verification. if (!callback) { CertVerifyResult result; int rv = cert->Verify(hostname, flags, &result); *verify_result = result; return rv; } request_ = new Request(this, cert, hostname, flags, verify_result, callback); // Dispatch to worker thread... if (!WorkerPool::PostTask(FROM_HERE, NewRunnableMethod(request_.get(), &Request::DoVerify), true)) { NOTREACHED(); request_ = NULL; return ERR_FAILED; } return ERR_IO_PENDING; } } // namespace net <commit_msg>Revert 65349 - Update CertVerifier to watch for the origin loop's destruction, so that it doesn't crash if the SSLClientSocket is leaked.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/cert_verifier.h" #if defined(USE_NSS) #include <private/pprthred.h> // PR_DetatchThread #endif #include "base/message_loop.h" #include "base/worker_pool.h" #include "net/base/cert_verify_result.h" #include "net/base/net_errors.h" #include "net/base/x509_certificate.h" namespace net { class CertVerifier::Request : public base::RefCountedThreadSafe<CertVerifier::Request> { public: Request(CertVerifier* verifier, X509Certificate* cert, const std::string& hostname, int flags, CertVerifyResult* verify_result, CompletionCallback* callback) : cert_(cert), hostname_(hostname), flags_(flags), verifier_(verifier), verify_result_(verify_result), callback_(callback), origin_loop_(MessageLoop::current()), error_(OK) { } void DoVerify() { // Running on the worker thread error_ = cert_->Verify(hostname_, flags_, &result_); #if defined(USE_NSS) // Detach the thread from NSPR. // Calling NSS functions attaches the thread to NSPR, which stores // the NSPR thread ID in thread-specific data. // The threads in our thread pool terminate after we have called // PR_Cleanup. Unless we detach them from NSPR, net_unittests gets // segfaults on shutdown when the threads' thread-specific data // destructors run. PR_DetachThread(); #endif Task* reply = NewRunnableMethod(this, &Request::DoCallback); // The origin loop could go away while we are trying to post to it, so we // need to call its PostTask method inside a lock. See ~CertVerifier. { AutoLock locked(origin_loop_lock_); if (origin_loop_) { origin_loop_->PostTask(FROM_HERE, reply); reply = NULL; } } // Does nothing if it got posted. delete reply; } void DoCallback() { // Running on the origin thread. // We may have been cancelled! if (!verifier_) return; *verify_result_ = result_; // Drop the verifier's reference to us. Do this before running the // callback since the callback might result in the verifier being // destroyed. verifier_->request_ = NULL; callback_->Run(error_); } void Cancel() { verifier_ = NULL; AutoLock locked(origin_loop_lock_); origin_loop_ = NULL; } private: friend class base::RefCountedThreadSafe<CertVerifier::Request>; ~Request() {} // Set on the origin thread, read on the worker thread. scoped_refptr<X509Certificate> cert_; std::string hostname_; // bitwise OR'd of X509Certificate::VerifyFlags. int flags_; // Only used on the origin thread (where Verify was called). CertVerifier* verifier_; CertVerifyResult* verify_result_; CompletionCallback* callback_; // Used to post ourselves onto the origin thread. Lock origin_loop_lock_; MessageLoop* origin_loop_; // Assigned on the worker thread, read on the origin thread. int error_; CertVerifyResult result_; }; //----------------------------------------------------------------------------- CertVerifier::CertVerifier() { } CertVerifier::~CertVerifier() { if (request_) request_->Cancel(); } int CertVerifier::Verify(X509Certificate* cert, const std::string& hostname, int flags, CertVerifyResult* verify_result, CompletionCallback* callback) { DCHECK(!request_) << "verifier already in use"; // Do a synchronous verification. if (!callback) { CertVerifyResult result; int rv = cert->Verify(hostname, flags, &result); *verify_result = result; return rv; } request_ = new Request(this, cert, hostname, flags, verify_result, callback); // Dispatch to worker thread... if (!WorkerPool::PostTask(FROM_HERE, NewRunnableMethod(request_.get(), &Request::DoVerify), true)) { NOTREACHED(); request_ = NULL; return ERR_FAILED; } return ERR_IO_PENDING; } } // namespace net <|endoftext|>
<commit_before>/* * Jamoma 2-Dimensional Matrix Data Class * Copyright © 2011-2012, Timothy Place & Nathan Wolek * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTMatrix.h" #include "TTEnvironment.h" #include "TTBase.h" #define thisTTClass TTMatrix #define thisTTClassName "matrix" #define thisTTClassTags "matrix" TT_OBJECT_CONSTRUCTOR, mData(NULL), mRowCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?) mColumnCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?) mElementCount(1), mComponentCount(1), mComponentStride(1), mDataCount(0), mType(TT("uint8")), mTypeSizeInBytes(1), mDataSize(0), mDataIsLocallyOwned(YES), mHeadPtr(NULL), mTailPtr(NULL) { addAttributeWithGetterAndSetter(Dimensions, kTypeUInt32); // DEPRECATION in progress addAttributeWithSetter(RowCount, kTypeUInt32); addAttributeWithSetter(ColumnCount, kTypeUInt32); addAttributeWithSetter(Type, kTypeUInt8); addAttributeWithSetter(ElementCount, kTypeUInt8); addMessage(clear); addMessageWithArguments(fill); addMessageWithArguments(get); addMessageWithArguments(set); // TODO: getLockedPointer -- returns a pointer to the data, locks the matrix mutex // TODO: releaseLockedPointer -- releases the matrix mutex // TODO: the above two items mean we need a TTMutex member resize(); // DEPRECATION in progress: setAttributeValue(TT("dimensions"), kTTVal1); } TTMatrix::~TTMatrix() { if (mDataIsLocallyOwned) delete[] mData; // TODO: only do this if the refcount for the data is down to zero! } TTErr TTMatrix::resize() { mComponentCount = mRowCount * mColumnCount; mDataCount = mComponentCount * mElementCount; mDataSize = mDataCount * mTypeSizeInBytes; mComponentStride = mTypeSizeInBytes * mElementCount; if (mDataIsLocallyOwned) { // TODO: currently, we are not preserving memory when resizing. Should we try to preserve the previous memory contents? // TODO: thread protection delete[] mData; mData = new TTByte[mDataSize]; mHeadPtr = mData; mTailPtr = mData + mDataSize; } if (mDataSize && mData) { return kTTErrNone; } else { return kTTErrAllocFailed; } } TTErr TTMatrix::copy(const TTMatrix& source, TTMatrix& dest) { dest.adaptTo(source); memcpy(dest.mData, source.mData, source.mDataSize); return kTTErrNone; } TTErr TTMatrix::adaptTo(const TTMatrix& anotherMatrix) { TTValue v; // TODO: what should we do if anotherMatrix is not locally owned? // It would be nice to re-dimension the data, but we can't re-alloc / resize the number of bytes... anotherMatrix.getDimensions(v); setDimensions(v); setType(anotherMatrix.mType); setElementCount(anotherMatrix.mElementCount); return kTTErrNone; } TTBoolean TTMatrix::setRowCountWithoutResize(TTUInt32 aNewRowCount) { if (aNewRowCount > 0) { mRowCount = aNewRowCount; return true; } else { return false; } } TTBoolean TTMatrix::setColumnCountWithoutResize(TTUInt32 aNewColumnCount) { if (aNewColumnCount > 0) { mColumnCount = aNewColumnCount; return true; } else { return false; } } TTBoolean TTMatrix::setElementCountWithoutResize(TTUInt8 aNewElementCount) { if (aNewElementCount > 0) { mElementCount = aNewElementCount; return true; } else { return false; } } TTBoolean TTMatrix::setTypeWithoutResize(TTDataInfoPtr aNewType) { if (aNewType->isNumerical) { mType = aNewType->name; mTypeSizeInBytes = (aNewType->bitdepth / 8); return true; } else { return false; } } TTErr TTMatrix::setRowCount(const TTValue& aNewRowCount) { TTUInt32 aNewRowCountInt = aNewRowCount; if (setRowCountWithoutResize(aNewRowCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setColumnCount(const TTValue& aNewColumnCount) { TTUInt32 aNewColumnCountInt = aNewColumnCount; if (setColumnCountWithoutResize(aNewColumnCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setElementCount(const TTValue& newElementCount) { TTUInt8 aNewElementCountInt = newElementCount; if (setElementCountWithoutResize(aNewElementCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setType(const TTValue& aType) { TTSymbolPtr aNewTypeName = aType; TTDataInfoPtr aNewDataType = TTDataInfo::getInfoForType(aNewTypeName); if (setTypeWithoutResize(aNewDataType)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setDimensions(const TTValue& someNewDimensions) { TTUInt32 aNewRowCount = 1; TTUInt32 aNewColumnCount = 1; TTUInt8 size = someNewDimensions.getSize(); // needed to support old calls with 1 or 2 dimensions if (size > 0) { someNewDimensions.get(0, aNewRowCount); } if (size > 1) { someNewDimensions.get(1, aNewColumnCount); } if (this->setRowCountWithoutResize(aNewRowCount) && this->setColumnCountWithoutResize(aNewColumnCount)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::getDimensions(TTValue& returnedDimensions) const { returnedDimensions.setSize(2); returnedDimensions.set(0, mRowCount); returnedDimensions.set(1, mColumnCount); return kTTErrNone; } TTErr TTMatrix::clear() { memset(mData, 0, mDataSize); return kTTErrNone; } TTErr TTMatrix::fill(const TTValue& anInputValue, TTValue &anUnusedOutputValue) { TTBytePtr fillValue = new TTByte[mComponentStride]; // TODO: here we have this ugly switch again... if (mType == TT("uint8")) anInputValue.getArray((TTUInt8*)fillValue, mElementCount); else if (mType == TT("int32")) anInputValue.getArray((TTInt32*)fillValue, mElementCount); else if (mType == TT("float32")) anInputValue.getArray((TTFloat32*)fillValue, mElementCount); else if (mType == TT("float64")) anInputValue.getArray((TTFloat64*)fillValue, mElementCount); for (TTUInt32 i=0; i<mDataSize; i += mComponentStride) memcpy(mData+i, fillValue, mComponentStride); delete[] fillValue; return kTTErrNone; } /* To find the index in the matrix: 1D Matrix: index = x 2D Matrix: index = dim_0 y + x 3D Matrix: index = dim_0 dim_1 z + dim_0 y + x etc. */ // args passed-in should be the 2 coordinates // args returned will be the value(s) at those coordinates TTErr TTMatrix::get(const TTValue& anInputValue, TTValue &anOutputValue) const { TTUInt16 dimensionCount = anInputValue.getSize(); if (dimensionCount != 2) // 2 dimensions only return kTTErrWrongNumValues; /* TTUInt32 i, j, index; anInputValue.get(0, i); anInputValue.get(1, j) index = i*mColumnCount+j; */ int productOfLowerDimensionSizes = 1; int index = 0; for (int d=0; d<dimensionCount; d++) { int position = anInputValue.getInt32(d); index += position * productOfLowerDimensionSizes; productOfLowerDimensionSizes *= mDimensions[d]; } anOutputValue.clear(); // TODO: here we have this ugly switch again... // Maybe we could just have duplicate pointers of different types in our class, and then we could access them more cleanly? if (mType == TT("uint8")) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTUInt8*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("int32")) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTInt32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("float32")) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTFloat32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("float64")) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTFloat64*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } return kTTErrNone; } /* template<typename T> TTErr TTMatrix::get2dWithinBounds(TTRowID i, TTColumnID j, T& data) { //TTUInt32 m = mRowCount; TTUInt32 n = mColumnCount; i -= 1; // convert to zero-based indices for data access j -= 1; // convert to zero-based indices for data access TTUInt32 distanceFromHead = (i*n+j) * mComponentStride; TTBoolean isInBounds = inBoundsZeroIndex(distanceFromHead); if (isInBounds) { data = *(T*)(mData + distanceFromHead); return kTTErrNone; } else { return kTTErrInvalidValue; } } */ // args passed-in should be the coordinates plus the value TTErr TTMatrix::set(const TTValue& anInputValue, TTValue &anUnusedOutputValue) { TTValue theValue; TTValue theDimensions = anInputValue; TTUInt16 dimensionCount = anInputValue.getSize() - mElementCount; if (dimensionCount != ( 2 + mElementCount )) // 2 dimensions plus number of elements at coordinates return kTTErrWrongNumValues; theValue.copyFrom(anInputValue, dimensionCount); theDimensions.setSize(dimensionCount); int productOfLowerDimensionSizes = 1; int index = 0; for (int d=0; d<dimensionCount; d++) { int position = anInputValue.getInt32(d) - 1; // subtract 1 to get back to zero-based indices for mem access in C index += position * productOfLowerDimensionSizes; productOfLowerDimensionSizes *= mDimensions[d]; } if (mType == TT("uint8")) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTUInt8*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("int32")) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTInt32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("float32")) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTFloat32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("float64")) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTFloat64*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } return kTTErrNone; } TTBoolean TTMatrix::allAttributesMatch(const TTMatrix* A, const TTMatrix* B) { if (A->mType == B->mType && A->mElementCount == B->mElementCount && A->mRowCount == B->mRowCount && A->mColumnCount == B->mColumnCount) { return true; } else { return false; } } TTErr TTMatrix::iterate(TTMatrix* C, const TTMatrix* A, const TTMatrix* B, TTMatrixIterator iterator) { //TTBoolean AmatchesB = allAttributesMatch(A, B); if (true) { int stride = A->mTypeSizeInBytes; int size = A->mDataSize; TTValue dims; // DEPRECATION in progress C->setAttributeValue(kTTSym_type, A->mType); C->setAttributeValue(kTTSym_elementCount, A->mElementCount); /* DEPRECATION in progress: the following section had to be changed to prevent malloc errors. results are less efficient code, but this will be regained once mRowCount & mColumnCount are fully implemented. */ dims.setSize(2); dims.set(0, A->mRowCount); dims.set(1, A->mColumnCount); C->setAttributeValue(kTTSym_dimensions, dims); /* DEPRECATION in progress: end section to be changed */ for (int k=0; k<size; k+=stride) (*iterator)(C->mData+k, A->mData+k, B->mData+k); return kTTErrNone; } else return kTTErrGeneric; } <commit_msg>TTMatrix:set correction to dimensionCount check<commit_after>/* * Jamoma 2-Dimensional Matrix Data Class * Copyright © 2011-2012, Timothy Place & Nathan Wolek * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTMatrix.h" #include "TTEnvironment.h" #include "TTBase.h" #define thisTTClass TTMatrix #define thisTTClassName "matrix" #define thisTTClassTags "matrix" TT_OBJECT_CONSTRUCTOR, mData(NULL), mRowCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?) mColumnCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?) mElementCount(1), mComponentCount(1), mComponentStride(1), mDataCount(0), mType(TT("uint8")), mTypeSizeInBytes(1), mDataSize(0), mDataIsLocallyOwned(YES), mHeadPtr(NULL), mTailPtr(NULL) { addAttributeWithGetterAndSetter(Dimensions, kTypeUInt32); // DEPRECATION in progress addAttributeWithSetter(RowCount, kTypeUInt32); addAttributeWithSetter(ColumnCount, kTypeUInt32); addAttributeWithSetter(Type, kTypeUInt8); addAttributeWithSetter(ElementCount, kTypeUInt8); addMessage(clear); addMessageWithArguments(fill); addMessageWithArguments(get); addMessageWithArguments(set); // TODO: getLockedPointer -- returns a pointer to the data, locks the matrix mutex // TODO: releaseLockedPointer -- releases the matrix mutex // TODO: the above two items mean we need a TTMutex member resize(); // DEPRECATION in progress: setAttributeValue(TT("dimensions"), kTTVal1); } TTMatrix::~TTMatrix() { if (mDataIsLocallyOwned) delete[] mData; // TODO: only do this if the refcount for the data is down to zero! } TTErr TTMatrix::resize() { mComponentCount = mRowCount * mColumnCount; mDataCount = mComponentCount * mElementCount; mDataSize = mDataCount * mTypeSizeInBytes; mComponentStride = mTypeSizeInBytes * mElementCount; if (mDataIsLocallyOwned) { // TODO: currently, we are not preserving memory when resizing. Should we try to preserve the previous memory contents? // TODO: thread protection delete[] mData; mData = new TTByte[mDataSize]; mHeadPtr = mData; mTailPtr = mData + mDataSize; } if (mDataSize && mData) { return kTTErrNone; } else { return kTTErrAllocFailed; } } TTErr TTMatrix::copy(const TTMatrix& source, TTMatrix& dest) { dest.adaptTo(source); memcpy(dest.mData, source.mData, source.mDataSize); return kTTErrNone; } TTErr TTMatrix::adaptTo(const TTMatrix& anotherMatrix) { TTValue v; // TODO: what should we do if anotherMatrix is not locally owned? // It would be nice to re-dimension the data, but we can't re-alloc / resize the number of bytes... anotherMatrix.getDimensions(v); setDimensions(v); setType(anotherMatrix.mType); setElementCount(anotherMatrix.mElementCount); return kTTErrNone; } TTBoolean TTMatrix::setRowCountWithoutResize(TTUInt32 aNewRowCount) { if (aNewRowCount > 0) { mRowCount = aNewRowCount; return true; } else { return false; } } TTBoolean TTMatrix::setColumnCountWithoutResize(TTUInt32 aNewColumnCount) { if (aNewColumnCount > 0) { mColumnCount = aNewColumnCount; return true; } else { return false; } } TTBoolean TTMatrix::setElementCountWithoutResize(TTUInt8 aNewElementCount) { if (aNewElementCount > 0) { mElementCount = aNewElementCount; return true; } else { return false; } } TTBoolean TTMatrix::setTypeWithoutResize(TTDataInfoPtr aNewType) { if (aNewType->isNumerical) { mType = aNewType->name; mTypeSizeInBytes = (aNewType->bitdepth / 8); return true; } else { return false; } } TTErr TTMatrix::setRowCount(const TTValue& aNewRowCount) { TTUInt32 aNewRowCountInt = aNewRowCount; if (setRowCountWithoutResize(aNewRowCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setColumnCount(const TTValue& aNewColumnCount) { TTUInt32 aNewColumnCountInt = aNewColumnCount; if (setColumnCountWithoutResize(aNewColumnCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setElementCount(const TTValue& newElementCount) { TTUInt8 aNewElementCountInt = newElementCount; if (setElementCountWithoutResize(aNewElementCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setType(const TTValue& aType) { TTSymbolPtr aNewTypeName = aType; TTDataInfoPtr aNewDataType = TTDataInfo::getInfoForType(aNewTypeName); if (setTypeWithoutResize(aNewDataType)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setDimensions(const TTValue& someNewDimensions) { TTUInt32 aNewRowCount = 1; TTUInt32 aNewColumnCount = 1; TTUInt8 size = someNewDimensions.getSize(); // needed to support old calls with 1 or 2 dimensions if (size > 0) { someNewDimensions.get(0, aNewRowCount); } if (size > 1) { someNewDimensions.get(1, aNewColumnCount); } if (this->setRowCountWithoutResize(aNewRowCount) && this->setColumnCountWithoutResize(aNewColumnCount)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::getDimensions(TTValue& returnedDimensions) const { returnedDimensions.setSize(2); returnedDimensions.set(0, mRowCount); returnedDimensions.set(1, mColumnCount); return kTTErrNone; } TTErr TTMatrix::clear() { memset(mData, 0, mDataSize); return kTTErrNone; } TTErr TTMatrix::fill(const TTValue& anInputValue, TTValue &anUnusedOutputValue) { TTBytePtr fillValue = new TTByte[mComponentStride]; // TODO: here we have this ugly switch again... if (mType == TT("uint8")) anInputValue.getArray((TTUInt8*)fillValue, mElementCount); else if (mType == TT("int32")) anInputValue.getArray((TTInt32*)fillValue, mElementCount); else if (mType == TT("float32")) anInputValue.getArray((TTFloat32*)fillValue, mElementCount); else if (mType == TT("float64")) anInputValue.getArray((TTFloat64*)fillValue, mElementCount); for (TTUInt32 i=0; i<mDataSize; i += mComponentStride) memcpy(mData+i, fillValue, mComponentStride); delete[] fillValue; return kTTErrNone; } /* To find the index in the matrix: 1D Matrix: index = x 2D Matrix: index = dim_0 y + x 3D Matrix: index = dim_0 dim_1 z + dim_0 y + x etc. */ // args passed-in should be the 2 coordinates // args returned will be the value(s) at those coordinates TTErr TTMatrix::get(const TTValue& anInputValue, TTValue &anOutputValue) const { TTUInt16 dimensionCount = anInputValue.getSize(); if (dimensionCount != 2) // 2 dimensions only return kTTErrWrongNumValues; /* TTUInt32 i, j, index; anInputValue.get(0, i); anInputValue.get(1, j) index = i*mColumnCount+j; */ int productOfLowerDimensionSizes = 1; int index = 0; for (int d=0; d<dimensionCount; d++) { int position = anInputValue.getInt32(d); index += position * productOfLowerDimensionSizes; productOfLowerDimensionSizes *= mDimensions[d]; } anOutputValue.clear(); // TODO: here we have this ugly switch again... // Maybe we could just have duplicate pointers of different types in our class, and then we could access them more cleanly? if (mType == TT("uint8")) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTUInt8*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("int32")) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTInt32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("float32")) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTFloat32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("float64")) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTFloat64*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } return kTTErrNone; } /* template<typename T> TTErr TTMatrix::get2dWithinBounds(TTRowID i, TTColumnID j, T& data) { //TTUInt32 m = mRowCount; TTUInt32 n = mColumnCount; i -= 1; // convert to zero-based indices for data access j -= 1; // convert to zero-based indices for data access TTUInt32 distanceFromHead = (i*n+j) * mComponentStride; TTBoolean isInBounds = inBoundsZeroIndex(distanceFromHead); if (isInBounds) { data = *(T*)(mData + distanceFromHead); return kTTErrNone; } else { return kTTErrInvalidValue; } } */ // args passed-in should be the coordinates plus the value TTErr TTMatrix::set(const TTValue& anInputValue, TTValue &anUnusedOutputValue) { TTValue theValue; TTValue theDimensions = anInputValue; TTUInt16 dimensionCount = anInputValue.getSize() - mElementCount; if (dimensionCount != 2) // 2 dimensions only return kTTErrWrongNumValues; theValue.copyFrom(anInputValue, dimensionCount); theDimensions.setSize(dimensionCount); int productOfLowerDimensionSizes = 1; int index = 0; for (int d=0; d<dimensionCount; d++) { int position = anInputValue.getInt32(d) - 1; // subtract 1 to get back to zero-based indices for mem access in C index += position * productOfLowerDimensionSizes; productOfLowerDimensionSizes *= mDimensions[d]; } if (mType == TT("uint8")) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTUInt8*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("int32")) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTInt32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("float32")) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTFloat32*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } else if (mType == TT("float64")) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTFloat64*)(mData+(index*mComponentStride+e*mTypeSizeInBytes))); } return kTTErrNone; } TTBoolean TTMatrix::allAttributesMatch(const TTMatrix* A, const TTMatrix* B) { if (A->mType == B->mType && A->mElementCount == B->mElementCount && A->mRowCount == B->mRowCount && A->mColumnCount == B->mColumnCount) { return true; } else { return false; } } TTErr TTMatrix::iterate(TTMatrix* C, const TTMatrix* A, const TTMatrix* B, TTMatrixIterator iterator) { //TTBoolean AmatchesB = allAttributesMatch(A, B); if (true) { int stride = A->mTypeSizeInBytes; int size = A->mDataSize; TTValue dims; // DEPRECATION in progress C->setAttributeValue(kTTSym_type, A->mType); C->setAttributeValue(kTTSym_elementCount, A->mElementCount); /* DEPRECATION in progress: the following section had to be changed to prevent malloc errors. results are less efficient code, but this will be regained once mRowCount & mColumnCount are fully implemented. */ dims.setSize(2); dims.set(0, A->mRowCount); dims.set(1, A->mColumnCount); C->setAttributeValue(kTTSym_dimensions, dims); /* DEPRECATION in progress: end section to be changed */ for (int k=0; k<size; k+=stride) (*iterator)(C->mData+k, A->mData+k, B->mData+k); return kTTErrNone; } else return kTTErrGeneric; } <|endoftext|>
<commit_before>/** * @file SyncedWait.hpp * @brief SyncedWait class prototype. * @author zer0 * @date 2019-09-11 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_TIME_SYNCEDWAIT_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_TIME_SYNCEDWAIT_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/Err.hpp> #include <libtbag/Noncopyable.hpp> #include <string> #include <atomic> #include <functional> #include <future> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace time { /** * SyncedWait class prototype. * * @author zer0 * @date 2019-09-11 */ class TBAG_API SyncedWait : private Noncopyable { public: TBAG_CONSTEXPR static char const * const STATE_NONE = "NONE"; TBAG_CONSTEXPR static char const * const STATE_READY = "READY"; TBAG_CONSTEXPR static char const * const STATE_INITIALIZING = "INITIALIZING"; TBAG_CONSTEXPR static char const * const STATE_RUNNING = "RUNNING"; TBAG_CONSTEXPR static char const * const STATE_DONE = "DONE"; TBAG_CONSTEXPR static char const * const STATE_ERROR = "ERROR"; public: class RunningSignal TBAG_FINAL : private Noncopyable { private: SyncedWait & _parent; public: RunningSignal(SyncedWait & parent) : _parent(parent) { /* EMPTY. */ } ~RunningSignal() { /* EMPTY. */ } public: inline void nowRunning() TBAG_NOEXCEPT_SP_OP(_parent._state.store(State::S_RUNNING)) { _parent._state.store(State::S_RUNNING); } }; friend class RunningSignal; public: enum class State { S_NONE, S_READY, S_INITIALIZING, S_RUNNING, S_DONE, S_ERROR, }; public: using AtomicState = std::atomic<State>; using ErrFuture = std::future<Err>; using Callback = std::function<Err(RunningSignal&)>; private: AtomicState _state; ErrFuture _future; public: SyncedWait(); ~SyncedWait(); public: static char const * getStateName(State s) TBAG_NOEXCEPT; static State getState(std::string const & s) TBAG_NOEXCEPT; public: inline State state() const TBAG_NOEXCEPT_SP_OP(_state.load()) { return _state.load(); } public: Err run(Callback const & cb, int timeout_ms, int tick_ms = 1); public: Err get(); }; } // namespace time // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_TIME_SYNCEDWAIT_HPP__ <commit_msg>Fixed build error in Ubuntu-GCC.<commit_after>/** * @file SyncedWait.hpp * @brief SyncedWait class prototype. * @author zer0 * @date 2019-09-11 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_TIME_SYNCEDWAIT_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_TIME_SYNCEDWAIT_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/Err.hpp> #include <libtbag/Noncopyable.hpp> #include <string> #include <atomic> #include <functional> #include <future> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace time { /** * SyncedWait class prototype. * * @author zer0 * @date 2019-09-11 */ class TBAG_API SyncedWait : private Noncopyable { public: TBAG_CONSTEXPR static char const * const STATE_NONE = "NONE"; TBAG_CONSTEXPR static char const * const STATE_READY = "READY"; TBAG_CONSTEXPR static char const * const STATE_INITIALIZING = "INITIALIZING"; TBAG_CONSTEXPR static char const * const STATE_RUNNING = "RUNNING"; TBAG_CONSTEXPR static char const * const STATE_DONE = "DONE"; TBAG_CONSTEXPR static char const * const STATE_ERROR = "ERROR"; public: class RunningSignal TBAG_FINAL : private Noncopyable { private: SyncedWait & _parent; public: RunningSignal(SyncedWait & parent) : _parent(parent) { /* EMPTY. */ } ~RunningSignal() { /* EMPTY. */ } public: inline void nowRunning() { _parent.setRunning(); } }; friend class RunningSignal; public: enum class State { S_NONE, S_READY, S_INITIALIZING, S_RUNNING, S_DONE, S_ERROR, }; public: using AtomicState = std::atomic<State>; using ErrFuture = std::future<Err>; using Callback = std::function<Err(RunningSignal&)>; private: AtomicState _state; ErrFuture _future; public: SyncedWait(); ~SyncedWait(); public: static char const * getStateName(State s) TBAG_NOEXCEPT; static State getState(std::string const & s) TBAG_NOEXCEPT; private: inline void setRunning() TBAG_NOEXCEPT_SP_OP(_state.store(State::S_RUNNING)) { _state.store(State::S_RUNNING); } public: inline State state() const TBAG_NOEXCEPT_SP_OP(_state.load()) { return _state.load(); } public: Err run(Callback const & cb, int timeout_ms, int tick_ms = 1); public: Err get(); }; } // namespace time // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_TIME_SYNCEDWAIT_HPP__ <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <memory> #include <caf/fwd.hpp> namespace vast::system { // -- classes ------------------------------------------------------------------ class application; class column_index; class configuration; class default_application; class export_command; class import_command; class indexer_manager; class indexer_stage_driver; class node_command; class partition; class pcap_reader_command; class pcap_writer_command; class reader_command_base; class remote_command; class start_command; class table_index; class writer_command_base; // -- structs ------------------------------------------------------------------ struct query_statistics; // -- templates ---------------------------------------------------------------- template <class Reader> class reader_command; template <class Writer> class writer_command; // -- aliases ------------------------------------------------------------------ using column_index_ptr = std::unique_ptr<column_index>; using partition_ptr = caf::intrusive_ptr<partition>; } // namespace vast::system <commit_msg>Add forward declaration for partition_index<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <memory> #include <caf/fwd.hpp> namespace vast::system { // -- classes ------------------------------------------------------------------ class application; class column_index; class configuration; class default_application; class export_command; class import_command; class indexer_manager; class indexer_stage_driver; class node_command; class partition; class partition_index; class pcap_reader_command; class pcap_writer_command; class reader_command_base; class remote_command; class start_command; class table_index; class writer_command_base; // -- structs ------------------------------------------------------------------ struct query_statistics; // -- templates ---------------------------------------------------------------- template <class Reader> class reader_command; template <class Writer> class writer_command; // -- aliases ------------------------------------------------------------------ using column_index_ptr = std::unique_ptr<column_index>; using partition_ptr = caf::intrusive_ptr<partition>; } // namespace vast::system <|endoftext|>
<commit_before>#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" using namespace std; using namespace cv; Mat src; Mat dst; char window_name1[] = "Unprocessed Image"; char window_name2[] = "Processed Image"; int main( int argc, char** argv ) { /// Load the source image src = imread( argv[1], 1 ); namedWindow( window_name1, WINDOW_AUTOSIZE ); imshow("Unprocessed Image",src); dst = src.clone(); GaussianBlur( src, dst, Size( 15, 15 ), 0, 0 ); namedWindow( window_name2, WINDOW_AUTOSIZE ); imshow("Processed Image",dst); waitKey(); return 0; }<commit_msg>add opencv-pure: blur image sample<commit_after>#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" using namespace std; using namespace cv; Mat src; Mat dst; char window_name1[] = "Unprocessed Image"; char window_name2[] = "Processed Image"; int main( int argc, char** argv ){ /// Load the source image src = imread( argv[1], 1 ); namedWindow( window_name1, WINDOW_AUTOSIZE ); imshow("Unprocessed Image",src); dst = src.clone(); GaussianBlur( src, dst, Size( 15, 15 ), 0, 0 ); namedWindow( window_name2, WINDOW_AUTOSIZE ); imshow("Processed Image",dst); waitKey(); return 0; }<|endoftext|>
<commit_before>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "InterDex.h" #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <unordered_set> #include "Creators.h" #include "Debug.h" #include "DexClass.h" #include "DexLoader.h" #include "DexOutput.h" #include "DexUtil.h" #include "PgoFiles.h" #include "Transform.h" #include "walkers.h" namespace { typedef std::unordered_set<DexMethod*> mrefs_t; typedef std::unordered_set<DexField*> frefs_t; size_t global_dmeth_cnt; size_t global_smeth_cnt; size_t global_vmeth_cnt; size_t global_methref_cnt; size_t global_fieldref_cnt; size_t global_cls_cnt; static void gather_mrefs(DexClass* cls, mrefs_t& mrefs, frefs_t& frefs) { std::vector<DexMethod*> method_refs; std::vector<DexField*> field_refs; cls->gather_methods(method_refs); cls->gather_fields(field_refs); mrefs.insert(method_refs.begin(), method_refs.end()); frefs.insert(field_refs.begin(), field_refs.end()); } #ifdef GINGER_BREAD static const int kMaxLinearAlloc = (2600 * 1024); #else static const int kMaxLinearAlloc = (11600 * 1024); #endif static const int kMaxMethodRefs = ((64 * 1024) - 1); static const int kMaxFieldRefs = 64 * 1024 - 1; static const char* kCanaryPrefix = "Lsecondary/dex"; static const char* kCanaryClassFormat = "Lsecondary/dex%02d/Canary;"; static const int kCanaryClassBufsize = strlen(kCanaryClassFormat) + 1; static const int kMaxDexNum = 99; struct dex_emit_tracker { int la_size; mrefs_t mrefs; frefs_t frefs; std::vector<DexClass*> outs; std::unordered_set<DexClass*> emitted; std::unordered_map<std::string, DexClass*> clookup; }; static void update_dex_stats ( size_t cls_cnt, size_t methrefs_cnt, size_t frefs_cnt) { global_cls_cnt += cls_cnt; global_methref_cnt += methrefs_cnt; global_fieldref_cnt += frefs_cnt; } static void update_class_stats(DexClass* clazz) { int cnt_smeths = 0; for (auto const m : clazz->get_dmethods()) { if (is_static(m)) { cnt_smeths++; } } global_smeth_cnt += cnt_smeths; global_dmeth_cnt += clazz->get_dmethods().size(); global_vmeth_cnt += clazz->get_vmethods().size(); } static void flush_out_dex( dex_emit_tracker& det, DexClassesVector& outdex, size_t mrefs_size, size_t frefs_size) { DexClasses dc(det.outs.size()); for (size_t i = 0; i < det.outs.size(); i++) { dc.insert_at(det.outs[i], i); } outdex.emplace_back(std::move(dc)); // print out stats TRACE(IDEX, 1, "terminating dex at classes %lu, lin alloc %d:%d, mrefs %lu:%d, frefs " "%lu:%d\n", det.outs.size(), det.la_size, kMaxLinearAlloc, mrefs_size, kMaxMethodRefs, frefs_size, kMaxFieldRefs); update_dex_stats(det.outs.size(), mrefs_size, frefs_size); det.la_size = 0; det.mrefs.clear(); det.frefs.clear(); det.outs.clear(); } static void flush_out_dex( dex_emit_tracker& det, DexClassesVector& outdex) { flush_out_dex(det, outdex, det.mrefs.size(), det.frefs.size()); } static void flush_out_secondary( dex_emit_tracker &det, DexClassesVector &outdex, size_t mrefs_size, size_t frefs_size) { /* Find the Canary class and add it in. */ int dexnum = ((int)outdex.size()); char buf[kCanaryClassBufsize]; always_assert_log(dexnum <= kMaxDexNum, "Bailing, Max dex number surpassed %d\n", dexnum); snprintf(buf, sizeof(buf), kCanaryClassFormat, dexnum); std::string canaryname(buf); auto it = det.clookup.find(canaryname); if (it == det.clookup.end()) { fprintf(stderr, "Warning, no canary class %s found\n", buf); ClassCreator cc(DexType::make_type(canaryname.c_str())); cc.set_access(ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT); cc.set_super(get_object_type()); det.outs.push_back(cc.create()); } else { auto clazz = it->second; det.outs.push_back(clazz); } /* Now emit our outs list... */ flush_out_dex(det, outdex, mrefs_size, frefs_size); } static void flush_out_secondary( dex_emit_tracker &det, DexClassesVector &outdex) { flush_out_secondary(det, outdex, det.mrefs.size(), det.frefs.size()); } static bool is_canary(DexClass* clazz) { const char* cname = clazz->get_type()->get_name()->c_str(); if (strncmp(cname, kCanaryPrefix, sizeof(kCanaryPrefix) - 1) == 0) return true; return false; } static void emit_class(dex_emit_tracker &det, DexClassesVector &outdex, DexClass *clazz, bool is_primary) { if(det.emitted.count(clazz) != 0) return; if(is_canary(clazz)) return; int laclazz = estimate_linear_alloc(clazz); auto mrefs_size = det.mrefs.size(); auto frefs_size = det.frefs.size(); gather_mrefs(clazz, det.mrefs, det.frefs); if ((det.la_size + laclazz) > kMaxLinearAlloc || det.mrefs.size() >= kMaxMethodRefs || det.frefs.size() >= kMaxFieldRefs) { /* Emit out list */ always_assert_log(!is_primary, "would have to do an early flush on the primary dex\n" "la %d:%d , mrefs %lu:%d frefs %lu:%d\n", det.la_size + laclazz, kMaxLinearAlloc, det.mrefs.size(), kMaxMethodRefs, det.frefs.size(), kMaxFieldRefs); flush_out_secondary(det, outdex, mrefs_size, frefs_size); gather_mrefs(clazz, det.mrefs, det.frefs); } det.la_size += laclazz; det.outs.push_back(clazz); det.emitted.insert(clazz); update_class_stats(clazz); } static void emit_class(dex_emit_tracker &det, DexClassesVector &outdex, DexClass *clazz) { emit_class(det, outdex, clazz, false); } static DexClassesVector run_interdex( const DexClassesVector& dexen, PgoFiles& pgo, bool allow_cutting_off_dex ) { global_dmeth_cnt = 0; global_smeth_cnt = 0; global_vmeth_cnt = 0; global_methref_cnt = 0; global_fieldref_cnt = 0; global_cls_cnt = 0; auto interdexorder = pgo.get_coldstart_classes(); dex_emit_tracker det; dex_emit_tracker primary_det; for (auto const& dex : dexen) { for (auto const& clazz : dex) { std::string clzname(clazz->get_type()->get_name()->c_str()); det.clookup[clzname] = clazz; } } DexClassesVector outdex; // build a separate lookup table for the primary dex, // since we have to make sure we keep all classes // in the same dex auto const& primary_dex = dexen[0]; for (auto const& clazz : primary_dex) { std::string clzname(clazz->get_type()->get_name()->c_str()); primary_det.clookup[clzname] = clazz; } /* First emit just the primary dex, but sort it * according to interdex order **/ primary_det.la_size = 0; // first add the classes in the interdex list auto coldstart_classes_in_primary = 0; for (auto& entry : interdexorder) { auto it = primary_det.clookup.find(entry); if (it == primary_det.clookup.end()) { TRACE(IDEX, 4, "No such entry %s\n", entry.c_str()); continue; } auto clazz = it->second; emit_class(primary_det, outdex, clazz, true); coldstart_classes_in_primary++; } // now add the rest for (auto const& clazz : primary_dex) { emit_class(primary_det, outdex, clazz, true); } TRACE(IDEX, 1, "%d out of %lu classes in primary dex in interdex list\n", coldstart_classes_in_primary, primary_det.outs.size()); flush_out_dex(primary_det, outdex); // record the primary dex classes in the main emit tracker, // so we don't emit those classes again. *cough* for (auto const& clazz : primary_dex) { det.emitted.insert(clazz); } det.la_size = 0; for (auto& entry : interdexorder) { auto it = det.clookup.find(entry); if (it == det.clookup.end()) { TRACE(IDEX, 4, "No such entry %s\n", entry.c_str()); if (entry.find("DexEndMarker") != std::string::npos) { TRACE(IDEX, 1, "Terminating dex due to DexEndMarker\n"); flush_out_secondary(det, outdex); } continue; } auto clazz = it->second; emit_class(det, outdex, clazz); } Scope scope = build_class_scope(dexen); /* Now emit the kerf that wasn't specified in the head * or primary list. */ for (auto clazz : scope) { emit_class(det, outdex, clazz); } /* Finally, emit the "left-over" det.outs */ if (det.outs.size()) { flush_out_secondary(det, outdex); } TRACE(IDEX, 1, "InterDex secondary dex count %d\n", (int)(outdex.size() - 1)); TRACE(IDEX, 1, "global stats: %lu mrefs, %lu frefs, %lu cls, %lu dmeth, %lu smeth, %lu vmeth\n", global_methref_cnt, global_fieldref_cnt, global_cls_cnt, global_dmeth_cnt, global_smeth_cnt, global_vmeth_cnt); return outdex; } } void InterDexPass::run_pass(DexClassesVector& dexen, PgoFiles& pgo) { auto first_attempt = run_interdex(dexen, pgo, true); if (first_attempt.size() > dexen.size()) { fprintf(stderr, "Warning, Interdex grew the number of dexes from %lu to %lu! \n \ Retrying without cutting off interdex dexes. \n", dexen.size(), first_attempt.size()); dexen = run_interdex(dexen, pgo, false); } else { dexen = std::move(first_attempt); } } <commit_msg>remove classes from coldstart list which have no references to them in the list<commit_after>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "InterDex.h" #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include <unordered_set> #include "Creators.h" #include "Debug.h" #include "DexClass.h" #include "DexLoader.h" #include "DexOutput.h" #include "DexUtil.h" #include "PgoFiles.h" #include "ReachableClasses.h" #include "Transform.h" #include "walkers.h" namespace { typedef std::unordered_set<DexMethod*> mrefs_t; typedef std::unordered_set<DexField*> frefs_t; size_t global_dmeth_cnt; size_t global_smeth_cnt; size_t global_vmeth_cnt; size_t global_methref_cnt; size_t global_fieldref_cnt; size_t global_cls_cnt; size_t cls_skipped_in_primary = 0; size_t cls_skipped_in_secondary = 0; static void gather_mrefs(DexClass* cls, mrefs_t& mrefs, frefs_t& frefs) { std::vector<DexMethod*> method_refs; std::vector<DexField*> field_refs; cls->gather_methods(method_refs); cls->gather_fields(field_refs); mrefs.insert(method_refs.begin(), method_refs.end()); frefs.insert(field_refs.begin(), field_refs.end()); } #ifdef GINGER_BREAD static const int kMaxLinearAlloc = (2600 * 1024); #else static const int kMaxLinearAlloc = (11600 * 1024); #endif static const int kMaxMethodRefs = ((64 * 1024) - 1); static const int kMaxFieldRefs = 64 * 1024 - 1; static const char* kCanaryPrefix = "Lsecondary/dex"; static const char* kCanaryClassFormat = "Lsecondary/dex%02d/Canary;"; static const int kCanaryClassBufsize = strlen(kCanaryClassFormat) + 1; static const int kMaxDexNum = 99; struct dex_emit_tracker { int la_size; mrefs_t mrefs; frefs_t frefs; std::vector<DexClass*> outs; std::unordered_set<DexClass*> emitted; std::unordered_map<std::string, DexClass*> clookup; }; static void update_dex_stats ( size_t cls_cnt, size_t methrefs_cnt, size_t frefs_cnt) { global_cls_cnt += cls_cnt; global_methref_cnt += methrefs_cnt; global_fieldref_cnt += frefs_cnt; } static void update_class_stats(DexClass* clazz) { int cnt_smeths = 0; for (auto const m : clazz->get_dmethods()) { if (is_static(m)) { cnt_smeths++; } } global_smeth_cnt += cnt_smeths; global_dmeth_cnt += clazz->get_dmethods().size(); global_vmeth_cnt += clazz->get_vmethods().size(); } static void flush_out_dex( dex_emit_tracker& det, DexClassesVector& outdex, size_t mrefs_size, size_t frefs_size) { DexClasses dc(det.outs.size()); for (size_t i = 0; i < det.outs.size(); i++) { dc.insert_at(det.outs[i], i); } outdex.emplace_back(std::move(dc)); // print out stats TRACE(IDEX, 1, "terminating dex at classes %lu, lin alloc %d:%d, mrefs %lu:%d, frefs " "%lu:%d\n", det.outs.size(), det.la_size, kMaxLinearAlloc, mrefs_size, kMaxMethodRefs, frefs_size, kMaxFieldRefs); update_dex_stats(det.outs.size(), mrefs_size, frefs_size); det.la_size = 0; det.mrefs.clear(); det.frefs.clear(); det.outs.clear(); } static void flush_out_dex( dex_emit_tracker& det, DexClassesVector& outdex) { flush_out_dex(det, outdex, det.mrefs.size(), det.frefs.size()); } static void flush_out_secondary( dex_emit_tracker &det, DexClassesVector &outdex, size_t mrefs_size, size_t frefs_size) { /* Find the Canary class and add it in. */ int dexnum = ((int)outdex.size()); char buf[kCanaryClassBufsize]; always_assert_log(dexnum <= kMaxDexNum, "Bailing, Max dex number surpassed %d\n", dexnum); snprintf(buf, sizeof(buf), kCanaryClassFormat, dexnum); std::string canaryname(buf); auto it = det.clookup.find(canaryname); if (it == det.clookup.end()) { fprintf(stderr, "Warning, no canary class %s found\n", buf); ClassCreator cc(DexType::make_type(canaryname.c_str())); cc.set_access(ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT); cc.set_super(get_object_type()); det.outs.push_back(cc.create()); } else { auto clazz = it->second; det.outs.push_back(clazz); } /* Now emit our outs list... */ flush_out_dex(det, outdex, mrefs_size, frefs_size); } static void flush_out_secondary( dex_emit_tracker &det, DexClassesVector &outdex) { flush_out_secondary(det, outdex, det.mrefs.size(), det.frefs.size()); } static bool is_canary(DexClass* clazz) { const char* cname = clazz->get_type()->get_name()->c_str(); if (strncmp(cname, kCanaryPrefix, sizeof(kCanaryPrefix) - 1) == 0) return true; return false; } static void emit_class(dex_emit_tracker &det, DexClassesVector &outdex, DexClass *clazz, bool is_primary) { if(det.emitted.count(clazz) != 0) return; if(is_canary(clazz)) return; int laclazz = estimate_linear_alloc(clazz); auto mrefs_size = det.mrefs.size(); auto frefs_size = det.frefs.size(); gather_mrefs(clazz, det.mrefs, det.frefs); if ((det.la_size + laclazz) > kMaxLinearAlloc || det.mrefs.size() >= kMaxMethodRefs || det.frefs.size() >= kMaxFieldRefs) { /* Emit out list */ always_assert_log(!is_primary, "would have to do an early flush on the primary dex\n" "la %d:%d , mrefs %lu:%d frefs %lu:%d\n", det.la_size + laclazz, kMaxLinearAlloc, det.mrefs.size(), kMaxMethodRefs, det.frefs.size(), kMaxFieldRefs); flush_out_secondary(det, outdex, mrefs_size, frefs_size); gather_mrefs(clazz, det.mrefs, det.frefs); } det.la_size += laclazz; det.outs.push_back(clazz); det.emitted.insert(clazz); update_class_stats(clazz); } static void emit_class(dex_emit_tracker &det, DexClassesVector &outdex, DexClass *clazz) { emit_class(det, outdex, clazz, false); } static std::unordered_set<const DexClass*> find_unrefenced_coldstart_classes( const Scope& scope, dex_emit_tracker& det, const std::vector<std::string>& interdexorder, bool static_prune_classes) { int old_no_ref = -1; int new_no_ref = 0; std::unordered_set<DexClass*> coldstart_classes; std::unordered_set<const DexClass*> cold_cold_references; std::unordered_set<const DexClass*> unreferenced_classes; Scope input_scope = scope; // don't do analysis if we're not going doing pruning if (!static_prune_classes) { return unreferenced_classes; } for (auto const& class_string : interdexorder) { if (det.clookup.count(class_string)) { coldstart_classes.insert(det.clookup[class_string]); } } while (old_no_ref != new_no_ref) { old_no_ref = new_no_ref; new_no_ref = 0; cold_cold_references.clear(); walk_code( input_scope, [&](DexMethod* meth) { if (coldstart_classes.count(type_class(meth->get_class())) > 0) { return true; } return false; }, [&](DexMethod* meth, DexCode* code) { auto base_cls = type_class(meth->get_class()); for (auto const& inst : code->get_instructions()) { DexClass* called_cls = nullptr; if (inst->has_methods()) { auto method_access = static_cast<DexOpcodeMethod*>(inst); called_cls = type_class(method_access->get_method()->get_class()); } else if (inst->has_fields()) { auto field_access = static_cast<DexOpcodeField*>(inst); called_cls = type_class(field_access->field()->get_class()); } else if (inst->has_types()) { auto type_access = static_cast<DexOpcodeType*>(inst); called_cls = type_class(type_access->get_type()); } if (called_cls != nullptr && base_cls != called_cls && coldstart_classes.count(called_cls) > 0) { cold_cold_references.insert(called_cls); } } } ); for (const auto& cls: scope) { // make sure we don't drop classes which // might be called from native code if (!can_rename(cls)) { cold_cold_references.insert(cls); } } // get all classes in the reference // set, even if they are not referenced // by opcodes directly for (const auto& cls: input_scope) { if (cold_cold_references.count(cls)) { std::vector<DexType*> types; cls->gather_types(types); for (const auto& type: types) { auto cls = type_class(type); cold_cold_references.insert(cls); } } } Scope output_scope; for (auto& cls : coldstart_classes) { if (can_rename(cls) && cold_cold_references.count(cls) == 0) { new_no_ref++; unreferenced_classes.insert(cls); } else { output_scope.push_back(cls); } } TRACE(IDEX, 1, "found %d classes in coldstart with no references\n", new_no_ref); input_scope = output_scope; } return unreferenced_classes; } static DexClassesVector run_interdex( const DexClassesVector& dexen, PgoFiles& pgo, bool allow_cutting_off_dex, bool static_prune_classes ) { global_dmeth_cnt = 0; global_smeth_cnt = 0; global_vmeth_cnt = 0; global_methref_cnt = 0; global_fieldref_cnt = 0; global_cls_cnt = 0; cls_skipped_in_primary = 0; cls_skipped_in_secondary = 0; auto interdexorder = pgo.get_coldstart_classes(); dex_emit_tracker det; dex_emit_tracker primary_det; for (auto const& dex : dexen) { for (auto const& clazz : dex) { std::string clzname(clazz->get_type()->get_name()->c_str()); det.clookup[clzname] = clazz; } } auto scope = build_class_scope(dexen); auto unreferenced_classes = find_unrefenced_coldstart_classes( scope, det, interdexorder, static_prune_classes); DexClassesVector outdex; // build a separate lookup table for the primary dex, // since we have to make sure we keep all classes // in the same dex auto const& primary_dex = dexen[0]; for (auto const& clazz : primary_dex) { std::string clzname(clazz->get_type()->get_name()->c_str()); primary_det.clookup[clzname] = clazz; } /* First emit just the primary dex, but sort it * according to interdex order **/ primary_det.la_size = 0; // first add the classes in the interdex list auto coldstart_classes_in_primary = 0; for (auto& entry : interdexorder) { auto it = primary_det.clookup.find(entry); if (it == primary_det.clookup.end()) { TRACE(IDEX, 4, "No such entry %s\n", entry.c_str()); continue; } auto clazz = it->second; if (unreferenced_classes.count(clazz)) { TRACE(IDEX, 3, "%s no longer linked to coldstart set.\n", SHOW(clazz)); cls_skipped_in_primary++; continue; } emit_class(primary_det, outdex, clazz, true); coldstart_classes_in_primary++; } // now add the rest for (auto const& clazz : primary_dex) { emit_class(primary_det, outdex, clazz, true); } TRACE(IDEX, 1, "%d out of %lu classes in primary dex in interdex list\n", coldstart_classes_in_primary, primary_det.outs.size()); flush_out_dex(primary_det, outdex); // record the primary dex classes in the main emit tracker, // so we don't emit those classes again. *cough* for (auto const& clazz : primary_dex) { det.emitted.insert(clazz); } det.la_size = 0; for (auto& entry : interdexorder) { auto it = det.clookup.find(entry); if (it == det.clookup.end()) { TRACE(IDEX, 4, "No such entry %s\n", entry.c_str()); if (entry.find("DexEndMarker") != std::string::npos) { TRACE(IDEX, 1, "Terminating dex due to DexEndMarker\n"); flush_out_secondary(det, outdex); } continue; } auto clazz = it->second; if (unreferenced_classes.count(clazz)) { TRACE(IDEX, 3, "%s no longer linked to coldstart set.\n", SHOW(clazz)); cls_skipped_in_secondary++; continue; } emit_class(det, outdex, clazz); } /* Now emit the classes we omitted from the original * coldstart set */ for (auto& entry : interdexorder) { auto it = det.clookup.find(entry); if (it == det.clookup.end()) { TRACE(IDEX, 4, "No such entry %s\n", entry.c_str()); continue; } auto clazz = it->second; if (unreferenced_classes.count(clazz)) { emit_class(det, outdex, clazz); } } /* Now emit the kerf that wasn't specified in the head * or primary list. */ for (auto clazz : scope) { emit_class(det, outdex, clazz); } /* Finally, emit the "left-over" det.outs */ if (det.outs.size()) { flush_out_secondary(det, outdex); } TRACE(IDEX, 1, "InterDex secondary dex count %d\n", (int)(outdex.size() - 1)); TRACE(IDEX, 1, "global stats: %lu mrefs, %lu frefs, %lu cls, %lu dmeth, %lu smeth, %lu vmeth\n", global_methref_cnt, global_fieldref_cnt, global_cls_cnt, global_dmeth_cnt, global_smeth_cnt, global_vmeth_cnt); TRACE(IDEX, 1, "removed %d classes from coldstart list in primary dex, \ %d in secondary dexes due to static analysis\n", cls_skipped_in_primary, cls_skipped_in_secondary); return outdex; } } void InterDexPass::run_pass(DexClassesVector& dexen, PgoFiles& pgo) { bool static_prune = false; if (m_config["static_prune"] != nullptr) { auto prune_str = m_config["static_prune"].asString().toStdString(); if (prune_str == "1") { static_prune = true; } } auto first_attempt = run_interdex(dexen, pgo, true, static_prune); if (first_attempt.size() > dexen.size()) { fprintf(stderr, "Warning, Interdex grew the number of dexes from %lu to %lu! \n \ Retrying without cutting off interdex dexes. \n", dexen.size(), first_attempt.size()); dexen = run_interdex(dexen, pgo, false, static_prune); } else { dexen = std::move(first_attempt); } } <|endoftext|>
<commit_before>//****************************************************************************** // Board.cpp // Revision History: // // Date Author Description // 11/28/2017 Jason Chen Added class //****************************************************************************** #include <iostream> #include <sstream> #include "Deck.h" #include "Hand.h" #include "Card.h" #include "Board.h" #include "Player.h" #include "ConsoleUI.h" #include "helper.h" using namespace std; //constructor //initialize the board for a new game Board::Board(Player* hum, Player* AI, int smallBlindPlayer) { human = hum; this->AI=AI; setCommunity(); help=new helper(); this->smallBlindPlayer=smallBlindPlayer; } void Board::setBlind(int bld) { smallBlind = bld; } void Board::setCommunity() { for(int i = 0; i < 5; i++) { community[i] = dek.draw(); } //set player cards human->addOne(dek.draw()); human->addTwo(dek.draw()); AI->addOne(dek.draw()); AI->addTwo(dek.draw()); } void Board::printBoard() { cout << "The pot is: " << pot << endl; cout << "Your stack size is: " << human->getTotalChips() << endl; cout << "AI's stack size is: " << AI->getTotalChips() << endl << endl; } bool Board::run() { string inputTemp; ConsoleUI* ui = new ConsoleUI(); if(human->getTempPool() < AI->getTempPool()) { inputTemp=ui->input("Fold (1), Call (2), or Raise (3)\n"); while (!help->isInt(inputTemp)||stoi(inputTemp)<1||stoi(inputTemp)>3) { ui->output("Input must be an integer."); inputTemp=ui->input("Fold (1), Check (2), or Raise (3)"); } } else { inputTemp=ui->input("Fold (1), Check (2), or Raise (3)\n"); while (!help->isInt(inputTemp)||stoi(inputTemp)<1||stoi(inputTemp)>3) { ui->output("Input must be an integer."); inputTemp=ui->input("Fold (1), Check (2), or Raise (3)"); } } if(inputTemp == "1") { return true; } else if(inputTemp == "2") { human->call(AI); pot=human->getTempPool()+AI->getTempPool(); printBoard(); return false; } else { int prev = AI->getPrevBet(); string r = ui->input("How much do you want to raise by?"); while (!help->isInt(r)|| stoi(r) < prev*2 || stoi(r) > human->getTotalChips()) { ui->output("Input must be an integer and at least double the previous bet."); r=ui->input("How much do you want to raise by?"); } human->raise(stoi(r)); pot=human->getTempPool()+AI->getTempPool(); human->setPrevBet(stoi(r)); printBoard(); return false; } } bool Board::runAI(){ ConsoleUI* ui = new ConsoleUI(); ui->output("AI's turn: "); AI->call(human); //for now pot=AI->getTempPool()+human->getTempPool(); printBoard(); return false; } bool Board::preflop() { printBoard(); ConsoleUI* ui=new ConsoleUI(); string inputTemp; //print user's hand ui->output("Your hand: "); (human->getHandOne()).printCard(); (human->getHandTwo()).printCard(); ui->output(""); //force user to put in blind pot=smallBlind*3; if (smallBlindPlayer==1){ AI->raise(smallBlind); human->raise(smallBlind*2); } else{ human->raise(smallBlind); AI->raise(smallBlind*2); } cout<<"AI total chips: "<<AI->getTotalChips()<<endl; //980 cout<<"Human total chips: "<<human->getTotalChips()<<endl; //990 cout<<"small blind player : "<<smallBlindPlayer<<endl; while(human->getTempPool()!=AI->getTempPool()) //player facing a bet { if (smallBlindPlayer==1){ //AI goes first this->runAI(); bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } } else if (smallBlindPlayer==0){ //player goes first bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } this->runAI(); } } printBoard(); return false; } bool Board::flop() { printBoard(); ConsoleUI* ui=new ConsoleUI(); cout << "The flop is " << endl; community[0].printCard(); community[1].printCard(); community[2].printCard(); cout << endl; //print user's hand ui->output("Your hand: "); (human->getHandOne()).printCard(); (human->getHandTwo()).printCard(); ui->output(""); cout<<"AI total chips: "<<AI->getTotalChips()<<endl; //980 cout<<"Human total chips: "<<human->getTotalChips()<<endl; //990 cout<<"small blind player : "<<smallBlindPlayer<<endl; do { if (smallBlindPlayer==1){ //AI goes first this->runAI(); bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } } else if (smallBlindPlayer==0){ //player goes first bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } this->runAI(); } } while(human->getTempPool()!=AI->getTempPool()); //player facing a bet printBoard(); return false; } bool Board::turn() { printBoard(); cout << "The turn is " << endl; community[0].printCard(); community[1].printCard(); community[2].printCard(); community[3].printCard(); cout << endl; ConsoleUI* ui=new ConsoleUI(); //print user's hand ui->output("Your hand: "); (human->getHandOne()).printCard(); (human->getHandTwo()).printCard(); ui->output(""); cout<<"AI total chips: "<<AI->getTotalChips()<<endl; //980 cout<<"Human total chips: "<<human->getTotalChips()<<endl; //990 cout<<"small blind player : "<<smallBlindPlayer<<endl; do { if (smallBlindPlayer==1){ //AI goes first this->runAI(); bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } } else if (smallBlindPlayer==0){ //player goes first bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } this->runAI(); } } while(human->getTempPool()!=AI->getTempPool()); //player facing a bet printBoard(); return false; } bool Board::river() { printBoard(); cout << "The river is " << endl; community[0].printCard(); community[1].printCard(); community[2].printCard(); community[3].printCard(); community[4].printCard(); cout << endl; ConsoleUI* ui=new ConsoleUI(); //print user's hand ui->output("Your hand: "); (human->getHandOne()).printCard(); (human->getHandTwo()).printCard(); ui->output(""); cout<<"AI total chips: "<<AI->getTotalChips()<<endl; //980 cout<<"Human total chips: "<<human->getTotalChips()<<endl; //990 cout<<"small blind player : "<<smallBlindPlayer<<endl; do { if (smallBlindPlayer==1){ //AI goes first this->runAI(); bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } } else if (smallBlindPlayer==0){ //player goes first bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } this->runAI(); } } while(human->getTempPool()!=AI->getTempPool()); //player facing a bet printBoard(); //after everything is done Hand* humanBest=help->bestHand((human->getHandOne()),(human->getHandTwo()), community[0],community[1],community[2],community[3],community[4]); Hand* AIBest=help->bestHand((AI->getHandOne()),(AI->getHandTwo()), community[0],community[1],community[2],community[3],community[4]); int result=help->compareHands(humanBest,AIBest); ui->output("Community Cards: "); for (int i=0;i<5;i++){ community[i].printCard(); } ui->output(""); ui->output("AI's cards: "); AI->getHandOne().printCard(); AI->getHandTwo().printCard(); ui->output(""); ui->output("Your cards: "); human->getHandOne().printCard(); human->getHandTwo().printCard(); ui->output(""); ui->output("Your best hand: "); humanBest->printHand(); ui->output(""); ui->output("AI's best hand: "); AIBest->printHand(); ui->output(""); if (result==1){ ui->output("You won."); human->setTotalChips(human->getTotalChips()+pot); } else if (result==0){ ui->output("AI won"); AI->setTotalChips(AI->getTotalChips()+pot); } else{ ui->output("Tie"); human->setTotalChips(human->getTotalChips()+pot/2); AI->setTotalChips(AI->getTotalChips()+pot/2); } //cout<<"Result: "<<result<<endl; return false; } void Board::clearBoard() { human->resetTempPool(); AI->resetTempPool(); pot=0; dek.shuffle(); setCommunity(); if (smallBlindPlayer==0){ smallBlindPlayer=1; } else{ smallBlindPlayer=0; } } <commit_msg>removed excess printboards<commit_after>//****************************************************************************** // Board.cpp // Revision History: // // Date Author Description // 11/28/2017 Jason Chen Added class //****************************************************************************** #include <iostream> #include <sstream> #include "Deck.h" #include "Hand.h" #include "Card.h" #include "Board.h" #include "Player.h" #include "ConsoleUI.h" #include "helper.h" using namespace std; //constructor //initialize the board for a new game Board::Board(Player* hum, Player* AI, int smallBlindPlayer) { human = hum; this->AI=AI; setCommunity(); help=new helper(); this->smallBlindPlayer=smallBlindPlayer; } void Board::setBlind(int bld) { smallBlind = bld; } void Board::setCommunity() { for(int i = 0; i < 5; i++) { community[i] = dek.draw(); } //set player cards human->addOne(dek.draw()); human->addTwo(dek.draw()); AI->addOne(dek.draw()); AI->addTwo(dek.draw()); } void Board::printBoard() { cout << "The pot is: " << pot << endl; cout << "Your stack size is: " << human->getTotalChips() << endl; cout << "AI's stack size is: " << AI->getTotalChips() << endl << endl; } bool Board::run() { string inputTemp; ConsoleUI* ui = new ConsoleUI(); if(human->getTempPool() < AI->getTempPool()) { inputTemp=ui->input("Fold (1), Call (2), or Raise (3)\n"); while (!help->isInt(inputTemp)||stoi(inputTemp)<1||stoi(inputTemp)>3) { ui->output("Input must be an integer."); inputTemp=ui->input("Fold (1), Check (2), or Raise (3)"); } } else { inputTemp=ui->input("Fold (1), Check (2), or Raise (3)\n"); while (!help->isInt(inputTemp)||stoi(inputTemp)<1||stoi(inputTemp)>3) { ui->output("Input must be an integer."); inputTemp=ui->input("Fold (1), Check (2), or Raise (3)"); } } if(inputTemp == "1") { return true; } else if(inputTemp == "2") { human->call(AI); pot=human->getTempPool()+AI->getTempPool(); printBoard(); return false; } else { int prev = AI->getPrevBet(); string r = ui->input("How much do you want to raise by?"); while (!help->isInt(r)|| stoi(r) < prev*2 || stoi(r) > human->getTotalChips()) { ui->output("Input must be an integer and at least double the previous bet."); r=ui->input("How much do you want to raise by?"); } human->raise(stoi(r)); pot=human->getTempPool()+AI->getTempPool(); human->setPrevBet(stoi(r)); printBoard(); return false; } } bool Board::runAI(){ ConsoleUI* ui = new ConsoleUI(); ui->output("AI's turn: "); AI->call(human); //for now pot=AI->getTempPool()+human->getTempPool(); printBoard(); return false; } bool Board::preflop() { printBoard(); ConsoleUI* ui=new ConsoleUI(); string inputTemp; //print user's hand ui->output("Your hand: "); (human->getHandOne()).printCard(); (human->getHandTwo()).printCard(); ui->output(""); //force user to put in blind pot=smallBlind*3; if (smallBlindPlayer==1){ AI->raise(smallBlind); human->raise(smallBlind*2); } else{ human->raise(smallBlind); AI->raise(smallBlind*2); } cout<<"AI total chips: "<<AI->getTotalChips()<<endl; //980 cout<<"Human total chips: "<<human->getTotalChips()<<endl; //990 cout<<"small blind player : "<<smallBlindPlayer<<endl; while(human->getTempPool()!=AI->getTempPool()) //player facing a bet { if (smallBlindPlayer==1){ //AI goes first this->runAI(); bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } } else if (smallBlindPlayer==0){ //player goes first bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } this->runAI(); } } return false; } bool Board::flop() { ConsoleUI* ui=new ConsoleUI(); cout << "The flop is " << endl; community[0].printCard(); community[1].printCard(); community[2].printCard(); cout << endl; //print user's hand ui->output("Your hand: "); (human->getHandOne()).printCard(); (human->getHandTwo()).printCard(); ui->output(""); cout<<"AI total chips: "<<AI->getTotalChips()<<endl; //980 cout<<"Human total chips: "<<human->getTotalChips()<<endl; //990 cout<<"small blind player : "<<smallBlindPlayer<<endl; do { if (smallBlindPlayer==1){ //AI goes first this->runAI(); bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } } else if (smallBlindPlayer==0){ //player goes first bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } this->runAI(); } } while(human->getTempPool()!=AI->getTempPool()); //player facing a bet return false; } bool Board::turn() { cout << "The turn is " << endl; community[0].printCard(); community[1].printCard(); community[2].printCard(); community[3].printCard(); cout << endl; ConsoleUI* ui=new ConsoleUI(); //print user's hand ui->output("Your hand: "); (human->getHandOne()).printCard(); (human->getHandTwo()).printCard(); ui->output(""); cout<<"AI total chips: "<<AI->getTotalChips()<<endl; //980 cout<<"Human total chips: "<<human->getTotalChips()<<endl; //990 cout<<"small blind player : "<<smallBlindPlayer<<endl; do { if (smallBlindPlayer==1){ //AI goes first this->runAI(); bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } } else if (smallBlindPlayer==0){ //player goes first bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } this->runAI(); } } while(human->getTempPool()!=AI->getTempPool()); //player facing a bet return false; } bool Board::river() { cout << "The river is " << endl; community[0].printCard(); community[1].printCard(); community[2].printCard(); community[3].printCard(); community[4].printCard(); cout << endl; ConsoleUI* ui=new ConsoleUI(); //print user's hand ui->output("Your hand: "); (human->getHandOne()).printCard(); (human->getHandTwo()).printCard(); ui->output(""); cout<<"AI total chips: "<<AI->getTotalChips()<<endl; //980 cout<<"Human total chips: "<<human->getTotalChips()<<endl; //990 cout<<"small blind player : "<<smallBlindPlayer<<endl; do { if (smallBlindPlayer==1){ //AI goes first this->runAI(); bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } } else if (smallBlindPlayer==0){ //player goes first bool flag=this->run(); if (flag==true){ AI->setTotalChips(AI->getTotalChips()+pot); return true; } this->runAI(); } } while(human->getTempPool()!=AI->getTempPool()); //player facing a bet //after everything is done Hand* humanBest=help->bestHand((human->getHandOne()),(human->getHandTwo()), community[0],community[1],community[2],community[3],community[4]); Hand* AIBest=help->bestHand((AI->getHandOne()),(AI->getHandTwo()), community[0],community[1],community[2],community[3],community[4]); int result=help->compareHands(humanBest,AIBest); ui->output("Community Cards: "); for (int i=0;i<5;i++){ community[i].printCard(); } ui->output(""); ui->output("AI's cards: "); AI->getHandOne().printCard(); AI->getHandTwo().printCard(); ui->output(""); ui->output("Your cards: "); human->getHandOne().printCard(); human->getHandTwo().printCard(); ui->output(""); ui->output("Your best hand: "); humanBest->printHand(); ui->output(""); ui->output("AI's best hand: "); AIBest->printHand(); ui->output(""); if (result==1){ ui->output("You won."); human->setTotalChips(human->getTotalChips()+pot); } else if (result==0){ ui->output("AI won"); AI->setTotalChips(AI->getTotalChips()+pot); } else{ ui->output("Tie"); human->setTotalChips(human->getTotalChips()+pot/2); AI->setTotalChips(AI->getTotalChips()+pot/2); } //cout<<"Result: "<<result<<endl; return false; } void Board::clearBoard() { human->resetTempPool(); AI->resetTempPool(); pot=0; dek.shuffle(); setCommunity(); if (smallBlindPlayer==0){ smallBlindPlayer=1; } else{ smallBlindPlayer=0; } } <|endoftext|>
<commit_before>MAIN_ENV typedef struct { int *a, *queue; long int *start, *end; int p, index; LOCKDEC(indexLock); } GM; GM *gm; void queueLock(void) { register int i,j,q,p; int N = 1500000; int k = 0; int M = 0; int pid; q = 0; p = 0; int myIndex; GET_PID(pid) CLOCK(gm->start[pid]) for (i = 0; i < N; i++) { //Acquire lock. /* LOCK(gm->indexLock) myIndex = gm->index; if (myIndex >= (p-1)*64) gm->index = 0; else gm->index += 64; UNLOCK(gm->indexLock) */ while(gm->queue[myIndex]); gm->queue[myIndex] = 1; //Execute critical section for (j = 0; j < k; j++) q++; //Unlock: //If this index points to the last spot in the queue, index=0 can go //Otherwise, myIndex+1 can go next if (myIndex >= (p-1)*64) gm->queue[0] = 0; else gm->queue[myIndex+64] = 0; } CLOCK(gm->end[pid]) gm->a[pid] = p + q; } /* void queueLock(int pid) { register int i,j,q,N,p,k,M, r; N = 1500000; B k = 0 M = 0; if (pid == 0) { gm->queue[0] = 1; } CLOCK(gm->start[pid]) for (i = 0; i < N; i++) { // printf("At proc: %d\n", pid); while (gm->queue[8*pid] == 0); B // CRITICAL SECITON LOCK(gm->lock) for (j = 0; j < k; j++) q++; UNLOCK(gm->lock) // printf("At proc: %d, next proc at loc: %d\n", pid, (8*pid + gm->p) % (8 * gm->p)); LOCK(gm->increment) gm->queue[8*pid] = 0; gm->queue[(8*pid + gm->p) % (8 * gm->p)] = 1; UNLOCK(gm->increment) p = 0; for (j = 0; j < k; j++) p++; } CLOCK(gm->end[pid]) gm->a[pid] = p + q; }*/ int main(int argc,char **argv) { int i,j,p,n; int *queue; unsigned int t1,t2; MAIN_INITENV gm = (GM*)G_MALLOC(sizeof(GM)); LOCKINIT(gm->indexLock); gm->a = (int*)G_MALLOC(p*sizeof(int)); gm->start = (long int*)G_MALLOC(p*sizeof(long int)); gm->end = (long int*)G_MALLOC(p*sizeof(long int)); p = gm->p = atoi(argv[1]); gm->queue = (int*)G_MALLOC(256*p/sizeof(int)); gm->index = (int)G_MALLOC(sizeof(int)); for(i = 0; i < p; i++) gm->a[i]= 0; for(i = 0; i < (p*256/sizeof(int)); i++) gm->queue[i]= 0; assert(p > 0); assert(p <= 8); // Create p Processes for(i = 0; i < p; i++) CREATE(queueLock) CLOCK(t1) WAIT_FOR_END(p-1) CLOCK(t2) printf("Elapsed: %u us\n",t2-t1); for(i = 0; i < p; i++) printf("Proc %d finished at %d\n", i, gm->end[i]); G_FREE(gm->queue,p*64*sizeof(int)) G_FREE(gm->start,p*sizeof(long int)) G_FREE(gm->end,p*sizeof(long int)) MAIN_END return 0; } <commit_msg>queueLock fixed<commit_after>MAIN_ENV typedef struct { int *a, *queue; long int *start, *end; int p, index; LOCKDEC(indexLock); } GM; GM *gm; void queueLock(void) { register int i,j,q,p; int N = 1500000; int k = 0; int M = 0; int pid; q = 0; p = 0; int myIndex; GET_PID(pid) CLOCK(gm->start[pid]) for (i = 0; i < N; i++) { //Acquire lock. LOCK(gm->indexLock) myIndex = gm->index; if (myIndex == (gm->p-1)*64) gm->index = 0; else gm->index += 64; UNLOCK(gm->indexLock) while(gm->queue[myIndex]); gm->queue[myIndex] = 1; //Execute critical section for (j = 0; j < k; j++) q++; //Unlock: //If this index points to the last spot in the queue, index=0 can go //Otherwise, myIndex+1 can go next if (myIndex == (gm->p-1)*64) gm->queue[0] = 0; else gm->queue[myIndex+64] = 0; } CLOCK(gm->end[pid]) gm->a[pid] = p + q; } int main(int argc,char **argv) { int i,j,p,n; int *queue; unsigned int t1,t2; MAIN_INITENV gm = (GM*)G_MALLOC(sizeof(GM)); LOCKINIT(gm->indexLock); p = gm->p = atoi(argv[1]); gm->a = (int*)G_MALLOC(p*sizeof(int)); gm->start = (long int*)G_MALLOC(p*sizeof(long int)); gm->end = (long int*)G_MALLOC(p*sizeof(long int)); gm->queue = (int*)G_MALLOC(256*p); gm->index = (int)G_MALLOC(sizeof(int)); gm->index = 0; for(i = 0; i < p; i++) gm->a[i]= 0; for(i = 0; i < (p*256/sizeof(int)); i++) { if (i == 0) gm->queue[i]= 0; else gm->queue[i] = 1; } assert(p > 0); assert(p <= 8); // Create p Processes for(i = 0; i < p; i++) CREATE(queueLock) CLOCK(t1) WAIT_FOR_END(p-1) CLOCK(t2) printf("Elapsed: %u us\n",t2-t1); for(i = 0; i < p; i++) printf("Proc %d finished at %d\n", i, gm->end[i]); G_FREE(gm->queue,p*64*sizeof(int)) G_FREE(gm->start,p*sizeof(long int)) G_FREE(gm->end,p*sizeof(long int)) MAIN_END return 0; } <|endoftext|>
<commit_before>// Copyright [2016] <Salomão Rodrigues Jacinto> #ifndef LISTA_HPP #define LISTA_HPP /** * @brief Implementação de uma estrutura de Lista em C++ * * @tparam T Ponteiro para o início da Lista * * @param topo Armazena o último da Lista * @param tamanho Armazena o tamanho da Lista */ template <typename T> class Lista { private: const int MAXLISTA = 100; T* m_dados; int topo; int tamanho; public: /** * @brief Construtor da classe Lista * * @details Valor do tamanho definido em uma constante como 100 */ Lista() { topo = -1; m_dados = new T[MAXLISTA]; tamanho = MAXLISTA; } /** * @brief Construtor da classe Fila * * @param tam Valor para o tamanho da lista */ explicit Lista(int tam) { topo = -1; m_dados = new T[tam]; tamanho = tam; } /** * @brief Adiciona um dado ao último da lista * * @param dado Dado genérico, podendo ser um inteiro, float... */ void adiciona(T dado) { adicionaNaPosicao(dado, topo+1); } /** * @brief Adiciona um dado ao início da lista * * @param dado Dado genérico, podendo ser um inteiro, float... */ void adicionaNoInicio(T dado) { adicionaNaPosicao(dado, 0); } /** * @brief Adiciona um dado na posição desejada da lista *yaourt * @param dado Dado genérico, podendo ser um inteiro, float... * @param posicao Inteiro para posição desejada */ void adicionaNaPosicao(T dado, int posicao) { if(listaCheia()) { throw "Lista cheia"; } else { if(posicao > topo + 1 || posicao < 0) { throw "Posição inválida"; } else { topo++; int i = topo; while(i > posicao) { m_dados[i] = m_dados[i-1]; i--; } m_dados[posicao] = dado; } } } /** * @brief Adiciona um dado na lista acima do que possuí uma valor * inferior ao seu e abaixo do que possuí um valor superior * * @param dado Dado genérico, podendo ser um inteiro, float... */ void adicionaEmOrdem(T dado) { if(listaCheia()) { throw "Lista Cheia"; } else { int i = 0; while(i <= topo && maior(dado, m_dados[i])) { i++; } adicionaNaPosicao(dado, i); } } /** * @brief Retira o último dado colocado na lista */ T retira() { return retiraDaPosicao(topo); } /** * @brief Retira o dado que ocupe a posição 0 da lista */ T retiraDoInicio() { return retiraDaPosicao(0); } /** * @brief Retira o dado que ocupe a posição desejada na lista * * @param posicao Inteiro para posição desejada */ T retiraDaPosicao(int posicao) { if(posicao > topo || posicao < 0) { throw "Posição inválidaa"; } else { if(listaVazia()) { throw "Lista Vazia"; } else { topo--; T dadoaux = m_dados[posicao]; int i = posicao; while(i <= topo) { m_dados[i] = m_dados[i+1]; i++; } return dadoaux; } } } /** * @brief Retira um dado específico da lista * * @param dado Dado a ser pesquisado na lista, e retirado caso * encontrado */ T retiraEspecifico(T dado) { return retiraDaPosicao(posicao(dado)); } /** * @brief Retorna a posição do dado desejado * * @param dado Dado genérico, podendo ser um inteiro, float... * * @return Inteiro para posição do dado */ int posicao(T dado) { int i = 0; while(i <= topo && !(igual(dado, m_dados[i]))) { i++; } if(i > topo) { throw "Este dado não existe"; } else { return i; } } /** * @brief Pesquisa se a lista contém um determinado dado * * @param dado Dado genérico, podendo ser um inteiro, float... * * @return Retorna true caso exista o dado desejado na lista e * false caso contrário */ bool contem(T dado) { if(listaVazia()) { return false; } else { for(int i = 0; i <= topo; i++) { if(igual(m_dados[i], dado)) { return true; } } return false; } } /** * @brief Checa se dois determinados dados são iguais */ bool igual(T dado1, T dado2) { return dado1 == dado2; } /** * @brief Checa se o dado1 é maior que o dado2 */ bool maior(T dado1, T dado2) { return dado1 > dado2; } /** * @brief Checa se o dado1 é menor que o dado2 */ bool menor(T dado1, T dado2) { return dado1 < dado2; } /** * @brief Checa se a lista está cheia * * @return Retorna true caso a lista esteja cheia */ bool listaCheia() { if (topo == tamanho-1) { return true; } else { return false; } } /** * @brief Checa se a lista está vazia * * @return Retorna true caso a lista esteja vazia */ bool listaVazia() { if (topo == -1) { return true; } else { return false; } } /** * @brief Reinicia a lista sem apagar os dados, apenas reinicia o * indexador, ou seja, os dados serão sobrescritos */ void destroiLista() { topo = -1; } }; #endif // LISTA_HPP <commit_msg>Delete Lista.hpp<commit_after><|endoftext|>
<commit_before>/*------------MD.cpp----------------------------------------------------------// * * MD.cpp -- a simple event-driven MD simulation * * Purpose: Figure out the pressure on the interior of a box based on * Boltzmann's theory and stuff * * Notes: This simulation will predominantly follow the logic of the link in * the README file * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <fstream> #include <random> //#include <algorithm> namespace sim{ /* putting our stuff in its own namespace so we can call "time" "time" without colliding with names from the standard library */ using time = double; } /*----------------------------------------------------------------------------// * STRUCTS AND FUNCTIONS *-----------------------------------------------------------------------------*/ // Holds our data in a central struct, to be called mainly in a vector struct Particle{ int PID; sim::time ts; double pos_x, pos_y, pos_z, vel_x, vel_y, vel_z; }; // holds interaction data struct Interaction{ sim::time rtime; int part1, part2; }; // Makes starting data std::vector<Particle> populate(int pnum, double box_length, double max_vel); // Makes the list for our simulation later, required starting data std::vector<Interaction> make_list(const std::vector<Particle> &curr_data, double box_length, double radius); // This performs our MD simulation with a vector of interactions // Also writes simulation to file, specified by README void simulate(std::vector<int> interactions, std::vector<Particle> curr_data); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(void){ int pnum = 1000; double box_length = 10, max_vel = 0.01; std::vector<Particle> curr_data = populate(pnum, box_length, max_vel); for (auto &p : curr_data){ std::cout << p.pos_x << std::endl; } std::vector<Interaction> list = make_list(curr_data, box_length,0.1); std::cout << std::endl << std::endl; for (auto &it : list){ std::cout << it.rtime << std::endl; } return 0; } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // Makes starting data std::vector<Particle> populate(int pnum, double box_length, double max_vel){ std::vector<Particle> curr_data(pnum); // static to create only 1 random_device static std::random_device rd; static std::mt19937 gen(rd()); /* instead of doing % and * to get the correct distribution we directly specify which distribution we want */ std::uniform_real_distribution<double> box_length_distribution(0, box_length); std::uniform_real_distribution<double> max_vel_distribution(0, max_vel); int PID_counter = 0; for (auto &p : curr_data){ //read: for all particles p in curr_data p.ts = 0; p.PID = PID_counter++; for (auto &pos : { &p.pos_x, &p.pos_y, &p.pos_z }) *pos = box_length_distribution(gen); for (auto &vel : { &p.vel_x, &p.vel_y, &p.vel_z }) *vel = max_vel_distribution(gen); } return curr_data; } // Makes the list for our simulation later, required starting data // Step 1: Check interactions between Particles, based on README link // Step 2: Update list. // Step 3: Sort list, lowest first std::vector<Interaction> make_list(const std::vector<Particle> &curr_data, double box_length, double radius){ /* passing curr_data as const reference to avoid the copy and accidental overwriting */ std::vector<Interaction> list; Interaction test; int i = 0,j = 0; double del_x, del_y, del_z, del_vx, del_vy, del_vz, r_tot, rad_d; // Step 1 -- find interactions for (auto &ip : curr_data){ for (auto &jp : curr_data){ if (i != j){ del_x = ip.pos_x - jp.pos_x; del_y = ip.pos_y - jp.pos_y; del_z = ip.pos_z - jp.pos_y; del_vx = ip.vel_x - jp.vel_y; del_vy = ip.vel_y - jp.vel_y; del_vz = ip.vel_z - jp.vel_z; r_tot = 2 * radius; rad_d = (pow(del_vx*del_x + del_vy*del_y + del_vz*del_z, 2) - 4 * (del_vx*del_vx + del_vy*del_vy + del_vz*del_vz) * (del_x*del_x + del_y*del_y + del_z*del_z - r_tot*r_tot)); sim::time check; if (del_x * del_vx >= 0 && del_y * del_vy >= 0 && del_z * del_vz >= 0){ check = 0; } // NaN error here! Sorry about that ^^ else if (rad_d < 0){ check = 0; } else { check = (-(del_vx*del_x + del_vy*del_y + del_vz*del_z) + sqrt(rad_d)) / (2 * (del_vx*del_vx + del_vz*del_vz + del_vy*del_vy)); } // Step 2 -- update list if (check != 0){ std::cout << "found one!" << std::endl; test.rtime = check; test.part1 = i; test.part2 = j; list.push_back(test); } } j++; } i++; } // Step 3 -- sort the list TODO return list; } // This performs our MD simulation with a vector of interactions // Also writes simulation to file, specified by README // Note: Time-loop here void simulate(std::vector<int> interactions, std::vector<Particle> curr_data){ } <commit_msg>fixed sorting and did some refactoring<commit_after>/*------------MD.cpp----------------------------------------------------------// * * MD.cpp -- a simple event-driven MD simulation * * Purpose: Figure out the pressure on the interior of a box based on * Boltzmann's theory and stuff * * Notes: This simulation will predominantly follow the logic of the link in * the README file * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <fstream> #include <random> #include <algorithm> namespace sim{ /* putting our stuff in its own namespace so we can call "time" "time" without colliding with names from the standard library */ using time = double; } /*----------------------------------------------------------------------------// * STRUCTS AND FUNCTIONS *-----------------------------------------------------------------------------*/ // Holds our data in a central struct, to be called mainly in a vector struct Particle{ int PID; sim::time ts; double pos_x, pos_y, pos_z, vel_x, vel_y, vel_z; }; // holds interaction data struct Interaction{ sim::time rtime; int part1, part2; }; // Makes starting data std::vector<Particle> populate(int pnum, double box_length, double max_vel); // Makes the list for our simulation later, required starting data std::vector<Interaction> make_list(const std::vector<Particle> &curr_data, double box_length, double radius); // This performs our MD simulation with a vector of interactions // Also writes simulation to file, specified by README void simulate(std::vector<int> interactions, std::vector<Particle> curr_data); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(void){ int pnum = 1000; double box_length = 10, max_vel = 0.01; std::vector<Particle> curr_data = populate(pnum, box_length, max_vel); for (auto &p : curr_data){ std::cout << p.pos_x << '\n'; } std::vector<Interaction> list = make_list(curr_data, box_length, 0.1); std::cout << '\n' << '\n'; for (auto &it : list){ std::cout << it.rtime << '\n'; } return 0; } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // Makes starting data std::vector<Particle> populate(int pnum, double box_length, double max_vel){ std::vector<Particle> curr_data(pnum); // static to create only 1 random_device static std::random_device rd; static std::mt19937 gen(rd()); /* instead of doing % and * to get the correct distribution we directly specify which distribution we want */ std::uniform_real_distribution<double> box_length_distribution(0, box_length); std::uniform_real_distribution<double> max_vel_distribution(0, max_vel); int PID_counter = 0; for (auto &p : curr_data){ //read: for all particles p in curr_data p.ts = 0; p.PID = PID_counter++; for (auto &pos : { &p.pos_x, &p.pos_y, &p.pos_z }) *pos = box_length_distribution(gen); for (auto &vel : { &p.vel_x, &p.vel_y, &p.vel_z }) *vel = max_vel_distribution(gen); } return curr_data; } // Makes the list for our simulation later, required starting data // Step 1: Check interactions between Particles, based on README link // Step 2: Update list. // Step 3: Sort list, lowest first std::vector<Interaction> make_list(const std::vector<Particle> &curr_data, double box_length, double radius){ /* passing curr_data as const reference to avoid the copy and accidental overwriting */ std::vector<Interaction> list; // Step 1 -- find interactions /* The "for (auto &e : c)" syntax is not very useful when we need the index and don't iterate over every element */ /* After we compute the pair i-j we don't need to compare the pair j-i anymore, also no i-i comparison, so make j > i */ for (size_t i = 0; i < curr_data.size(); ++i){ for (size_t j = i + 1; j < curr_data.size(); ++j){ //think of this as giving "curr_data[i]" the new name "ip" const auto &ip = curr_data[i]; const auto &jp = curr_data[j]; const double delta_x = ip.pos_x - jp.pos_x; const double delta_y = ip.pos_y - jp.pos_y; const double delta_z = ip.pos_z - jp.pos_y; const double delta_vx = ip.vel_x - jp.vel_y; const double delta_vy = ip.vel_y - jp.vel_y; const double delta_vz = ip.vel_z - jp.vel_z; if (delta_x * delta_vx >= 0 && delta_y * delta_vy >= 0 && delta_z * delta_vz >= 0){ continue; } const double r_tot = 2 * radius; //change "r_tot" and "rad_d" to a more descriptive name? const double delta = delta_vx*delta_x + delta_vy*delta_y + delta_vz*delta_z; const double rad_d = (delta * delta - 4 * (delta_vx*delta_vx + delta_vy*delta_vy + delta_vz*delta_vz) * (delta_x*delta_x + delta_y*delta_y + delta_z*delta_z - r_tot*r_tot)); // NaN error here! Sorry about that ^^ if (rad_d < 0){ continue; } // Step 2 -- update list std::cout << "found one!" << '\n'; const auto check = (-(delta_vx*delta_x + delta_vy*delta_y + delta_vz*delta_z) + sqrt(rad_d)) / (2 * (delta_vx*delta_vx + delta_vz*delta_vz + delta_vy*delta_vy)); Interaction test; test.rtime = check; test.part1 = i; test.part2 = j; list.push_back(test); } } // Step 3 -- sort the list by rtime /* given 2 objects, std::sort needs to know if the first one is smaller */ std::sort(std::begin(list), std::end(list), [](const Interaction &lhs, const Interaction &rhs){ return lhs.rtime < rhs.rtime; } ); return list; } // This performs our MD simulation with a vector of interactions // Also writes simulation to file, specified by README // Note: Time-loop here void simulate(std::vector<int> interactions, std::vector<Particle> curr_data){ } <|endoftext|>
<commit_before>#include <fstream> #include <cmath> #include "output.hpp" #include "tatum_assert.hpp" #include "TimingGraph.hpp" #include "TimingConstraints.hpp" #include "TimingTags.hpp" #include "timing_analyzers.hpp" using tatum::NodeId; using tatum::EdgeId; using tatum::DomainId; using tatum::TimingTags; using tatum::TimingTag; using tatum::TimingGraph; using tatum::TimingConstraints; void write_tags(std::ostream& os, const std::string& type, const TimingTags& tags, const NodeId node_id); void write_timing_graph(std::ostream& os, const TimingGraph& tg) { os << "timing_graph:" << "\n"; //We manually iterate to write the nodes in ascending order for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); os << " node: " << size_t(node_id) << "\n"; os << " type: " << tg.node_type(node_id); os << "\n"; os << " in_edges: "; for(EdgeId edge_id : tg.node_in_edges(node_id)) { os << size_t(edge_id) << " "; } os << "\n"; os << " out_edges: "; for(EdgeId edge_id : tg.node_out_edges(node_id)) { os << size_t(edge_id) << " "; } os << "\n"; } //We manually iterate to write the edges in ascending order for(size_t edge_idx = 0; edge_idx < tg.edges().size(); ++edge_idx) { EdgeId edge_id(edge_idx); os << " edge: " << size_t(edge_id) << "\n"; os << " src_node: " << size_t(tg.edge_src_node(edge_id)) << "\n"; os << " sink_node: " << size_t(tg.edge_sink_node(edge_id)) << "\n"; } os << "\n"; } void write_timing_constraints(std::ostream& os, const TimingConstraints& tc) { os << "timing_constraints:\n"; for(auto domain_id : tc.clock_domains()) { os << " type: CLOCK domain: " << size_t(domain_id) << " name: \"" << tc.clock_domain_name(domain_id) << "\"\n"; } for(auto domain_id : tc.clock_domains()) { NodeId source_node_id = tc.clock_domain_source_node(domain_id); if(source_node_id) { os << " type: CLOCK_SOURCE node: " << size_t(source_node_id) << " domain: " << size_t(domain_id) << "\n"; } } for(auto node_id : tc.constant_generators()) { os << " type: CONSTANT_GENERATOR node: " << size_t(node_id) << "\n"; } for(auto kv : tc.input_constraints()) { auto node_id = kv.first; auto domain_id = kv.second.domain; auto constraint = kv.second.constraint; if(!isnan(constraint)) { os << " type: INPUT_CONSTRAINT node: " << size_t(node_id) << " domain: " << size_t(domain_id) << " constraint: " << constraint << "\n"; } } for(auto kv : tc.output_constraints()) { auto node_id = kv.first; auto domain_id = kv.second.domain; auto constraint = kv.second.constraint; if(!isnan(constraint)) { os << " type: OUTPUT_CONSTRAINT node: " << size_t(node_id) << " domain: " << size_t(domain_id) << " constraint: " << constraint << "\n"; } } for(auto kv : tc.setup_constraints()) { auto key = kv.first; auto constraint = kv.second; if(!isnan(constraint)) { os << " type: SETUP_CONSTRAINT"; os << " src_domain: " << size_t(key.src_domain_id); os << " sink_domain: " << size_t(key.sink_domain_id); os << " constraint: " << constraint; os << "\n"; } } for(auto kv : tc.hold_constraints()) { auto key = kv.first; auto constraint = kv.second; if(!isnan(constraint)) { os << " type: HOLD_CONSTRAINT"; os << " src_domain: " << size_t(key.src_domain_id); os << " sink_domain: " << size_t(key.sink_domain_id); os << " constraint: " << constraint; os << "\n"; } } os << "\n"; } void write_analysis_result(std::ostream& os, const TimingGraph& tg, const std::shared_ptr<tatum::TimingAnalyzer> analyzer) { os << "analysis_result:\n"; auto setup_analyzer = std::dynamic_pointer_cast<tatum::SetupTimingAnalyzer>(analyzer); if(setup_analyzer) { for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); write_tags(os, "SETUP_DATA", setup_analyzer->get_setup_data_tags(node_id), node_id); } for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); write_tags(os, "SETUP_CLOCK", setup_analyzer->get_setup_clock_tags(node_id), node_id); } } auto hold_analyzer = std::dynamic_pointer_cast<tatum::HoldTimingAnalyzer>(analyzer); if(hold_analyzer) { for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); write_tags(os, "HOLD_DATA", hold_analyzer->get_hold_data_tags(node_id), node_id); } for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); write_tags(os, "HOLD_CLOCK", hold_analyzer->get_hold_clock_tags(node_id), node_id); } } os << "\n"; } void write_tags(std::ostream& os, const std::string& type, const TimingTags& tags, const NodeId node_id) { for(const auto& tag : tags) { float arr = tag.arr_time().value(); float req = tag.req_time().value(); if(!isnan(arr) || !isnan(req)) { os << " type: " << type; os << " node: " << size_t(node_id); os << " domain: " << size_t(tag.clock_domain()); if(!isnan(arr)) { os << " arr: " << arr; } if(!isnan(arr)) { os << " req: " << tag.req_time().value(); } os << "\n"; } } } <commit_msg>Sort out edges<commit_after>#include <fstream> #include <cmath> #include <vector> #include <algorithm> #include "output.hpp" #include "tatum_assert.hpp" #include "TimingGraph.hpp" #include "TimingConstraints.hpp" #include "TimingTags.hpp" #include "timing_analyzers.hpp" using tatum::NodeId; using tatum::EdgeId; using tatum::DomainId; using tatum::TimingTags; using tatum::TimingTag; using tatum::TimingGraph; using tatum::TimingConstraints; void write_tags(std::ostream& os, const std::string& type, const TimingTags& tags, const NodeId node_id); void write_timing_graph(std::ostream& os, const TimingGraph& tg) { os << "timing_graph:" << "\n"; //We manually iterate to write the nodes in ascending order for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); os << " node: " << size_t(node_id) << "\n"; os << " type: " << tg.node_type(node_id); os << "\n"; os << " in_edges: "; auto in_edges = tg.node_in_edges(node_id); std::vector<EdgeId> edges(in_edges.begin(), in_edges.end()); std::sort(edges.begin(), edges.end()); for(EdgeId edge_id : edges) { os << size_t(edge_id) << " "; } os << "\n"; os << " out_edges: "; auto out_edges = tg.node_out_edges(node_id); edges = std::vector<EdgeId>(out_edges.begin(), out_edges.end()); std::sort(edges.begin(), edges.end()); for(EdgeId edge_id : edges) { os << size_t(edge_id) << " "; } os << "\n"; } //We manually iterate to write the edges in ascending order for(size_t edge_idx = 0; edge_idx < tg.edges().size(); ++edge_idx) { EdgeId edge_id(edge_idx); os << " edge: " << size_t(edge_id) << "\n"; os << " src_node: " << size_t(tg.edge_src_node(edge_id)) << "\n"; os << " sink_node: " << size_t(tg.edge_sink_node(edge_id)) << "\n"; } os << "\n"; } void write_timing_constraints(std::ostream& os, const TimingConstraints& tc) { os << "timing_constraints:\n"; for(auto domain_id : tc.clock_domains()) { os << " type: CLOCK domain: " << size_t(domain_id) << " name: \"" << tc.clock_domain_name(domain_id) << "\"\n"; } for(auto domain_id : tc.clock_domains()) { NodeId source_node_id = tc.clock_domain_source_node(domain_id); if(source_node_id) { os << " type: CLOCK_SOURCE node: " << size_t(source_node_id) << " domain: " << size_t(domain_id) << "\n"; } } for(auto node_id : tc.constant_generators()) { os << " type: CONSTANT_GENERATOR node: " << size_t(node_id) << "\n"; } for(auto kv : tc.input_constraints()) { auto node_id = kv.first; auto domain_id = kv.second.domain; auto constraint = kv.second.constraint; if(!isnan(constraint)) { os << " type: INPUT_CONSTRAINT node: " << size_t(node_id) << " domain: " << size_t(domain_id) << " constraint: " << constraint << "\n"; } } for(auto kv : tc.output_constraints()) { auto node_id = kv.first; auto domain_id = kv.second.domain; auto constraint = kv.second.constraint; if(!isnan(constraint)) { os << " type: OUTPUT_CONSTRAINT node: " << size_t(node_id) << " domain: " << size_t(domain_id) << " constraint: " << constraint << "\n"; } } for(auto kv : tc.setup_constraints()) { auto key = kv.first; auto constraint = kv.second; if(!isnan(constraint)) { os << " type: SETUP_CONSTRAINT"; os << " src_domain: " << size_t(key.src_domain_id); os << " sink_domain: " << size_t(key.sink_domain_id); os << " constraint: " << constraint; os << "\n"; } } for(auto kv : tc.hold_constraints()) { auto key = kv.first; auto constraint = kv.second; if(!isnan(constraint)) { os << " type: HOLD_CONSTRAINT"; os << " src_domain: " << size_t(key.src_domain_id); os << " sink_domain: " << size_t(key.sink_domain_id); os << " constraint: " << constraint; os << "\n"; } } os << "\n"; } void write_analysis_result(std::ostream& os, const TimingGraph& tg, const std::shared_ptr<tatum::TimingAnalyzer> analyzer) { os << "analysis_result:\n"; auto setup_analyzer = std::dynamic_pointer_cast<tatum::SetupTimingAnalyzer>(analyzer); if(setup_analyzer) { for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); write_tags(os, "SETUP_DATA", setup_analyzer->get_setup_data_tags(node_id), node_id); } for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); write_tags(os, "SETUP_CLOCK", setup_analyzer->get_setup_clock_tags(node_id), node_id); } } auto hold_analyzer = std::dynamic_pointer_cast<tatum::HoldTimingAnalyzer>(analyzer); if(hold_analyzer) { for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); write_tags(os, "HOLD_DATA", hold_analyzer->get_hold_data_tags(node_id), node_id); } for(size_t node_idx = 0; node_idx < tg.nodes().size(); ++node_idx) { NodeId node_id(node_idx); write_tags(os, "HOLD_CLOCK", hold_analyzer->get_hold_clock_tags(node_id), node_id); } } os << "\n"; } void write_tags(std::ostream& os, const std::string& type, const TimingTags& tags, const NodeId node_id) { for(const auto& tag : tags) { float arr = tag.arr_time().value(); float req = tag.req_time().value(); if(!isnan(arr) || !isnan(req)) { os << " type: " << type; os << " node: " << size_t(node_id); os << " domain: " << size_t(tag.clock_domain()); if(!isnan(arr)) { os << " arr: " << arr; } if(!isnan(arr)) { os << " req: " << tag.req_time().value(); } os << "\n"; } } } <|endoftext|>
<commit_before>#ifndef MJOLNIR_CORE_VERLET_LIST #define MJOLNIR_CORE_VERLET_LIST #include <vector> #include <unordered_map> #include "SpatialPartition.hpp" namespace mjolnir { template<typename traitsT> class VerletList : public SpatialPartition<traitsT> { public: typedef SpatialPartition<traitsT> base_type; typedef typename base_type::time_type time_type; typedef typename base_type::real_type real_type; typedef typename base_type::coordinate_type coordinate_type; typedef typename base_type::particle_container_type particle_container_type; typedef typename base_type::index_type index_type; typedef typename base_type::index_list index_list; typedef std::vector<index_list> verlet_list_type; typedef std::vector<index_list> except_list_type; public: VerletList() = default; VerletList(const real_type cutoff, const real_type mergin) : dt_(0.), cutoff_(cutoff), mergin_(mergin), current_mergin_(-1.) {} VerletList(const real_type cutoff, const real_type mergin, const time_type dt) : dt_(dt), cutoff_(cutoff), mergin_(mergin), current_mergin_(-1.) {} ~VerletList() = default; bool valid() const noexcept override {return current_mergin_ >= 0. || dt_ == 0.;} void make (const particle_container_type& pcon) override; void update(const particle_container_type& pcon) override; void update(const particle_container_type& pcon, const time_type dt) override; real_type const& cutoff() const {return this->cutoff_;} real_type & cutoff() {return this->cutoff_;} real_type const& mergin() const {return this->mergin_;} real_type & mergin() {return this->mergin_;} void add_except(const index_type i, const index_type j); void set_except(const list_type& ex){excepts_ = ex;} void set_except(list_type&& ex){excepts_ = std::forward<list_type>(ex);} index_list const& partners(const std::size_t i) const override {return list_.at(i);} index_list & partners(const std::size_t i) override {return list_.at(i);} private: real_type dt_; real_type cutoff_; real_type mergin_; real_type current_mergin_; verlet_list_type list_; except_list_type except_; }; template<typename traitsT> inline void VerletList<traitsT>::add_except(const index_type i, const index_type j) { const index_type acc = std::min(i, j); const index_type dnr = std::max(i, j); if(this->excepts_.size() < acc) this->excepts_.resize(acc); this->excepts_.at(acc).push_back(dnr); return ; } template<typename traitsT> void VerletList<traitsT>::make(const particle_container_type& pcon) { list_.clear(); list_.resize(pcon.size()); const real_type rc = (cutoff_ + mergin_); const real_type rc2 = rc * rc; if(excepts_.empty()) { for(std::size_t i=0; i<pcon.size()-1; ++i) { const coordinate_type ri = pcon[i].position; for(std::size_t j=i+1; j<pcon.size(); ++j) { const coordinate_type rij = pcon[j].position - ri; const real_type r2 = length_sq(rij); if(r2 < rc2) { list_.at(i).push_back(j); } } } } else { for(std::size_t i=0; i<pcon.size()-1; ++i) { const coordinate_type ri = pcon[i].position; if(excepts_.at(i).empty()) { for(std::size_t j=i+1; j<pcon.size(); ++j) { const coordinate_type rij = pcon[j].position - ri; const real_type r2 = length_sq(rij); if(r2 < rc2) { list_.at(i).push_back(j); } } } else { list_.at(i).reserve(pcon.size() - i - 1 - excepts_.at(i).size()); const auto cbeg = excepts_.at(i).cbegin(); const auto cend = excepts_.at(i).cend(); for(std::size_t j=i+1; j<pcon.size(); ++j) { if(std::find(cbeg, cend, j) != cend) continue; const coordinate_type rij = pcon[j].position - ri; const real_type r2 = length_sq(rij); if(r2 < rc2) { list_.at(i).push_back(j); } } } } } this->current_mergin_ = mergin_; return ; } template<typename traitsT> void VerletList<traitsT>::update(const particle_container_type& pcon) { real_type max_speed = 0.; for(auto iter = pcon.cbegin(); iter != pcon.cend(); ++iter) max_speed = std::max(max_speed, length_sq(iter->velocity)); this->current_mergin_ -= std::sqrt(max_speed) * dt_ * 2.; if(this->current_mergin_ < 0.) this->make(pcon); return ; } template<typename traitsT> void VerletList<traitsT>::update(const particle_container_type& pcon, const time_type dt) { this->dt_ = dt; this->update(pcon); return ; } } // mjolnir #endif/* MJOLNIR_CORE_VERLET_LIST */ <commit_msg>fix typo<commit_after>#ifndef MJOLNIR_CORE_VERLET_LIST #define MJOLNIR_CORE_VERLET_LIST #include <vector> #include <unordered_map> #include "SpatialPartition.hpp" namespace mjolnir { template<typename traitsT> class VerletList : public SpatialPartition<traitsT> { public: typedef SpatialPartition<traitsT> base_type; typedef typename base_type::time_type time_type; typedef typename base_type::real_type real_type; typedef typename base_type::coordinate_type coordinate_type; typedef typename base_type::particle_container_type particle_container_type; typedef typename base_type::index_type index_type; typedef typename base_type::index_list index_list; typedef std::vector<index_list> verlet_list_type; typedef std::vector<index_list> except_list_type; public: VerletList() = default; VerletList(const real_type cutoff, const real_type mergin) : dt_(0.), cutoff_(cutoff), mergin_(mergin), current_mergin_(-1.) {} VerletList(const real_type cutoff, const real_type mergin, const time_type dt) : dt_(dt), cutoff_(cutoff), mergin_(mergin), current_mergin_(-1.) {} ~VerletList() = default; bool valid() const noexcept override {return current_mergin_ >= 0. || dt_ == 0.;} void make (const particle_container_type& pcon) override; void update(const particle_container_type& pcon) override; void update(const particle_container_type& pcon, const time_type dt) override; real_type const& cutoff() const {return this->cutoff_;} real_type & cutoff() {return this->cutoff_;} real_type const& mergin() const {return this->mergin_;} real_type & mergin() {return this->mergin_;} void add_except(const index_type i, const index_type j); void set_except(const list_type& ex){except_ = ex;} void set_except(list_type&& ex){except_ = std::forward<list_type>(ex);} index_list const& partners(const std::size_t i) const override {return list_.at(i);} index_list & partners(const std::size_t i) override {return list_.at(i);} private: real_type dt_; real_type cutoff_; real_type mergin_; real_type current_mergin_; verlet_list_type list_; except_list_type except_; }; template<typename traitsT> inline void VerletList<traitsT>::add_except(const index_type i, const index_type j) { const index_type acc = std::min(i, j); const index_type dnr = std::max(i, j); if(this->except_.size() < acc) this->except_.resize(acc); this->except_.at(acc).push_back(dnr); return ; } template<typename traitsT> void VerletList<traitsT>::make(const particle_container_type& pcon) { list_.clear(); list_.resize(pcon.size()); const real_type rc = (cutoff_ + mergin_); const real_type rc2 = rc * rc; if(except_.empty()) { for(std::size_t i=0; i<pcon.size()-1; ++i) { const coordinate_type ri = pcon[i].position; for(std::size_t j=i+1; j<pcon.size(); ++j) { const coordinate_type rij = pcon[j].position - ri; const real_type r2 = length_sq(rij); if(r2 < rc2) { list_.at(i).push_back(j); } } } } else { for(std::size_t i=0; i<pcon.size()-1; ++i) { const coordinate_type ri = pcon[i].position; if(except_.at(i).empty()) { for(std::size_t j=i+1; j<pcon.size(); ++j) { const coordinate_type rij = pcon[j].position - ri; const real_type r2 = length_sq(rij); if(r2 < rc2) { list_.at(i).push_back(j); } } } else { list_.at(i).reserve(pcon.size() - i - 1 - except_.at(i).size()); const auto cbeg = except_.at(i).cbegin(); const auto cend = except_.at(i).cend(); for(std::size_t j=i+1; j<pcon.size(); ++j) { if(std::find(cbeg, cend, j) != cend) continue; const coordinate_type rij = pcon[j].position - ri; const real_type r2 = length_sq(rij); if(r2 < rc2) { list_.at(i).push_back(j); } } } } } this->current_mergin_ = mergin_; return ; } template<typename traitsT> void VerletList<traitsT>::update(const particle_container_type& pcon) { real_type max_speed = 0.; for(auto iter = pcon.cbegin(); iter != pcon.cend(); ++iter) max_speed = std::max(max_speed, length_sq(iter->velocity)); this->current_mergin_ -= std::sqrt(max_speed) * dt_ * 2.; if(this->current_mergin_ < 0.) this->make(pcon); return ; } template<typename traitsT> void VerletList<traitsT>::update(const particle_container_type& pcon, const time_type dt) { this->dt_ = dt; this->update(pcon); return ; } } // mjolnir #endif/* MJOLNIR_CORE_VERLET_LIST */ <|endoftext|>
<commit_before>784a4720-2e4d-11e5-9284-b827eb9e62be<commit_msg>784f3348-2e4d-11e5-9284-b827eb9e62be<commit_after>784f3348-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>766aba7e-2e4e-11e5-9284-b827eb9e62be<commit_msg>766fc65e-2e4e-11e5-9284-b827eb9e62be<commit_after>766fc65e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>08d919e6-2e4f-11e5-9284-b827eb9e62be<commit_msg>08de23a0-2e4f-11e5-9284-b827eb9e62be<commit_after>08de23a0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fef20bc2-2e4e-11e5-9284-b827eb9e62be<commit_msg>fef7038e-2e4e-11e5-9284-b827eb9e62be<commit_after>fef7038e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3183eefe-2e4d-11e5-9284-b827eb9e62be<commit_msg>3188e06c-2e4d-11e5-9284-b827eb9e62be<commit_after>3188e06c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fa15b758-2e4d-11e5-9284-b827eb9e62be<commit_msg>fa1aad76-2e4d-11e5-9284-b827eb9e62be<commit_after>fa1aad76-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f64a0a02-2e4d-11e5-9284-b827eb9e62be<commit_msg>f64f00b6-2e4d-11e5-9284-b827eb9e62be<commit_after>f64f00b6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d535f8f4-2e4c-11e5-9284-b827eb9e62be<commit_msg>d53b15f0-2e4c-11e5-9284-b827eb9e62be<commit_after>d53b15f0-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dd628b8a-2e4e-11e5-9284-b827eb9e62be<commit_msg>dd6780f4-2e4e-11e5-9284-b827eb9e62be<commit_after>dd6780f4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>fe9acc88-2e4c-11e5-9284-b827eb9e62be<commit_msg>fe9fc54e-2e4c-11e5-9284-b827eb9e62be<commit_after>fe9fc54e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>58bc23f6-2e4d-11e5-9284-b827eb9e62be<commit_msg>58c12d10-2e4d-11e5-9284-b827eb9e62be<commit_after>58c12d10-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0342eb20-2e4e-11e5-9284-b827eb9e62be<commit_msg>0347e5b2-2e4e-11e5-9284-b827eb9e62be<commit_after>0347e5b2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>49fc7c98-2e4e-11e5-9284-b827eb9e62be<commit_msg>4a017d92-2e4e-11e5-9284-b827eb9e62be<commit_after>4a017d92-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>da332366-2e4e-11e5-9284-b827eb9e62be<commit_msg>da440f50-2e4e-11e5-9284-b827eb9e62be<commit_after>da440f50-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>82b74b76-2e4e-11e5-9284-b827eb9e62be<commit_msg>82bc5efe-2e4e-11e5-9284-b827eb9e62be<commit_after>82bc5efe-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b02d058c-2e4e-11e5-9284-b827eb9e62be<commit_msg>b03204f6-2e4e-11e5-9284-b827eb9e62be<commit_after>b03204f6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3223ad22-2e4d-11e5-9284-b827eb9e62be<commit_msg>32289cd8-2e4d-11e5-9284-b827eb9e62be<commit_after>32289cd8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f9fce336-2e4d-11e5-9284-b827eb9e62be<commit_msg>fa01d88c-2e4d-11e5-9284-b827eb9e62be<commit_after>fa01d88c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f3cb279c-2e4e-11e5-9284-b827eb9e62be<commit_msg>f3d023be-2e4e-11e5-9284-b827eb9e62be<commit_after>f3d023be-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>69f27980-2e4e-11e5-9284-b827eb9e62be<commit_msg>69f7785e-2e4e-11e5-9284-b827eb9e62be<commit_after>69f7785e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>092b19ae-2e4e-11e5-9284-b827eb9e62be<commit_msg>093028ea-2e4e-11e5-9284-b827eb9e62be<commit_after>093028ea-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>34b5eb6c-2e4e-11e5-9284-b827eb9e62be<commit_msg>34bbef62-2e4e-11e5-9284-b827eb9e62be<commit_after>34bbef62-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3ba9f360-2e4d-11e5-9284-b827eb9e62be<commit_msg>3baefb12-2e4d-11e5-9284-b827eb9e62be<commit_after>3baefb12-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ed884492-2e4d-11e5-9284-b827eb9e62be<commit_msg>ed8d9924-2e4d-11e5-9284-b827eb9e62be<commit_after>ed8d9924-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>70ded0a4-2e4e-11e5-9284-b827eb9e62be<commit_msg>70e3c960-2e4e-11e5-9284-b827eb9e62be<commit_after>70e3c960-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ba155e3e-2e4c-11e5-9284-b827eb9e62be<commit_msg>ba1a669a-2e4c-11e5-9284-b827eb9e62be<commit_after>ba1a669a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c5ab6d36-2e4e-11e5-9284-b827eb9e62be<commit_msg>c5b0808c-2e4e-11e5-9284-b827eb9e62be<commit_after>c5b0808c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>83c10dd6-2e4e-11e5-9284-b827eb9e62be<commit_msg>83c625aa-2e4e-11e5-9284-b827eb9e62be<commit_after>83c625aa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>43852d88-2e4e-11e5-9284-b827eb9e62be<commit_msg>438a4bf6-2e4e-11e5-9284-b827eb9e62be<commit_after>438a4bf6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ab9187ba-2e4d-11e5-9284-b827eb9e62be<commit_msg>ab967f7c-2e4d-11e5-9284-b827eb9e62be<commit_after>ab967f7c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>84021778-2e4d-11e5-9284-b827eb9e62be<commit_msg>84070e90-2e4d-11e5-9284-b827eb9e62be<commit_after>84070e90-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c485c678-2e4d-11e5-9284-b827eb9e62be<commit_msg>c48abbf6-2e4d-11e5-9284-b827eb9e62be<commit_after>c48abbf6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e63ded9a-2e4d-11e5-9284-b827eb9e62be<commit_msg>e642eca0-2e4d-11e5-9284-b827eb9e62be<commit_after>e642eca0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>dc13c876-2e4d-11e5-9284-b827eb9e62be<commit_msg>dc18df28-2e4d-11e5-9284-b827eb9e62be<commit_after>dc18df28-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3b3a4b26-2e4f-11e5-9284-b827eb9e62be<commit_msg>3b3f41e4-2e4f-11e5-9284-b827eb9e62be<commit_after>3b3f41e4-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f4832ece-2e4d-11e5-9284-b827eb9e62be<commit_msg>f48846b6-2e4d-11e5-9284-b827eb9e62be<commit_after>f48846b6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>673de850-2e4e-11e5-9284-b827eb9e62be<commit_msg>6742de46-2e4e-11e5-9284-b827eb9e62be<commit_after>6742de46-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>cf4f76f4-2e4c-11e5-9284-b827eb9e62be<commit_msg>cf546d1c-2e4c-11e5-9284-b827eb9e62be<commit_after>cf546d1c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f7d99ec8-2e4d-11e5-9284-b827eb9e62be<commit_msg>f7de99b4-2e4d-11e5-9284-b827eb9e62be<commit_after>f7de99b4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5e3bba5c-2e4e-11e5-9284-b827eb9e62be<commit_msg>5e40b214-2e4e-11e5-9284-b827eb9e62be<commit_after>5e40b214-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6b600040-2e4d-11e5-9284-b827eb9e62be<commit_msg>6b650860-2e4d-11e5-9284-b827eb9e62be<commit_after>6b650860-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>be40dbc6-2e4e-11e5-9284-b827eb9e62be<commit_msg>be45f138-2e4e-11e5-9284-b827eb9e62be<commit_after>be45f138-2e4e-11e5-9284-b827eb9e62be<|endoftext|>