text
stringlengths 54
60.6k
|
|---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bmp.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: rt $ $Date: 2005-09-08 08:52:06 $
*
* 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
*
************************************************************************/
#include <stdio.h>
#include <signal.h>
#include <vector>
using namespace std;
#include <vcl/svapp.hxx>
#include "solar.hrc"
#include "filedlg.hxx"
#include "bmpcore.hxx"
#include "bmp.hrc"
// ----------
// - BmpApp -
// ----------
class BmpApp : public BmpCreator
{
private:
String aOutputFileName;
BYTE cExitCode;
BOOL GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam );
BOOL GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams );
void SetExitCode( BYTE cExit )
{
if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
cExitCode = cExit;
}
void ShowUsage();
virtual void Message( const String& rText, BYTE cExitCode );
public:
BmpApp();
~BmpApp();
int Start( const ::std::vector< String >& rArgs );
};
// -----------------------------------------------------------------------------
BmpApp::BmpApp()
{
}
// -----------------------------------------------------------------------------
BmpApp::~BmpApp()
{
}
// -----------------------------------------------------------------------
BOOL BmpApp::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam )
{
BOOL bRet = FALSE;
for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ )
{
String aTestStr( '-' );
for( int n = 0; ( n < 2 ) && !bRet; n++ )
{
aTestStr += rSwitch;
if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
{
bRet = TRUE;
if( i < ( nCount - 1 ) )
rParam = rArgs[ i + 1 ];
else
rParam = String();
}
if( 0 == n )
aTestStr = '/';
}
}
return bRet;
}
// -----------------------------------------------------------------------
BOOL BmpApp::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams )
{
BOOL bRet = FALSE;
for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ )
{
String aTestStr( '-' );
for( int n = 0; ( n < 2 ) && !bRet; n++ )
{
aTestStr += rSwitch;
if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
{
if( i < ( nCount - 1 ) )
rParams.push_back( rArgs[ i + 1 ] );
else
rParams.push_back( String() );
break;
}
if( 0 == n )
aTestStr = '/';
}
}
return( rParams.size() > 0 );
}
// -----------------------------------------------------------------------
void BmpApp::Message( const String& rText, BYTE cExit )
{
if( EXIT_NOERROR != cExit )
SetExitCode( cExit );
ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
aText.Append( "\r\n" );
fprintf( stderr, aText.GetBuffer() );
}
// -----------------------------------------------------------------------------
void BmpApp::ShowUsage()
{
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmp srs_inputfile output_dir lang_dir lang_num -i input_dir [-i input_dir ][-f err_file]" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " -i ... name of directory to be searched for input files [multiple occurence is possible]" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " -f name of file, output should be written to" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmp /home/test.srs /home/out enus 01 -i /home/res -f /home/out/bmp.err" ) ), EXIT_NOERROR );
}
// -----------------------------------------------------------------------------
int BmpApp::Start( const ::std::vector< String >& rArgs )
{
String aOutName;
cExitCode = EXIT_NOERROR;
if( rArgs.size() >= 6 )
{
LangInfo aLangInfo;
USHORT nCurCmd = 0;
const String aSrsName( rArgs[ nCurCmd++ ] );
::std::vector< String > aInDirVector;
ByteString aLangDir;
aOutName = rArgs[ nCurCmd++ ];
aLangDir = ByteString( rArgs[ nCurCmd++ ], RTL_TEXTENCODING_ASCII_US );
aLangInfo.mnLangNum = static_cast< sal_uInt16 >( rArgs[ nCurCmd++ ].ToInt32() );
memcpy( aLangInfo.maLangDir, aLangDir.GetBuffer(), aLangDir.Len() + 1 );
GetCommandOption( rArgs, 'f', aOutputFileName );
GetCommandOptions( rArgs, 'i', aInDirVector );
Create( aSrsName, aInDirVector, aOutName, aLangInfo );
}
else
{
ShowUsage();
cExitCode = EXIT_COMMONERROR;
}
if( ( EXIT_NOERROR == cExitCode ) && aOutputFileName.Len() && aOutName.Len() )
{
SvFileStream aOStm( aOutputFileName, STREAM_WRITE | STREAM_TRUNC );
ByteString aStr( "Successfully generated ImageList(s) in: " );
aOStm.WriteLine( aStr.Append( ByteString( aOutName, RTL_TEXTENCODING_UTF8 ) ) );
aOStm.Close();
}
return cExitCode;
}
// --------
// - Main -
// --------
int main( int nArgCount, char* ppArgs[] )
{
#ifdef UNX
static char aDisplayVar[ 1024 ];
strcpy( aDisplayVar, "DISPLAY=" );
putenv( aDisplayVar );
#endif
::std::vector< String > aArgs;
BmpApp aBmpApp;
InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() );
for( int i = 1; i < nArgCount; i++ )
aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) );
return aBmpApp.Start( aArgs );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.15.326); FILE MERGED 2006/09/01 17:42:37 kaib 1.15.326.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bmp.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: obo $ $Date: 2006-09-17 14:11:28 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <stdio.h>
#include <signal.h>
#include <vector>
using namespace std;
#include <vcl/svapp.hxx>
#include "solar.hrc"
#include "filedlg.hxx"
#include "bmpcore.hxx"
#include "bmp.hrc"
// ----------
// - BmpApp -
// ----------
class BmpApp : public BmpCreator
{
private:
String aOutputFileName;
BYTE cExitCode;
BOOL GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam );
BOOL GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams );
void SetExitCode( BYTE cExit )
{
if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
cExitCode = cExit;
}
void ShowUsage();
virtual void Message( const String& rText, BYTE cExitCode );
public:
BmpApp();
~BmpApp();
int Start( const ::std::vector< String >& rArgs );
};
// -----------------------------------------------------------------------------
BmpApp::BmpApp()
{
}
// -----------------------------------------------------------------------------
BmpApp::~BmpApp()
{
}
// -----------------------------------------------------------------------
BOOL BmpApp::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam )
{
BOOL bRet = FALSE;
for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ )
{
String aTestStr( '-' );
for( int n = 0; ( n < 2 ) && !bRet; n++ )
{
aTestStr += rSwitch;
if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
{
bRet = TRUE;
if( i < ( nCount - 1 ) )
rParam = rArgs[ i + 1 ];
else
rParam = String();
}
if( 0 == n )
aTestStr = '/';
}
}
return bRet;
}
// -----------------------------------------------------------------------
BOOL BmpApp::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams )
{
BOOL bRet = FALSE;
for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ )
{
String aTestStr( '-' );
for( int n = 0; ( n < 2 ) && !bRet; n++ )
{
aTestStr += rSwitch;
if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
{
if( i < ( nCount - 1 ) )
rParams.push_back( rArgs[ i + 1 ] );
else
rParams.push_back( String() );
break;
}
if( 0 == n )
aTestStr = '/';
}
}
return( rParams.size() > 0 );
}
// -----------------------------------------------------------------------
void BmpApp::Message( const String& rText, BYTE cExit )
{
if( EXIT_NOERROR != cExit )
SetExitCode( cExit );
ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
aText.Append( "\r\n" );
fprintf( stderr, aText.GetBuffer() );
}
// -----------------------------------------------------------------------------
void BmpApp::ShowUsage()
{
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmp srs_inputfile output_dir lang_dir lang_num -i input_dir [-i input_dir ][-f err_file]" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " -i ... name of directory to be searched for input files [multiple occurence is possible]" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " -f name of file, output should be written to" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR );
Message( String( RTL_CONSTASCII_USTRINGPARAM( " bmp /home/test.srs /home/out enus 01 -i /home/res -f /home/out/bmp.err" ) ), EXIT_NOERROR );
}
// -----------------------------------------------------------------------------
int BmpApp::Start( const ::std::vector< String >& rArgs )
{
String aOutName;
cExitCode = EXIT_NOERROR;
if( rArgs.size() >= 6 )
{
LangInfo aLangInfo;
USHORT nCurCmd = 0;
const String aSrsName( rArgs[ nCurCmd++ ] );
::std::vector< String > aInDirVector;
ByteString aLangDir;
aOutName = rArgs[ nCurCmd++ ];
aLangDir = ByteString( rArgs[ nCurCmd++ ], RTL_TEXTENCODING_ASCII_US );
aLangInfo.mnLangNum = static_cast< sal_uInt16 >( rArgs[ nCurCmd++ ].ToInt32() );
memcpy( aLangInfo.maLangDir, aLangDir.GetBuffer(), aLangDir.Len() + 1 );
GetCommandOption( rArgs, 'f', aOutputFileName );
GetCommandOptions( rArgs, 'i', aInDirVector );
Create( aSrsName, aInDirVector, aOutName, aLangInfo );
}
else
{
ShowUsage();
cExitCode = EXIT_COMMONERROR;
}
if( ( EXIT_NOERROR == cExitCode ) && aOutputFileName.Len() && aOutName.Len() )
{
SvFileStream aOStm( aOutputFileName, STREAM_WRITE | STREAM_TRUNC );
ByteString aStr( "Successfully generated ImageList(s) in: " );
aOStm.WriteLine( aStr.Append( ByteString( aOutName, RTL_TEXTENCODING_UTF8 ) ) );
aOStm.Close();
}
return cExitCode;
}
// --------
// - Main -
// --------
int main( int nArgCount, char* ppArgs[] )
{
#ifdef UNX
static char aDisplayVar[ 1024 ];
strcpy( aDisplayVar, "DISPLAY=" );
putenv( aDisplayVar );
#endif
::std::vector< String > aArgs;
BmpApp aBmpApp;
InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() );
for( int i = 1; i < nArgCount; i++ )
aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) );
return aBmpApp.Start( aArgs );
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
setScales (float min_scale, int nr_octaves, int nr_scales_per_octave)
{
if (min_scale <= 0)
{
PCL_ERROR ("[pcl::%s::setScales] : min_scale (%f) must be positive!\n",
name_.c_str (), min_scale);
return;
}
if (nr_octaves <= 0)
{
PCL_ERROR ("[pcl::%s::setScales] : Number of octaves (%d) must be at least 1!\n",
name_.c_str (), nr_octaves);
return;
}
if (nr_scales_per_octave < 1)
{
PCL_ERROR ("[pcl::%s::setScales] : Number of scales per octave (%d) must be at least 1!\n",
name_.c_str (), nr_scales_per_octave);
return;
}
min_scale_ = min_scale;
nr_octaves_ = nr_octaves;
nr_scales_per_octave_ = nr_scales_per_octave;
this->setKSearch (1);
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
setMinimumContrast (float min_contrast)
{
if (min_contrast < 0)
{
PCL_ERROR ("[pcl::%s::setMinimumContrast] : min_contrast (%f) must be non-negative!\n",
name_.c_str (), min_contrast);
return;
}
min_contrast_ = min_contrast;
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
detectKeypoints (PointCloudOut &output)
{
// Check for valid inputs
if (min_scale_ == 0 || nr_octaves_ == 0 || nr_scales_per_octave_ == 0)
{
PCL_ERROR ("[pcl::%s::detectKeypoints] : A valid range of scales must be specified by setScales before detecting keypoints!\n", name_.c_str ());
return;
}
if (surface_ != input_)
{
PCL_WARN ("[pcl::%s::detectKeypoints] : A search surface has be set by setSearchSurface, but this SIFT keypoint detection algorithm does not support search surfaces other than the input cloud. The cloud provided in setInputCloud is being used instead.\n", name_.c_str ());
}
// Make sure the output cloud is empty
output.points.clear ();
// Create a local copy of the input cloud that will be resized for each octave
boost::shared_ptr<pcl::PointCloud<PointInT> > cloud (new pcl::PointCloud<PointInT> (*input_));
// Search for keypoints at each octave
float scale = min_scale_;
for (int i_octave = 0; i_octave < nr_octaves_; ++i_octave)
{
// Downsample the point cloud
VoxelGrid<PointInT> voxel_grid;
float s = 1.0 * scale; // note: this can be adjusted
voxel_grid.setLeafSize (s, s, s);
voxel_grid.setInputCloud (cloud);
voxel_grid.filter (*cloud);
// Make sure the downsampled cloud still has enough points
const size_t min_nr_points = 25;
if (cloud->points.size () < min_nr_points)
{
return;
}
// Update the KdTree with the downsampled points
tree_->setInputCloud (cloud);
// Detect keypoints for the current scale
detectKeypointsForOctave (*cloud, *tree_, scale, nr_scales_per_octave_, output);
// Increase the scale by another octave
scale *= 2;
}
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
detectKeypointsForOctave (const PointCloudIn &input, KdTree &tree, float base_scale, int nr_scales_per_octave,
PointCloudOut &output)
{
// Compute the difference of Gaussians (DoG) scale space
std::vector<float> scales (nr_scales_per_octave + 3);
for (int i_scale = 0; i_scale <= nr_scales_per_octave + 2; ++i_scale)
{
scales[i_scale] = base_scale * pow (2.0, (1.0 * i_scale - 1) / nr_scales_per_octave);
}
Eigen::MatrixXf diff_of_gauss;
computeScaleSpace (input, tree, scales, diff_of_gauss);
// Find extrema in the DoG scale space
std::vector<int> extrema_indices, extrema_scales;
findScaleSpaceExtrema (input, tree, diff_of_gauss, extrema_indices, extrema_scales);
// Add keypoints to output
for (size_t i_keypoint = 0; i_keypoint < extrema_indices.size (); ++i_keypoint)
{
PointOutT keypoint;
const int &keypoint_index = extrema_indices[i_keypoint];
keypoint.x = input.points[keypoint_index].x;
keypoint.y = input.points[keypoint_index].y;
keypoint.z = input.points[keypoint_index].z;
keypoint.scale = scales[extrema_scales[i_keypoint]];
output.points.push_back (keypoint);
}
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
computeScaleSpace (const PointCloudIn &input, KdTree &tree, const std::vector<float> &scales,
Eigen::MatrixXf &diff_of_gauss)
{
std::vector<int> nn_indices;
std::vector<float> nn_dist;
diff_of_gauss.resize (input.size (), scales.size () - 1);
// For efficiency, we will only filter over points within 3 standard deviations
const float max_radius = 3.0 * scales.back ();
for (size_t i_point = 0; i_point < input.size (); ++i_point)
{
tree.radiusSearch (i_point, max_radius, nn_indices, nn_dist); // *
// * note: at this stage of the algorithm, we must find all points within a radius defined by the maximum scale,
// regardless of the configurable search method specified by the user, so we directly employ tree.radiusSearch
// here instead of using searchForNeighbors.
// For each scale, compute the Gaussian "filter response" at the current point
float filter_response = 0;
float previous_filter_response;
for (size_t i_scale = 0; i_scale < scales.size (); ++i_scale)
{
float sigma_sqr = pow (scales[i_scale], 2);
float numerator = 0.0;
float denominator = 0.0;
for (size_t i_neighbor = 0; i_neighbor < nn_indices.size (); ++i_neighbor)
{
const float &value = getFieldValue_ (input.points[nn_indices[i_neighbor]]);
const float &dist_sqr = nn_dist[i_neighbor];
if (dist_sqr <= 9*sigma_sqr)
{
float w = exp (-0.5 * dist_sqr / sigma_sqr);
numerator += value * w;
denominator += w;
}
else break; // i.e. if dist > 3 standard deviations, then terminate early
}
previous_filter_response = filter_response;
filter_response = numerator / denominator;
// Compute the difference between adjacent scales
if (i_scale > 0)
{
diff_of_gauss (i_point, i_scale - 1) = filter_response - previous_filter_response;
}
}
}
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
findScaleSpaceExtrema (const PointCloudIn &input, KdTree &tree, const Eigen::MatrixXf &diff_of_gauss,
std::vector<int> &extrema_indices, std::vector<int> &extrema_scales)
{
const int k = 25;
std::vector<int> nn_indices (k);
std::vector<float> nn_dist (k);
float nr_scales = diff_of_gauss.cols ();
std::vector<float> min_val (nr_scales), max_val (nr_scales);
for (size_t i_point = 0; i_point < input.size (); ++i_point)
{
// Define the local neighborhood around the current point
tree.nearestKSearch (i_point, k, nn_indices, nn_dist); //*
// * note: the neighborhood for finding local extrema is best defined as a small fixed-k neighborhood, regardless of
// the configurable search method specified by the user, so we directly employ tree.nearestKSearch here instead
// of using searchForNeighbors
// At each scale, find the extreme values of the DoG within the current neighborhood
for (int i_scale = 0; i_scale < nr_scales; ++i_scale)
{
min_val[i_scale] = std::numeric_limits<float>::max ();
max_val[i_scale] = -std::numeric_limits<float>::max ();
for (size_t i_neighbor = 0; i_neighbor < nn_indices.size (); ++i_neighbor)
{
const float &d = diff_of_gauss (nn_indices[i_neighbor], i_scale);
min_val[i_scale] = (std::min) (min_val[i_scale], d);
max_val[i_scale] = (std::max) (max_val[i_scale], d);
}
}
// If the current point is an extreme value with high enough contrast, add it as a keypoint
for (int i_scale = 1; i_scale < nr_scales - 1; ++i_scale)
{
const float &val = diff_of_gauss (i_point, i_scale);
// Does the point have sufficient contrast?
if (fabs (val) >= min_contrast_)
{
// Is it a local minimum?
if ((val == min_val[i_scale]) &&
(val < min_val[i_scale - 1]) &&
(val < min_val[i_scale + 1]))
{
extrema_indices.push_back (i_point);
extrema_scales.push_back (i_scale);
}
// Is it a local maximum?
else if ((val == max_val[i_scale]) &&
(val > max_val[i_scale - 1]) &&
(val > max_val[i_scale + 1]))
{
extrema_indices.push_back (i_point);
extrema_scales.push_back (i_scale);
}
}
}
}
}
<commit_msg>Fixed a bug in SIFTKeypoint<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
setScales (float min_scale, int nr_octaves, int nr_scales_per_octave)
{
if (min_scale <= 0)
{
PCL_ERROR ("[pcl::%s::setScales] : min_scale (%f) must be positive!\n",
name_.c_str (), min_scale);
return;
}
if (nr_octaves <= 0)
{
PCL_ERROR ("[pcl::%s::setScales] : Number of octaves (%d) must be at least 1!\n",
name_.c_str (), nr_octaves);
return;
}
if (nr_scales_per_octave < 1)
{
PCL_ERROR ("[pcl::%s::setScales] : Number of scales per octave (%d) must be at least 1!\n",
name_.c_str (), nr_scales_per_octave);
return;
}
min_scale_ = min_scale;
nr_octaves_ = nr_octaves;
nr_scales_per_octave_ = nr_scales_per_octave;
this->setKSearch (1);
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
setMinimumContrast (float min_contrast)
{
if (min_contrast < 0)
{
PCL_ERROR ("[pcl::%s::setMinimumContrast] : min_contrast (%f) must be non-negative!\n",
name_.c_str (), min_contrast);
return;
}
min_contrast_ = min_contrast;
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
detectKeypoints (PointCloudOut &output)
{
// Check for valid inputs
if (min_scale_ == 0 || nr_octaves_ == 0 || nr_scales_per_octave_ == 0)
{
PCL_ERROR ("[pcl::%s::detectKeypoints] : A valid range of scales must be specified by setScales before detecting keypoints!\n", name_.c_str ());
return;
}
if (surface_ != input_)
{
PCL_WARN ("[pcl::%s::detectKeypoints] : A search surface has be set by setSearchSurface, but this SIFT keypoint detection algorithm does not support search surfaces other than the input cloud. The cloud provided in setInputCloud is being used instead.\n", name_.c_str ());
}
// Make sure the output cloud is empty
output.points.clear ();
// Create a local copy of the input cloud that will be resized for each octave
boost::shared_ptr<pcl::PointCloud<PointInT> > cloud (new pcl::PointCloud<PointInT> (*input_));
// Search for keypoints at each octave
float scale = min_scale_;
for (int i_octave = 0; i_octave < nr_octaves_; ++i_octave)
{
// Downsample the point cloud
VoxelGrid<PointInT> voxel_grid;
float s = 1.0 * scale; // note: this can be adjusted
voxel_grid.setLeafSize (s, s, s);
voxel_grid.setInputCloud (cloud);
boost::shared_ptr<pcl::PointCloud<PointInT> > temp (new pcl::PointCloud<PointInT>);
voxel_grid.filter (*temp);
cloud = temp;
// Make sure the downsampled cloud still has enough points
const size_t min_nr_points = 25;
if (cloud->points.size () < min_nr_points)
{
return;
}
// Update the KdTree with the downsampled points
tree_->setInputCloud (cloud);
// Detect keypoints for the current scale
detectKeypointsForOctave (*cloud, *tree_, scale, nr_scales_per_octave_, output);
// Increase the scale by another octave
scale *= 2;
}
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
detectKeypointsForOctave (const PointCloudIn &input, KdTree &tree, float base_scale, int nr_scales_per_octave,
PointCloudOut &output)
{
// Compute the difference of Gaussians (DoG) scale space
std::vector<float> scales (nr_scales_per_octave + 3);
for (int i_scale = 0; i_scale <= nr_scales_per_octave + 2; ++i_scale)
{
scales[i_scale] = base_scale * pow (2.0, (1.0 * i_scale - 1) / nr_scales_per_octave);
}
Eigen::MatrixXf diff_of_gauss;
computeScaleSpace (input, tree, scales, diff_of_gauss);
// Find extrema in the DoG scale space
std::vector<int> extrema_indices, extrema_scales;
findScaleSpaceExtrema (input, tree, diff_of_gauss, extrema_indices, extrema_scales);
// Add keypoints to output
for (size_t i_keypoint = 0; i_keypoint < extrema_indices.size (); ++i_keypoint)
{
PointOutT keypoint;
const int &keypoint_index = extrema_indices[i_keypoint];
keypoint.x = input.points[keypoint_index].x;
keypoint.y = input.points[keypoint_index].y;
keypoint.z = input.points[keypoint_index].z;
keypoint.scale = scales[extrema_scales[i_keypoint]];
output.points.push_back (keypoint);
}
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
computeScaleSpace (const PointCloudIn &input, KdTree &tree, const std::vector<float> &scales,
Eigen::MatrixXf &diff_of_gauss)
{
std::vector<int> nn_indices;
std::vector<float> nn_dist;
diff_of_gauss.resize (input.size (), scales.size () - 1);
// For efficiency, we will only filter over points within 3 standard deviations
const float max_radius = 3.0 * scales.back ();
for (size_t i_point = 0; i_point < input.size (); ++i_point)
{
tree.radiusSearch (i_point, max_radius, nn_indices, nn_dist); // *
// * note: at this stage of the algorithm, we must find all points within a radius defined by the maximum scale,
// regardless of the configurable search method specified by the user, so we directly employ tree.radiusSearch
// here instead of using searchForNeighbors.
// For each scale, compute the Gaussian "filter response" at the current point
float filter_response = 0;
float previous_filter_response;
for (size_t i_scale = 0; i_scale < scales.size (); ++i_scale)
{
float sigma_sqr = pow (scales[i_scale], 2);
float numerator = 0.0;
float denominator = 0.0;
for (size_t i_neighbor = 0; i_neighbor < nn_indices.size (); ++i_neighbor)
{
const float &value = getFieldValue_ (input.points[nn_indices[i_neighbor]]);
const float &dist_sqr = nn_dist[i_neighbor];
if (dist_sqr <= 9*sigma_sqr)
{
float w = exp (-0.5 * dist_sqr / sigma_sqr);
numerator += value * w;
denominator += w;
}
else break; // i.e. if dist > 3 standard deviations, then terminate early
}
previous_filter_response = filter_response;
filter_response = numerator / denominator;
// Compute the difference between adjacent scales
if (i_scale > 0)
{
diff_of_gauss (i_point, i_scale - 1) = filter_response - previous_filter_response;
}
}
}
}
template <typename PointInT, typename PointOutT>
void pcl::SIFTKeypoint<PointInT, PointOutT>::
findScaleSpaceExtrema (const PointCloudIn &input, KdTree &tree, const Eigen::MatrixXf &diff_of_gauss,
std::vector<int> &extrema_indices, std::vector<int> &extrema_scales)
{
const int k = 25;
std::vector<int> nn_indices (k);
std::vector<float> nn_dist (k);
float nr_scales = diff_of_gauss.cols ();
std::vector<float> min_val (nr_scales), max_val (nr_scales);
for (size_t i_point = 0; i_point < input.size (); ++i_point)
{
// Define the local neighborhood around the current point
tree.nearestKSearch (i_point, k, nn_indices, nn_dist); //*
// * note: the neighborhood for finding local extrema is best defined as a small fixed-k neighborhood, regardless of
// the configurable search method specified by the user, so we directly employ tree.nearestKSearch here instead
// of using searchForNeighbors
// At each scale, find the extreme values of the DoG within the current neighborhood
for (int i_scale = 0; i_scale < nr_scales; ++i_scale)
{
min_val[i_scale] = std::numeric_limits<float>::max ();
max_val[i_scale] = -std::numeric_limits<float>::max ();
for (size_t i_neighbor = 0; i_neighbor < nn_indices.size (); ++i_neighbor)
{
const float &d = diff_of_gauss (nn_indices[i_neighbor], i_scale);
min_val[i_scale] = (std::min) (min_val[i_scale], d);
max_val[i_scale] = (std::max) (max_val[i_scale], d);
}
}
// If the current point is an extreme value with high enough contrast, add it as a keypoint
for (int i_scale = 1; i_scale < nr_scales - 1; ++i_scale)
{
const float &val = diff_of_gauss (i_point, i_scale);
// Does the point have sufficient contrast?
if (fabs (val) >= min_contrast_)
{
// Is it a local minimum?
if ((val == min_val[i_scale]) &&
(val < min_val[i_scale - 1]) &&
(val < min_val[i_scale + 1]))
{
extrema_indices.push_back (i_point);
extrema_scales.push_back (i_scale);
}
// Is it a local maximum?
else if ((val == max_val[i_scale]) &&
(val > max_val[i_scale - 1]) &&
(val > max_val[i_scale + 1]))
{
extrema_indices.push_back (i_point);
extrema_scales.push_back (i_scale);
}
}
}
}
}
<|endoftext|>
|
<commit_before>#include <QDebug>
#include "Sleeper.hpp"
#include "Timer.hpp"
namespace Dissent {
namespace Utils {
Timer::Timer() : _next_timer(-1)
{
_queue = TimerQueue(&(TimerEvent::ReverseComparer));
_real_time = true;
}
Timer::~Timer()
{
Clear();
}
Timer& Timer::GetInstance()
{
static Timer timer;
return timer;
}
void Timer::QueueEvent(TimerEvent te)
{
_queue.push(te);
if(_queue.top() == te && _real_time) {
if(_next_timer != -1) {
killTimer(_next_timer);
}
_next_timer = startTimer(0);
}
}
TimerEvent Timer::QueueCallback(const QSharedPointer<TimerCallback> &callback,
int due_time)
{
TimerEvent te(callback, due_time);
QueueEvent(te);
return te;
}
TimerEvent Timer::QueueCallback(const QSharedPointer<TimerCallback> &callback,
int due_time, int period)
{
TimerEvent te(callback, due_time, period);
QueueEvent(te);
return te;
}
TimerEvent Timer::QueueCallback(TimerCallback *callback, int due_time)
{
TimerEvent te(callback, due_time);
QueueEvent(te);
return te;
}
TimerEvent Timer::QueueCallback(TimerCallback *callback, int due_time, int period)
{
TimerEvent te(callback, due_time, period);
QueueEvent(te);
return te;
}
void Timer::UseVirtualTime()
{
if(!_real_time) {
return;
}
_real_time = false;
Clear();
Time::GetInstance().UseVirtualTime();
}
void Timer::UseRealTime()
{
if(_real_time) {
return;
}
_real_time = true;
Clear();
Time::GetInstance().UseRealTime();
}
void Timer::timerEvent(QTimerEvent *event)
{
killTimer(event->timerId());
qint64 next = Run();
if(next > -1) {
_next_timer = startTimer(next);
}
}
qint64 Timer::Run()
{
int next = -1;
while(true) {
if(_queue.empty()) {
next = -1;
break;
}
TimerEvent te = _queue.top();
if(te.GetNextRun() <= Time::GetInstance().MSecsSinceEpoch()) {
_queue.pop();
te.Run();
if(te.GetPeriod() > 0) {
_queue.push(te);
}
} else {
next = te.GetNextRun() - Time::GetInstance().MSecsSinceEpoch();
break;
}
}
return next;
}
qint64 Timer::VirtualRun()
{
if(_real_time) {
return -1;
}
qint64 next = Run();
// @TODO make Utils::ThreadPool that for virtual clock runs the task
// inline as opposed to another thread
QThreadPool::globalInstance()->waitForDone();
QCoreApplication::processEvents();
QCoreApplication::sendPostedEvents();
return next;
}
void Timer::Clear()
{
if(_next_timer != -1) {
killTimer(_next_timer);
}
_next_timer = -1;
_queue = TimerQueue(&(TimerEvent::ReverseComparer));
}
}
}
<commit_msg>[Utils] Found a long lived race condition in the VirtualRun function<commit_after>#include <QDebug>
#include "Sleeper.hpp"
#include "Timer.hpp"
namespace Dissent {
namespace Utils {
Timer::Timer() : _next_timer(-1)
{
_queue = TimerQueue(&(TimerEvent::ReverseComparer));
_real_time = true;
}
Timer::~Timer()
{
Clear();
}
Timer& Timer::GetInstance()
{
static Timer timer;
return timer;
}
void Timer::QueueEvent(TimerEvent te)
{
_queue.push(te);
if(_queue.top() == te && _real_time) {
if(_next_timer != -1) {
killTimer(_next_timer);
}
_next_timer = startTimer(0);
}
}
TimerEvent Timer::QueueCallback(const QSharedPointer<TimerCallback> &callback,
int due_time)
{
TimerEvent te(callback, due_time);
QueueEvent(te);
return te;
}
TimerEvent Timer::QueueCallback(const QSharedPointer<TimerCallback> &callback,
int due_time, int period)
{
TimerEvent te(callback, due_time, period);
QueueEvent(te);
return te;
}
TimerEvent Timer::QueueCallback(TimerCallback *callback, int due_time)
{
TimerEvent te(callback, due_time);
QueueEvent(te);
return te;
}
TimerEvent Timer::QueueCallback(TimerCallback *callback, int due_time, int period)
{
TimerEvent te(callback, due_time, period);
QueueEvent(te);
return te;
}
void Timer::UseVirtualTime()
{
if(!_real_time) {
return;
}
_real_time = false;
Clear();
Time::GetInstance().UseVirtualTime();
}
void Timer::UseRealTime()
{
if(_real_time) {
return;
}
_real_time = true;
Clear();
Time::GetInstance().UseRealTime();
}
void Timer::timerEvent(QTimerEvent *event)
{
killTimer(event->timerId());
qint64 next = Run();
if(next > -1) {
_next_timer = startTimer(next);
}
}
qint64 Timer::Run()
{
int next = -1;
while(true) {
if(_queue.empty()) {
next = -1;
break;
}
TimerEvent te = _queue.top();
if(te.GetNextRun() <= Time::GetInstance().MSecsSinceEpoch()) {
_queue.pop();
te.Run();
if(te.GetPeriod() > 0) {
_queue.push(te);
}
} else {
next = te.GetNextRun() - Time::GetInstance().MSecsSinceEpoch();
break;
}
}
return next;
}
qint64 Timer::VirtualRun()
{
if(_real_time) {
return -1;
}
qint64 next = Run();
// @TODO make Utils::ThreadPool that for virtual clock runs the task
// inline as opposed to another thread
if(QThreadPool::globalInstance()->activeThreadCount()) {
QThreadPool::globalInstance()->waitForDone();
if(next == -1) {
next = VirtualRun();
}
}
if(QCoreApplication::hasPendingEvents()) {
QCoreApplication::processEvents();
QCoreApplication::sendPostedEvents();
if(next == -1) {
next = VirtualRun();
}
}
return next;
}
void Timer::Clear()
{
if(_next_timer != -1) {
killTimer(_next_timer);
}
_next_timer = -1;
_queue = TimerQueue(&(TimerEvent::ReverseComparer));
}
}
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "BackendPasses.h"
#include "llvm/Analysis/InlineCost.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Scalar.h"
//#include "clang/Basic/LangOptions.h"
//#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
using namespace cling;
using namespace clang;
using namespace llvm;
using namespace llvm::legacy;
namespace {
class KeepLocalGVPass: public ModulePass {
static char ID;
bool runOnGlobal(GlobalValue& GV) {
if (GV.isDeclaration())
return false; // no change.
// GV is a definition.
llvm::GlobalValue::LinkageTypes LT = GV.getLinkage();
if (!GV.isDiscardableIfUnused(LT))
return false;
if (LT == llvm::GlobalValue::InternalLinkage
|| LT == llvm::GlobalValue::PrivateLinkage) {
GV.setLinkage(llvm::GlobalValue::ExternalLinkage);
return true; // a change!
}
return false;
}
public:
KeepLocalGVPass() : ModulePass(ID) {}
bool runOnModule(Module &M) override {
bool ret = false;
for (auto &&F: M)
ret |= runOnGlobal(F);
for (auto &&G: M.globals())
ret |= runOnGlobal(G);
return ret;
}
};
}
char KeepLocalGVPass::ID = 0;
BackendPasses::~BackendPasses() {
//delete m_PMBuilder->Inliner;
}
void BackendPasses::CreatePasses(llvm::Module& M)
{
// From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses().
CodeGenOptions::InliningMethod Inlining = m_CGOpts.getInlining();
#if 0
CodeGenOptions& CGOpts_ = const_cast<CodeGenOptions&>(m_CGOpts);
// DON'T: we will not find our symbols...
//CGOpts_.CXXCtorDtorAliases = 1;
// Default clang -O2 on Linux 64bit also has the following, but see
// CIFactory.cpp.
CGOpts_.DisableFPElim = 0;
CGOpts_.DiscardValueNames = 1;
CGOpts_.OmitLeafFramePointer = 1;
CGOpts_.OptimizationLevel = 2;
CGOpts_.RelaxAll = 0;
CGOpts_.UnrollLoops = 1;
CGOpts_.VectorizeLoop = 1;
CGOpts_.VectorizeSLP = 1;
#endif
// Better inlining is pending https://bugs.llvm.org//show_bug.cgi?id=19668
// and its consequence https://sft.its.cern.ch/jira/browse/ROOT-7111
// shown e.g. by roottest/cling/stl/map/badstringMap
CGOpts_.setInlining(CodeGenOptions::NormalInlining);
unsigned OptLevel = m_CGOpts.OptimizationLevel;
CodeGenOptions::InliningMethod Inlining = m_CGOpts.getInlining();
// Handle disabling of LLVM optimization, where we want to preserve the
// internal module before any optimization.
if (m_CGOpts.DisableLLVMOpts) {
OptLevel = 0;
// Always keep at least ForceInline - NoInlining is deadly for libc++.
// Inlining = CGOpts.NoInlining;
}
llvm::PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = OptLevel;
PMBuilder.SizeLevel = m_CGOpts.OptimizeSize;
PMBuilder.BBVectorize = m_CGOpts.VectorizeBB;
PMBuilder.SLPVectorize = m_CGOpts.VectorizeSLP;
PMBuilder.LoopVectorize = m_CGOpts.VectorizeLoop;
PMBuilder.DisableTailCalls = m_CGOpts.DisableTailCalls;
PMBuilder.DisableUnitAtATime = !m_CGOpts.UnitAtATime;
PMBuilder.DisableUnrollLoops = !m_CGOpts.UnrollLoops;
PMBuilder.MergeFunctions = m_CGOpts.MergeFunctions;
PMBuilder.RerollLoops = m_CGOpts.RerollLoops;
PMBuilder.LibraryInfo = new TargetLibraryInfoImpl(m_TM.getTargetTriple());
switch (Inlining) {
case CodeGenOptions::OnlyHintInlining: // fall-through:
case CodeGenOptions::NoInlining: {
assert(0 && "libc++ requires at least OnlyAlwaysInlining!");
break;
}
case CodeGenOptions::NormalInlining: {
PMBuilder.Inliner =
createFunctionInliningPass(OptLevel, m_CGOpts.OptimizeSize);
break;
}
case CodeGenOptions::OnlyAlwaysInlining:
// Respect always_inline.
if (OptLevel == 0)
// Do not insert lifetime intrinsics at -O0.
PMBuilder.Inliner = createAlwaysInlinerPass(false);
else
PMBuilder.Inliner = createAlwaysInlinerPass();
break;
}
// Set up the per-module pass manager.
m_MPM.reset(new legacy::PassManager());
m_MPM->add(new KeepLocalGVPass());
m_MPM->add(createTargetTransformInfoWrapperPass(m_TM.getTargetIRAnalysis()));
// Add target-specific passes that need to run as early as possible.
PMBuilder.addExtension(
PassManagerBuilder::EP_EarlyAsPossible,
[&](const PassManagerBuilder &,
legacy::PassManagerBase &PM) {
m_TM.addEarlyAsPossiblePasses(PM);
});
PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
[&](const PassManagerBuilder &,
legacy::PassManagerBase &PM) {
PM.add(createAddDiscriminatorsPass());
});
//if (!CGOpts.RewriteMapFiles.empty())
// addSymbolRewriterPass(CGOpts, m_MPM);
PMBuilder.populateModulePassManager(*m_MPM);
m_FPM.reset(new legacy::FunctionPassManager(&M));
m_FPM->add(createTargetTransformInfoWrapperPass(m_TM.getTargetIRAnalysis()));
if (m_CGOpts.VerifyModule)
m_FPM->add(createVerifierPass());
PMBuilder.populateFunctionPassManager(*m_FPM);
}
void BackendPasses::runOnModule(Module& M) {
if (!m_MPM)
CreatePasses(M);
// Set up the per-function pass manager.
// Run the per-function passes on the module.
m_FPM->doInitialization();
for (auto&& I: M.functions())
if (!I.isDeclaration())
m_FPM->run(I);
m_FPM->doFinalization();
m_MPM->run(M);
}
<commit_msg>Force NormalInlining only for GCC.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "BackendPasses.h"
#include "llvm/Analysis/InlineCost.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Scalar.h"
//#include "clang/Basic/LangOptions.h"
//#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
using namespace cling;
using namespace clang;
using namespace llvm;
using namespace llvm::legacy;
namespace {
class KeepLocalGVPass: public ModulePass {
static char ID;
bool runOnGlobal(GlobalValue& GV) {
if (GV.isDeclaration())
return false; // no change.
// GV is a definition.
llvm::GlobalValue::LinkageTypes LT = GV.getLinkage();
if (!GV.isDiscardableIfUnused(LT))
return false;
if (LT == llvm::GlobalValue::InternalLinkage
|| LT == llvm::GlobalValue::PrivateLinkage) {
GV.setLinkage(llvm::GlobalValue::ExternalLinkage);
return true; // a change!
}
return false;
}
public:
KeepLocalGVPass() : ModulePass(ID) {}
bool runOnModule(Module &M) override {
bool ret = false;
for (auto &&F: M)
ret |= runOnGlobal(F);
for (auto &&G: M.globals())
ret |= runOnGlobal(G);
return ret;
}
};
}
char KeepLocalGVPass::ID = 0;
BackendPasses::~BackendPasses() {
//delete m_PMBuilder->Inliner;
}
void BackendPasses::CreatePasses(llvm::Module& M)
{
// From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses().
CodeGenOptions::InliningMethod Inlining = m_CGOpts.getInlining();
#if 0
CodeGenOptions& CGOpts_ = const_cast<CodeGenOptions&>(m_CGOpts);
// DON'T: we will not find our symbols...
//CGOpts_.CXXCtorDtorAliases = 1;
// Default clang -O2 on Linux 64bit also has the following, but see
// CIFactory.cpp.
CGOpts_.DisableFPElim = 0;
CGOpts_.DiscardValueNames = 1;
CGOpts_.OmitLeafFramePointer = 1;
CGOpts_.OptimizationLevel = 2;
CGOpts_.RelaxAll = 0;
CGOpts_.UnrollLoops = 1;
CGOpts_.VectorizeLoop = 1;
CGOpts_.VectorizeSLP = 1;
#endif
#ifdef __GNUC__
// Better inlining is pending https://bugs.llvm.org//show_bug.cgi?id=19668
// and its consequence https://sft.its.cern.ch/jira/browse/ROOT-7111
// shown e.g. by roottest/cling/stl/map/badstringMap
if (Inlining > CodeGenOptions::NormalInlining)
Inlining = CodeGenOptions::NormalInlining;
#endif
// Handle disabling of LLVM optimization, where we want to preserve the
// internal module before any optimization.
if (m_CGOpts.DisableLLVMOpts) {
OptLevel = 0;
// Always keep at least ForceInline - NoInlining is deadly for libc++.
// Inlining = CGOpts.NoInlining;
}
llvm::PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = OptLevel;
PMBuilder.SizeLevel = m_CGOpts.OptimizeSize;
PMBuilder.BBVectorize = m_CGOpts.VectorizeBB;
PMBuilder.SLPVectorize = m_CGOpts.VectorizeSLP;
PMBuilder.LoopVectorize = m_CGOpts.VectorizeLoop;
PMBuilder.DisableTailCalls = m_CGOpts.DisableTailCalls;
PMBuilder.DisableUnitAtATime = !m_CGOpts.UnitAtATime;
PMBuilder.DisableUnrollLoops = !m_CGOpts.UnrollLoops;
PMBuilder.MergeFunctions = m_CGOpts.MergeFunctions;
PMBuilder.RerollLoops = m_CGOpts.RerollLoops;
PMBuilder.LibraryInfo = new TargetLibraryInfoImpl(m_TM.getTargetTriple());
switch (Inlining) {
case CodeGenOptions::OnlyHintInlining: // fall-through:
case CodeGenOptions::NoInlining: {
assert(0 && "libc++ requires at least OnlyAlwaysInlining!");
break;
}
case CodeGenOptions::NormalInlining: {
PMBuilder.Inliner =
createFunctionInliningPass(OptLevel, m_CGOpts.OptimizeSize);
break;
}
case CodeGenOptions::OnlyAlwaysInlining:
// Respect always_inline.
if (OptLevel == 0)
// Do not insert lifetime intrinsics at -O0.
PMBuilder.Inliner = createAlwaysInlinerPass(false);
else
PMBuilder.Inliner = createAlwaysInlinerPass();
break;
}
// Set up the per-module pass manager.
m_MPM.reset(new legacy::PassManager());
m_MPM->add(new KeepLocalGVPass());
m_MPM->add(createTargetTransformInfoWrapperPass(m_TM.getTargetIRAnalysis()));
// Add target-specific passes that need to run as early as possible.
PMBuilder.addExtension(
PassManagerBuilder::EP_EarlyAsPossible,
[&](const PassManagerBuilder &,
legacy::PassManagerBase &PM) {
m_TM.addEarlyAsPossiblePasses(PM);
});
PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
[&](const PassManagerBuilder &,
legacy::PassManagerBase &PM) {
PM.add(createAddDiscriminatorsPass());
});
//if (!CGOpts.RewriteMapFiles.empty())
// addSymbolRewriterPass(CGOpts, m_MPM);
PMBuilder.populateModulePassManager(*m_MPM);
m_FPM.reset(new legacy::FunctionPassManager(&M));
m_FPM->add(createTargetTransformInfoWrapperPass(m_TM.getTargetIRAnalysis()));
if (m_CGOpts.VerifyModule)
m_FPM->add(createVerifierPass());
PMBuilder.populateFunctionPassManager(*m_FPM);
}
void BackendPasses::runOnModule(Module& M) {
if (!m_MPM)
CreatePasses(M);
// Set up the per-function pass manager.
// Run the per-function passes on the module.
m_FPM->doInitialization();
for (auto&& I: M.functions())
if (!I.isDeclaration())
m_FPM->run(I);
m_FPM->doFinalization();
m_MPM->run(M);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: sfxecode.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hjs $ $Date: 2004-06-25 16:31:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFXECODE_HXX
#define _SFXECODE_HXX
#include <tools/errcode.hxx>
#define ERRCODE_SFX_NOSTDTEMPLATE (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|1)
#define ERRCODE_SFX_NOTATEMPLATE (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|2)
#define ERRCODE_SFX_GENERAL (ERRCODE_AREA_SFX|ERRCODE_CLASS_GENERAL|3)
#define ERRCODE_SFX_DOLOADFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_READ|4)
#define ERRCODE_SFX_DOSAVECOMPLETEDFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_WRITE|5)
#define ERRCODE_SFX_COMMITFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_WRITE|6)
#define ERRCODE_SFX_HANDSOFFFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_GENERAL|7)
#define ERRCODE_SFX_DOINITNEWFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|8)
#define ERRCODE_SFX_CANTREADDOCINFO (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|9)
#define ERRCODE_SFX_ALREADYOPEN (ERRCODE_AREA_SFX|ERRCODE_CLASS_ALREADYEXISTS|10)
#define ERRCODE_SFX_WRONGPASSWORD (ERRCODE_AREA_SFX|ERRCODE_CLASS_READ|11)
#define ERRCODE_SFX_DOCUMENTREADONLY (ERRCODE_AREA_SFX|ERRCODE_CLASS_WRITE|12)
#define ERRCODE_SFX_OLEGENERAL (ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|14)
#define ERRCODE_SFXMSG_STYLEREPLACE (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|13)
#define ERRCODE_SFX_TEMPLATENOTFOUND (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|15)
#define ERRCODE_SFX_ISRELATIVE (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|16)
#define ERRCODE_SFX_FORCEDOCLOAD (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|17)
#define ERRCODE_SFX_NOFILTER (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|45)
#define ERRCODE_SFX_FORCEQUIET (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|47)
#define ERRCODE_SFX_CONSULTUSER (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|48)
#define ERRCODE_SFX_NEVERCHECKCONTENT (ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|49)
#define ERRCODE_SFX_CANTFINDORIGINAL (ERRCODE_AREA_SFX|ERRCODE_CLASS_GENERAL|19)
#define ERRCODE_SFX_RESTART (ERRCODE_AREA_SFX|ERRCODE_CLASS_GENERAL|20)
#define ERRCODE_SFX_CANTCREATECONTENT (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|21)
#define ERRCODE_SFX_CANTCREATELINK (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|22)
#define ERRCODE_SFX_WRONGBMKFORMAT (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|23)
#define ERRCODE_SFX_WRONGICONFILE (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|24)
#define ERRCODE_SFX_CANTDELICONFILE (ERRCODE_AREA_SFX|ERRCODE_CLASS_ACCESS|25)
#define ERRCODE_SFX_CANTWRITEICONFILE (ERRCODE_AREA_SFX|ERRCODE_CLASS_ACCESS|26)
#define ERRCODE_SFX_CANTRENAMECONTENT (ERRCODE_AREA_SFX|ERRCODE_CLASS_ACCESS|27)
#define ERRCODE_SFX_INVALIDBMKPATH (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|28)
#define ERRCODE_SFX_CANTWRITEURLCFGFILE (ERRCODE_AREA_SFX|ERRCODE_CLASS_ACCESS|29)
#define ERRCODE_SFX_WRONGURLCFGFORMAT (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|30)
#define ERRCODE_SFX_NODOCUMENT (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|31)
#define ERRCODE_SFX_INVALIDLINK (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|32)
#define ERRCODE_SFX_INVALIDTRASHPATH (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|33)
#define ERRCODE_SFX_NOTRESTORABLE (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|34)
#define ERRCODE_SFX_NOTRASH (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|35)
#define ERRCODE_SFX_INVALIDSYNTAX (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|36)
#define ERRCODE_SFX_CANTCREATEFOLDER (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|37)
#define ERRCODE_SFX_CANTRENAMEFOLDER (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|38)
#define ERRCODE_SFX_WRONG_CDF_FORMAT (ERRCODE_AREA_SFX| ERRCODE_CLASS_READ | 39)
#define ERRCODE_SFX_EMPTY_SERVER (ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|40)
#define ERRCODE_SFX_NO_ABOBOX (ERRCODE_AREA_SFX| ERRCODE_CLASS_READ | 41)
#define ERRCODE_SFX_CANTGETPASSWD (ERRCODE_AREA_SFX| ERRCODE_CLASS_READ | 42)
//Dies und das
#define ERRCTX_ERROR 21
#define ERRCTX_WARNING 22
//Documentkontexte
#define ERRCTX_SFX_LOADTEMPLATE 1
#define ERRCTX_SFX_SAVEDOC 2
#define ERRCTX_SFX_SAVEASDOC 3
#define ERRCTX_SFX_DOCINFO 4
#define ERRCTX_SFX_DOCTEMPLATE 5
#define ERRCTX_SFX_MOVEORCOPYCONTENTS 6
//Appkontexte
#define ERRCTX_SFX_DOCMANAGER 50
#define ERRCTX_SFX_OPENDOC 51
#define ERRCTX_SFX_NEWDOCDIRECT 52
#define ERRCTX_SFX_NEWDOC 53
//Organizerkontexte
#define ERRCTX_SFX_CREATEOBJSH 70
//BASIC-Kontexte
#define ERRCTX_SFX_LOADBASIC 80
//Addressbook contexts
#define ERRCTX_SFX_SEARCHADDRESS 90
#endif // #ifndef _SFXECODE_HXX
<commit_msg>INTEGRATION: CWS docking2 (1.3.28); FILE MERGED 2004/07/16 15:32:52 mav 1.3.28.1: #i31253# new error code<commit_after>/*************************************************************************
*
* $RCSfile: sfxecode.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-08-02 15:07:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFXECODE_HXX
#define _SFXECODE_HXX
#include <tools/errcode.hxx>
#define ERRCODE_SFX_NOSTDTEMPLATE (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|1)
#define ERRCODE_SFX_NOTATEMPLATE (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|2)
#define ERRCODE_SFX_GENERAL (ERRCODE_AREA_SFX|ERRCODE_CLASS_GENERAL|3)
#define ERRCODE_SFX_DOLOADFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_READ|4)
#define ERRCODE_SFX_DOSAVECOMPLETEDFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_WRITE|5)
#define ERRCODE_SFX_COMMITFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_WRITE|6)
#define ERRCODE_SFX_HANDSOFFFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_GENERAL|7)
#define ERRCODE_SFX_DOINITNEWFAILED (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|8)
#define ERRCODE_SFX_CANTREADDOCINFO (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|9)
#define ERRCODE_SFX_ALREADYOPEN (ERRCODE_AREA_SFX|ERRCODE_CLASS_ALREADYEXISTS|10)
#define ERRCODE_SFX_WRONGPASSWORD (ERRCODE_AREA_SFX|ERRCODE_CLASS_READ|11)
#define ERRCODE_SFX_DOCUMENTREADONLY (ERRCODE_AREA_SFX|ERRCODE_CLASS_WRITE|12)
#define ERRCODE_SFX_OLEGENERAL (ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|14)
#define ERRCODE_SFXMSG_STYLEREPLACE (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|13)
#define ERRCODE_SFX_TEMPLATENOTFOUND (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|15)
#define ERRCODE_SFX_ISRELATIVE (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|16)
#define ERRCODE_SFX_FORCEDOCLOAD (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|17)
#define ERRCODE_SFX_NOFILTER (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|45)
#define ERRCODE_SFX_FORCEQUIET (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|47)
#define ERRCODE_SFX_CONSULTUSER (ERRCODE_WARNING_MASK|ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|48)
#define ERRCODE_SFX_NEVERCHECKCONTENT (ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|49)
#define ERRCODE_SFX_CANTFINDORIGINAL (ERRCODE_AREA_SFX|ERRCODE_CLASS_GENERAL|19)
#define ERRCODE_SFX_RESTART (ERRCODE_AREA_SFX|ERRCODE_CLASS_GENERAL|20)
#define ERRCODE_SFX_CANTCREATECONTENT (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|21)
#define ERRCODE_SFX_CANTCREATELINK (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|22)
#define ERRCODE_SFX_WRONGBMKFORMAT (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|23)
#define ERRCODE_SFX_WRONGICONFILE (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|24)
#define ERRCODE_SFX_CANTDELICONFILE (ERRCODE_AREA_SFX|ERRCODE_CLASS_ACCESS|25)
#define ERRCODE_SFX_CANTWRITEICONFILE (ERRCODE_AREA_SFX|ERRCODE_CLASS_ACCESS|26)
#define ERRCODE_SFX_CANTRENAMECONTENT (ERRCODE_AREA_SFX|ERRCODE_CLASS_ACCESS|27)
#define ERRCODE_SFX_INVALIDBMKPATH (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|28)
#define ERRCODE_SFX_CANTWRITEURLCFGFILE (ERRCODE_AREA_SFX|ERRCODE_CLASS_ACCESS|29)
#define ERRCODE_SFX_WRONGURLCFGFORMAT (ERRCODE_AREA_SFX|ERRCODE_CLASS_FORMAT|30)
#define ERRCODE_SFX_NODOCUMENT (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|31)
#define ERRCODE_SFX_INVALIDLINK (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|32)
#define ERRCODE_SFX_INVALIDTRASHPATH (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|33)
#define ERRCODE_SFX_NOTRESTORABLE (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|34)
#define ERRCODE_SFX_NOTRASH (ERRCODE_AREA_SFX|ERRCODE_CLASS_NOTEXISTS|35)
#define ERRCODE_SFX_INVALIDSYNTAX (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|36)
#define ERRCODE_SFX_CANTCREATEFOLDER (ERRCODE_AREA_SFX|ERRCODE_CLASS_CREATE|37)
#define ERRCODE_SFX_CANTRENAMEFOLDER (ERRCODE_AREA_SFX|ERRCODE_CLASS_PATH|38)
#define ERRCODE_SFX_WRONG_CDF_FORMAT (ERRCODE_AREA_SFX| ERRCODE_CLASS_READ | 39)
#define ERRCODE_SFX_EMPTY_SERVER (ERRCODE_AREA_SFX|ERRCODE_CLASS_NONE|40)
#define ERRCODE_SFX_NO_ABOBOX (ERRCODE_AREA_SFX| ERRCODE_CLASS_READ | 41)
#define ERRCODE_SFX_CANTGETPASSWD (ERRCODE_AREA_SFX| ERRCODE_CLASS_READ | 42)
#define ERRCODE_SFX_TARGETFILECORRUPTED (ERRCODE_AREA_SFX| ERRCODE_CLASS_READ | 43)
//Dies und das
#define ERRCTX_ERROR 21
#define ERRCTX_WARNING 22
//Documentkontexte
#define ERRCTX_SFX_LOADTEMPLATE 1
#define ERRCTX_SFX_SAVEDOC 2
#define ERRCTX_SFX_SAVEASDOC 3
#define ERRCTX_SFX_DOCINFO 4
#define ERRCTX_SFX_DOCTEMPLATE 5
#define ERRCTX_SFX_MOVEORCOPYCONTENTS 6
//Appkontexte
#define ERRCTX_SFX_DOCMANAGER 50
#define ERRCTX_SFX_OPENDOC 51
#define ERRCTX_SFX_NEWDOCDIRECT 52
#define ERRCTX_SFX_NEWDOC 53
//Organizerkontexte
#define ERRCTX_SFX_CREATEOBJSH 70
//BASIC-Kontexte
#define ERRCTX_SFX_LOADBASIC 80
//Addressbook contexts
#define ERRCTX_SFX_SEARCHADDRESS 90
#endif // #ifndef _SFXECODE_HXX
<|endoftext|>
|
<commit_before>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <windows.h>
#include "hadesmem/config.hpp"
namespace hadesmem
{
class Process;
namespace detail
{
enum class ProtectGuardType
{
kRead,
kWrite
};
class ProtectGuard
{
public:
ProtectGuard(Process const* process, PVOID address, ProtectGuardType type);
ProtectGuard(ProtectGuard&& other) HADESMEM_NOEXCEPT;
ProtectGuard& operator=(ProtectGuard&& other) HADESMEM_NOEXCEPT;
~ProtectGuard();
void Restore();
void RestoreUnchecked() HADESMEM_NOEXCEPT;
private:
ProtectGuard(ProtectGuard const& other) HADESMEM_DELETED_FUNCTION;
ProtectGuard& operator=(ProtectGuard const& other) HADESMEM_DELETED_FUNCTION;
Process const* process_;
ProtectGuardType type_;
bool can_read_or_write_;
DWORD old_protect_;
MEMORY_BASIC_INFORMATION mbi_;
};
}
}
<commit_msg>* More explicit specifiers.<commit_after>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <windows.h>
#include "hadesmem/config.hpp"
namespace hadesmem
{
class Process;
namespace detail
{
enum class ProtectGuardType
{
kRead,
kWrite
};
class ProtectGuard
{
public:
explicit ProtectGuard(Process const* process, PVOID address,
ProtectGuardType type);
ProtectGuard(ProtectGuard&& other) HADESMEM_NOEXCEPT;
ProtectGuard& operator=(ProtectGuard&& other) HADESMEM_NOEXCEPT;
~ProtectGuard();
void Restore();
void RestoreUnchecked() HADESMEM_NOEXCEPT;
private:
ProtectGuard(ProtectGuard const& other) HADESMEM_DELETED_FUNCTION;
ProtectGuard& operator=(ProtectGuard const& other) HADESMEM_DELETED_FUNCTION;
Process const* process_;
ProtectGuardType type_;
bool can_read_or_write_;
DWORD old_protect_;
MEMORY_BASIC_INFORMATION mbi_;
};
}
}
<|endoftext|>
|
<commit_before>//============================================================================//
// File: qcan_network.cpp //
// Description: QCAN classes - CAN network //
// //
// Copyright (C) MicroControl GmbH & Co. KG //
// 53842 Troisdorf - Germany //
// www.microcontrol.net //
// //
//----------------------------------------------------------------------------//
// Redistribution and use in source and binary forms, with or without //
// modification, are permitted provided that the following conditions //
// are met: //
// 1. Redistributions of source code must retain the above copyright //
// notice, this list of conditions, the following disclaimer and //
// the referenced file 'COPYING'. //
// 2. Redistributions in binary form must reproduce the above copyright //
// notice, this list of conditions and the following disclaimer in the //
// documentation and/or other materials provided with the distribution. //
// 3. Neither the name of MicroControl nor the names of its contributors //
// may be used to endorse or promote products derived from this software //
// without specific prior written permission. //
// //
// Provided that this notice is retained in full, this software may be //
// distributed under the terms of the GNU Lesser General Public License //
// ("LGPL") version 3 as distributed in the 'COPYING' file. //
// //
//============================================================================//
/*----------------------------------------------------------------------------*\
** Include files **
** **
\*----------------------------------------------------------------------------*/
#include <QDebug>
#include "qcan_interface.hpp"
#include "qcan_network.hpp"
/*----------------------------------------------------------------------------*\
** Definitions **
** **
\*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*\
** Static variables **
** **
\*----------------------------------------------------------------------------*/
uint8_t QCanNetwork::ubNetIdP = 0;
/*----------------------------------------------------------------------------*\
** Class methods **
** **
\*----------------------------------------------------------------------------*/
//----------------------------------------------------------------------------//
// QCanNetwork() //
// constructor //
//----------------------------------------------------------------------------//
QCanNetwork::QCanNetwork(QObject * pclParentV,
uint16_t uwPortV)
{
//----------------------------------------------------------------
// set the parent
//
this->setParent(pclParentV);
//----------------------------------------------------------------
// each network has a unique network number, starting with 1
//
ubNetIdP++;
pclInterfaceP.clear();
//----------------------------------------------------------------
// set default network name
//
clNetNameP = "CAN " + QString("%1").arg(ubNetIdP);
//----------------------------------------------------------------
// create initial socket list
//
pclTcpSockListP = new QVector<QTcpSocket *>;
pclTcpSockListP->reserve(QCAN_TCP_SOCKET_MAX);
//----------------------------------------------------------------
// setup a new local server which is listening to the
// default network name
//
pclTcpSrvP = new QTcpServer();
clTcpHostAddrP = QHostAddress(QHostAddress::LocalHost);
uwTcpPortP = uwPortV;
//----------------------------------------------------------------
// clear statistic
//
ulCntFrameApiP = 0;
ulCntFrameCanP = 0;
ulCntFrameErrP = 0;
//----------------------------------------------------------------
// setup timing values
//
ulDispatchTimeP = 20;
ulStatisticTimeP = 250;
ulStatisticTickP = ulStatisticTimeP / ulDispatchTimeP;
//----------------------------------------------------------------
// setup default bit-rate
//
setBitrate(QCan::eCAN_BITRATE_500K, -1);
}
//----------------------------------------------------------------------------//
// ~QCanNetwork() //
// destructor //
//----------------------------------------------------------------------------//
QCanNetwork::~QCanNetwork()
{
//----------------------------------------------------------------
// close TCP server
//
if(pclTcpSrvP->isListening())
{
pclTcpSrvP->close();
}
delete(pclTcpSrvP);
ubNetIdP--;
}
//----------------------------------------------------------------------------//
// addInterface() //
// add physical CAN interface (plugin) //
//----------------------------------------------------------------------------//
bool QCanNetwork::addInterface(QCanInterface * pclCanIfV)
{
bool btResultT = false;
if(pclInterfaceP.isNull())
{
pclInterfaceP = pclCanIfV;
btResultT = true;
}
return (btResultT);
}
bool QCanNetwork::hasErrorFramesSupport(void)
{
return(false);
}
bool QCanNetwork::hasFastDataSupport(void)
{
return(false);
}
bool QCanNetwork::hasListenOnlySupport(void)
{
return(false);
}
//----------------------------------------------------------------------------//
// handleApiFrame() //
// //
//----------------------------------------------------------------------------//
bool QCanNetwork::handleApiFrame(int32_t & slSockSrcR,
QCanFrameApi & clApiFrameR)
{
bool btResultT = false;
switch(clApiFrameR.function())
{
case QCanFrameApi::eAPI_FUNC_NONE:
break;
case QCanFrameApi::eAPI_FUNC_BITRATE:
if(!pclInterfaceP.isNull())
{
pclInterfaceP->setBitrate( clApiFrameR.bitrate(),
clApiFrameR.brsClock());
}
btResultT = true;
break;
case QCanFrameApi::eAPI_FUNC_CAN_MODE:
break;
case QCanFrameApi::eAPI_FUNC_DRIVER_INIT:
break;
case QCanFrameApi::eAPI_FUNC_DRIVER_RELEASE:
break;
case QCanFrameApi::eAPI_FUNC_PROCESS_ID:
break;
default:
break;
}
ulCntFrameApiP++;
return(btResultT);
}
//----------------------------------------------------------------------------//
// handleCanFrame() //
// push QCan frame to all open sockets //
//----------------------------------------------------------------------------//
bool QCanNetwork::handleCanFrame(int32_t & slSockSrcR,
QByteArray & clSockDataR)
{
int32_t slSockIdxT;
bool btResultT = false;
QTcpSocket * pclSockS;
//----------------------------------------------------------------
// check all open sockets and write CAN frame
//
for(slSockIdxT = 0; slSockIdxT < pclTcpSockListP->size(); slSockIdxT++)
{
if(slSockIdxT != slSockSrcR)
{
pclSockS = pclTcpSockListP->at(slSockIdxT);
pclSockS->write(clSockDataR);
pclSockS->flush();
btResultT = true;
}
}
if(btResultT == true)
{
ulCntFrameCanP++;
}
return(btResultT);
}
//----------------------------------------------------------------------------//
// handleErrorFrame() //
// //
//----------------------------------------------------------------------------//
bool QCanNetwork::handleErrFrame(int32_t & slSockSrcR,
QCanFrameError & clErrorFrameR)
{
bool btResultT = false;
return(btResultT);
}
//----------------------------------------------------------------------------//
// onTcpSrvNewConnection() //
// slot that manages a new local server connection //
//----------------------------------------------------------------------------//
void QCanNetwork::onSocketConnect(void)
{
QTcpSocket * pclSocketT;
//----------------------------------------------------------------
// Get next pending connect and add this socket to the
// the socket list
//
pclSocketT = pclTcpSrvP->nextPendingConnection();
clTcpSockMutexP.lock();
pclTcpSockListP->append(pclSocketT);
clTcpSockMutexP.unlock();
qDebug() << "QCanNetwork::onSocketConnect()" << pclTcpSockListP->size() << "open sockets";
qDebug() << "Socket" << pclSocketT;
//----------------------------------------------------------------
// Add a slot that handles the disconnection of the socket
// from the local server
//
connect( pclSocketT,
SIGNAL(disconnected()),
this,
SLOT(onSocketDisconnect()) );
}
//----------------------------------------------------------------------------//
// setBitrate() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setBitrate(int32_t slBitrateV, int32_t slBrsClockV)
{
slBitrateP = slBitrateV;
slBrsClockP = slBrsClockV;
}
//----------------------------------------------------------------------------//
// setDispatcherTime() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setDispatcherTime(uint32_t ulTimeV)
{
ulDispatchTimeP = ulTimeV;
}
//----------------------------------------------------------------------------//
// setErrorFramesEnabled() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setErrorFramesEnabled(bool btEnableV)
{
if(hasErrorFramesSupport() == true)
{
btErrorFramesEnabledP = btEnableV;
}
else
{
btErrorFramesEnabledP = false;
}
}
//----------------------------------------------------------------------------//
// setFastDataEnabled() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setFastDataEnabled(bool btEnableV)
{
if(hasFastDataSupport() == true)
{
btFastDataEnabledP = btEnableV;
}
else
{
btFastDataEnabledP = false;
}
}
//----------------------------------------------------------------------------//
// setListenOnlyEnabled() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setListenOnlyEnabled(bool btEnableV)
{
{btListenOnlyEnabledP = btEnableV;};
}
//----------------------------------------------------------------------------//
// setNetworkEnabled() //
// start / stop the TCP server //
//----------------------------------------------------------------------------//
void QCanNetwork::setNetworkEnabled(bool btEnableV)
{
if(btEnableV == true)
{
//--------------------------------------------------------
// limit the number of connections
//
pclTcpSrvP->setMaxPendingConnections(QCAN_TCP_SOCKET_MAX);
if(!pclTcpSrvP->listen(clTcpHostAddrP, uwTcpPortP))
{
qDebug() << "QCanNetwork(): can not listen to " << clNetNameP;
}
//--------------------------------------------------------
// a new connection is handled by the onTcpSrvNewConnection()
// method
//
connect( pclTcpSrvP, SIGNAL(newConnection()),
this, SLOT(onSocketConnect()));
//--------------------------------------------------------
// start network thread
//
clDispatchTmrP.singleShot(ulDispatchTimeP, this, SLOT(onTimerEvent()));
//--------------------------------------------------------
// set flag for further operations
//
btNetworkEnabledP = true;
}
else
{
//--------------------------------------------------------
// stop timer for message dispatching
//
clDispatchTmrP.stop();
//--------------------------------------------------------
// remove signal / slot connection
//
disconnect( pclTcpSrvP, SIGNAL(newConnection()),
this, SLOT(onSocketConnect()));
//--------------------------------------------------------
// close TCP server
//
qDebug() << "Close server";
pclTcpSrvP->close();
//--------------------------------------------------------
// set flag for further operations
//
btNetworkEnabledP = false;
}
}
//----------------------------------------------------------------------------//
// onSocketDisconnect() //
// remove local socket from list //
//----------------------------------------------------------------------------//
void QCanNetwork::onSocketDisconnect(void)
{
int32_t slSockIdxT;
QTcpSocket * pclSockT;
QTcpSocket * pclSenderT;
//----------------------------------------------------------------
// get sender of signal
//
pclSenderT = (QTcpSocket* ) QObject::sender();
clTcpSockMutexP.lock();
for(slSockIdxT = 0; slSockIdxT < pclTcpSockListP->size(); slSockIdxT++)
{
pclSockT = pclTcpSockListP->at(slSockIdxT);
if(pclSockT == pclSenderT)
{
pclTcpSockListP->remove(slSockIdxT);
break;
}
}
clTcpSockMutexP.unlock();
qDebug() << "QCanNetwork::onSocketDisconnect()" << pclTcpSockListP->size() << "open sockets";
}
//----------------------------------------------------------------------------//
// onTimerEvent() //
// remove local socket from list //
//----------------------------------------------------------------------------//
void QCanNetwork::onTimerEvent(void)
{
int32_t slSockIdxT;
int32_t slListSizeT;
uint32_t ulFrameCntT;
uint32_t ulFrameMaxT;
uint32_t ulMsgPerSecT;
QTcpSocket * pclSockT;
QCanFrame clCanFrameT;
QByteArray clSockDataT;
//----------------------------------------------------------------
// lock socket list
//
clTcpSockMutexP.lock();
//----------------------------------------------------------------
// check all open sockets and read messages
//
slListSizeT = pclTcpSockListP->size();
for(slSockIdxT = 0; slSockIdxT < slListSizeT; slSockIdxT++)
{
pclSockT = pclTcpSockListP->at(slSockIdxT);
ulFrameMaxT = (pclSockT->bytesAvailable()) / QCAN_FRAME_ARRAY_SIZE;
for(ulFrameCntT = 0; ulFrameCntT < ulFrameMaxT; ulFrameCntT++)
{
clSockDataT = pclSockT->read(QCAN_FRAME_ARRAY_SIZE);
clCanFrameT.fromByteArray(clSockDataT);
switch(clCanFrameT.frameType())
{
//---------------------------------------------
// handle API frames
//---------------------------------------------
case QCanFrame::eTYPE_QCAN_API:
handleApiFrame(slSockIdxT, (QCanFrameApi &) clCanFrameT);
break;
//---------------------------------------------
// handle error frames
//---------------------------------------------
case QCanFrame::eTYPE_QCAN_ERR:
handleErrFrame(slSockIdxT, (QCanFrameError &) clCanFrameT);
break;
//---------------------------------------------
// handle CAN frames
//---------------------------------------------
default:
//-------------------------------------
// check for active CAN interface
//
if(pclInterfaceP.isNull() == false)
{
pclInterfaceP->write(clCanFrameT);
}
//-------------------------------------
// write to other sockets
//
handleCanFrame(slSockIdxT, clSockDataT);
break;
}
}
}
clTcpSockMutexP.unlock();
//----------------------------------------------------------------
// signal current statistic values
//
if(ulStatisticTickP > 0)
{
ulStatisticTickP--;
}
else
{
//--------------------------------------------------------
// reload tick value
//
ulStatisticTickP = ulStatisticTimeP / ulDispatchTimeP;
//--------------------------------------------------------
// signal current counter values
//
showApiFrames(ulCntFrameApiP);
showCanFrames(ulCntFrameCanP);
showErrFrames(ulCntFrameErrP);
//--------------------------------------------------------
// calculate messages per second
//
ulMsgPerSecT = ulCntFrameCanP - ulFrameCntSaveP;
ulMsgPerSecT = ulMsgPerSecT * 4;
//--------------------------------------------------------
// todo: calculate bus load
//
//--------------------------------------------------------
// signal bus load and msg/sec
//
showLoad(0, ulMsgPerSecT);
//--------------------------------------------------------
// store actual frame counter value
//
ulFrameCntSaveP = ulCntFrameCanP;
}
clDispatchTmrP.singleShot(ulDispatchTimeP, this, SLOT(onTimerEvent()));
}
//----------------------------------------------------------------------------//
// removeInterface() //
// remove physical CAN interface (plugin) //
//----------------------------------------------------------------------------//
void QCanNetwork::removeInterface(void)
{
pclInterfaceP.clear();
}
<commit_msg>Add support for CAN interface (read & write)<commit_after>//============================================================================//
// File: qcan_network.cpp //
// Description: QCAN classes - CAN network //
// //
// Copyright (C) MicroControl GmbH & Co. KG //
// 53842 Troisdorf - Germany //
// www.microcontrol.net //
// //
//----------------------------------------------------------------------------//
// Redistribution and use in source and binary forms, with or without //
// modification, are permitted provided that the following conditions //
// are met: //
// 1. Redistributions of source code must retain the above copyright //
// notice, this list of conditions, the following disclaimer and //
// the referenced file 'COPYING'. //
// 2. Redistributions in binary form must reproduce the above copyright //
// notice, this list of conditions and the following disclaimer in the //
// documentation and/or other materials provided with the distribution. //
// 3. Neither the name of MicroControl nor the names of its contributors //
// may be used to endorse or promote products derived from this software //
// without specific prior written permission. //
// //
// Provided that this notice is retained in full, this software may be //
// distributed under the terms of the GNU Lesser General Public License //
// ("LGPL") version 3 as distributed in the 'COPYING' file. //
// //
//============================================================================//
/*----------------------------------------------------------------------------*\
** Include files **
** **
\*----------------------------------------------------------------------------*/
#include <QDebug>
#include "qcan_interface.hpp"
#include "qcan_network.hpp"
/*----------------------------------------------------------------------------*\
** Definitions **
** **
\*----------------------------------------------------------------------------*/
//-------------------------------------------------------------------
// The "socket number" of the physical CAN interface gets a high
// value in order to avoid conflicts with real sockets
//
#define QCAN_SOCKET_CAN_IF 22345
/*----------------------------------------------------------------------------*\
** Static variables **
** **
\*----------------------------------------------------------------------------*/
uint8_t QCanNetwork::ubNetIdP = 0;
/*----------------------------------------------------------------------------*\
** Class methods **
** **
\*----------------------------------------------------------------------------*/
//----------------------------------------------------------------------------//
// QCanNetwork() //
// constructor //
//----------------------------------------------------------------------------//
QCanNetwork::QCanNetwork(QObject * pclParentV,
uint16_t uwPortV)
{
//----------------------------------------------------------------
// set the parent
//
this->setParent(pclParentV);
//----------------------------------------------------------------
// each network has a unique network number, starting with 1
//
ubNetIdP++;
pclInterfaceP.clear();
//----------------------------------------------------------------
// set default network name
//
clNetNameP = "CAN " + QString("%1").arg(ubNetIdP);
//----------------------------------------------------------------
// create initial socket list
//
pclTcpSockListP = new QVector<QTcpSocket *>;
pclTcpSockListP->reserve(QCAN_TCP_SOCKET_MAX);
//----------------------------------------------------------------
// setup a new local server which is listening to the
// default network name
//
pclTcpSrvP = new QTcpServer();
clTcpHostAddrP = QHostAddress(QHostAddress::LocalHost);
uwTcpPortP = uwPortV;
//----------------------------------------------------------------
// clear statistic
//
ulCntFrameApiP = 0;
ulCntFrameCanP = 0;
ulCntFrameErrP = 0;
//----------------------------------------------------------------
// setup timing values
//
ulDispatchTimeP = 20;
ulStatisticTimeP = 250;
ulStatisticTickP = ulStatisticTimeP / ulDispatchTimeP;
//----------------------------------------------------------------
// setup default bit-rate
//
setBitrate(QCan::eCAN_BITRATE_500K, -1);
}
//----------------------------------------------------------------------------//
// ~QCanNetwork() //
// destructor //
//----------------------------------------------------------------------------//
QCanNetwork::~QCanNetwork()
{
//----------------------------------------------------------------
// close TCP server
//
if(pclTcpSrvP->isListening())
{
pclTcpSrvP->close();
}
delete(pclTcpSrvP);
ubNetIdP--;
}
//----------------------------------------------------------------------------//
// addInterface() //
// add physical CAN interface (plugin) //
//----------------------------------------------------------------------------//
bool QCanNetwork::addInterface(QCanInterface * pclCanIfV)
{
bool btResultT = false;
if(pclInterfaceP.isNull())
{
//--------------------------------------------------------
// connect the interface
//
if(pclCanIfV->connect() == QCanInterface::eERROR_OK)
{
if (pclCanIfV->setBitrate(slBitrateP, slBrsClockP) == QCanInterface::eERROR_OK)
{
if (pclCanIfV->setMode(QCanInterface::eMODE_START) == QCanInterface::eERROR_OK)
{
pclInterfaceP = pclCanIfV;
btResultT = true;
}
}
}
}
return (btResultT);
}
bool QCanNetwork::hasErrorFramesSupport(void)
{
return(false);
}
bool QCanNetwork::hasFastDataSupport(void)
{
return(false);
}
bool QCanNetwork::hasListenOnlySupport(void)
{
return(false);
}
//----------------------------------------------------------------------------//
// handleApiFrame() //
// //
//----------------------------------------------------------------------------//
bool QCanNetwork::handleApiFrame(int32_t & slSockSrcR,
QCanFrameApi & clApiFrameR)
{
bool btResultT = false;
switch(clApiFrameR.function())
{
case QCanFrameApi::eAPI_FUNC_NONE:
break;
case QCanFrameApi::eAPI_FUNC_BITRATE:
if(!pclInterfaceP.isNull())
{
pclInterfaceP->setBitrate( clApiFrameR.bitrate(),
clApiFrameR.brsClock());
}
btResultT = true;
break;
case QCanFrameApi::eAPI_FUNC_CAN_MODE:
break;
case QCanFrameApi::eAPI_FUNC_DRIVER_INIT:
break;
case QCanFrameApi::eAPI_FUNC_DRIVER_RELEASE:
break;
case QCanFrameApi::eAPI_FUNC_PROCESS_ID:
break;
default:
break;
}
ulCntFrameApiP++;
return(btResultT);
}
//----------------------------------------------------------------------------//
// handleCanFrame() //
// push QCan frame to all open sockets //
//----------------------------------------------------------------------------//
bool QCanNetwork::handleCanFrame(int32_t & slSockSrcR,
QByteArray & clSockDataR)
{
int32_t slSockIdxT;
bool btResultT = false;
QTcpSocket * pclSockS;
//----------------------------------------------------------------
// check all open sockets and write CAN frame
//
for(slSockIdxT = 0; slSockIdxT < pclTcpSockListP->size(); slSockIdxT++)
{
if(slSockIdxT != slSockSrcR)
{
pclSockS = pclTcpSockListP->at(slSockIdxT);
pclSockS->write(clSockDataR);
pclSockS->flush();
btResultT = true;
}
}
if(btResultT == true)
{
ulCntFrameCanP++;
}
return(btResultT);
}
//----------------------------------------------------------------------------//
// handleErrorFrame() //
// //
//----------------------------------------------------------------------------//
bool QCanNetwork::handleErrFrame(int32_t & slSockSrcR,
QCanFrameError & clErrorFrameR)
{
bool btResultT = false;
return(btResultT);
}
//----------------------------------------------------------------------------//
// onTcpSrvNewConnection() //
// slot that manages a new local server connection //
//----------------------------------------------------------------------------//
void QCanNetwork::onSocketConnect(void)
{
QTcpSocket * pclSocketT;
//----------------------------------------------------------------
// Get next pending connect and add this socket to the
// the socket list
//
pclSocketT = pclTcpSrvP->nextPendingConnection();
clTcpSockMutexP.lock();
pclTcpSockListP->append(pclSocketT);
clTcpSockMutexP.unlock();
qDebug() << "QCanNetwork::onSocketConnect()" << pclTcpSockListP->size() << "open sockets";
qDebug() << "Socket" << pclSocketT;
//----------------------------------------------------------------
// Add a slot that handles the disconnection of the socket
// from the local server
//
connect( pclSocketT,
SIGNAL(disconnected()),
this,
SLOT(onSocketDisconnect()) );
}
//----------------------------------------------------------------------------//
// setBitrate() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setBitrate(int32_t slBitrateV, int32_t slBrsClockV)
{
slBitrateP = slBitrateV;
slBrsClockP = slBrsClockV;
}
//----------------------------------------------------------------------------//
// setDispatcherTime() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setDispatcherTime(uint32_t ulTimeV)
{
ulDispatchTimeP = ulTimeV;
}
//----------------------------------------------------------------------------//
// setErrorFramesEnabled() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setErrorFramesEnabled(bool btEnableV)
{
if(hasErrorFramesSupport() == true)
{
btErrorFramesEnabledP = btEnableV;
}
else
{
btErrorFramesEnabledP = false;
}
}
//----------------------------------------------------------------------------//
// setFastDataEnabled() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setFastDataEnabled(bool btEnableV)
{
if(hasFastDataSupport() == true)
{
btFastDataEnabledP = btEnableV;
}
else
{
btFastDataEnabledP = false;
}
}
//----------------------------------------------------------------------------//
// setListenOnlyEnabled() //
// //
//----------------------------------------------------------------------------//
void QCanNetwork::setListenOnlyEnabled(bool btEnableV)
{
{btListenOnlyEnabledP = btEnableV;};
}
//----------------------------------------------------------------------------//
// setNetworkEnabled() //
// start / stop the TCP server //
//----------------------------------------------------------------------------//
void QCanNetwork::setNetworkEnabled(bool btEnableV)
{
if(btEnableV == true)
{
//--------------------------------------------------------
// limit the number of connections
//
pclTcpSrvP->setMaxPendingConnections(QCAN_TCP_SOCKET_MAX);
if(!pclTcpSrvP->listen(clTcpHostAddrP, uwTcpPortP))
{
qDebug() << "QCanNetwork(): can not listen to " << clNetNameP;
}
//--------------------------------------------------------
// a new connection is handled by the onTcpSrvNewConnection()
// method
//
connect( pclTcpSrvP, SIGNAL(newConnection()),
this, SLOT(onSocketConnect()));
//--------------------------------------------------------
// start network thread
//
clDispatchTmrP.singleShot(ulDispatchTimeP, this, SLOT(onTimerEvent()));
//--------------------------------------------------------
// set flag for further operations
//
btNetworkEnabledP = true;
}
else
{
//--------------------------------------------------------
// stop timer for message dispatching
//
clDispatchTmrP.stop();
//--------------------------------------------------------
// remove signal / slot connection
//
disconnect( pclTcpSrvP, SIGNAL(newConnection()),
this, SLOT(onSocketConnect()));
//--------------------------------------------------------
// close TCP server
//
qDebug() << "Close server";
pclTcpSrvP->close();
//--------------------------------------------------------
// set flag for further operations
//
btNetworkEnabledP = false;
}
}
//----------------------------------------------------------------------------//
// onSocketDisconnect() //
// remove local socket from list //
//----------------------------------------------------------------------------//
void QCanNetwork::onSocketDisconnect(void)
{
int32_t slSockIdxT;
QTcpSocket * pclSockT;
QTcpSocket * pclSenderT;
//----------------------------------------------------------------
// get sender of signal
//
pclSenderT = (QTcpSocket* ) QObject::sender();
clTcpSockMutexP.lock();
for(slSockIdxT = 0; slSockIdxT < pclTcpSockListP->size(); slSockIdxT++)
{
pclSockT = pclTcpSockListP->at(slSockIdxT);
if(pclSockT == pclSenderT)
{
pclTcpSockListP->remove(slSockIdxT);
break;
}
}
clTcpSockMutexP.unlock();
qDebug() << "QCanNetwork::onSocketDisconnect()" << pclTcpSockListP->size() << "open sockets";
}
//----------------------------------------------------------------------------//
// onTimerEvent() //
// remove local socket from list //
//----------------------------------------------------------------------------//
void QCanNetwork::onTimerEvent(void)
{
int32_t slSockIdxT;
int32_t slListSizeT;
uint32_t ulFrameCntT;
uint32_t ulFrameMaxT;
uint32_t ulMsgPerSecT;
QTcpSocket * pclSockT;
QCanFrame clCanFrameT;
QByteArray clSockDataT;
//----------------------------------------------------------------
// lock socket list
//
clTcpSockMutexP.lock();
//----------------------------------------------------------------
// read messages from active CAN interface
//
if(pclInterfaceP.isNull() == false)
{
slSockIdxT = QCAN_SOCKET_CAN_IF;
while(pclInterfaceP->read(clCanFrameT) == QCanInterface::eERROR_OK)
{
switch(clCanFrameT.frameType())
{
//---------------------------------------------
// handle API frames
//---------------------------------------------
case QCanFrame::eTYPE_QCAN_API:
handleApiFrame(slSockIdxT, (QCanFrameApi &) clCanFrameT);
break;
//---------------------------------------------
// handle error frames
//---------------------------------------------
case QCanFrame::eTYPE_QCAN_ERR:
handleErrFrame(slSockIdxT, (QCanFrameError &) clCanFrameT);
break;
//---------------------------------------------
// handle CAN frames
//---------------------------------------------
default:
//-------------------------------------
// write to other sockets
//
clSockDataT = clCanFrameT.toByteArray();
handleCanFrame(slSockIdxT, clSockDataT);
break;
}
}
}
//----------------------------------------------------------------
// check all open sockets and read messages
//
slListSizeT = pclTcpSockListP->size();
for(slSockIdxT = 0; slSockIdxT < slListSizeT; slSockIdxT++)
{
pclSockT = pclTcpSockListP->at(slSockIdxT);
ulFrameMaxT = (pclSockT->bytesAvailable()) / QCAN_FRAME_ARRAY_SIZE;
for(ulFrameCntT = 0; ulFrameCntT < ulFrameMaxT; ulFrameCntT++)
{
clSockDataT = pclSockT->read(QCAN_FRAME_ARRAY_SIZE);
clCanFrameT.fromByteArray(clSockDataT);
switch(clCanFrameT.frameType())
{
//---------------------------------------------
// handle API frames
//---------------------------------------------
case QCanFrame::eTYPE_QCAN_API:
handleApiFrame(slSockIdxT, (QCanFrameApi &) clCanFrameT);
break;
//---------------------------------------------
// handle error frames
//---------------------------------------------
case QCanFrame::eTYPE_QCAN_ERR:
handleErrFrame(slSockIdxT, (QCanFrameError &) clCanFrameT);
break;
//---------------------------------------------
// handle CAN frames
//---------------------------------------------
default:
//-------------------------------------
// check for active CAN interface
//
if(pclInterfaceP.isNull() == false)
{
pclInterfaceP->write(clCanFrameT);
}
//-------------------------------------
// write to other sockets
//
handleCanFrame(slSockIdxT, clSockDataT);
break;
}
}
}
clTcpSockMutexP.unlock();
//----------------------------------------------------------------
// signal current statistic values
//
if(ulStatisticTickP > 0)
{
ulStatisticTickP--;
}
else
{
//--------------------------------------------------------
// reload tick value
//
ulStatisticTickP = ulStatisticTimeP / ulDispatchTimeP;
//--------------------------------------------------------
// signal current counter values
//
showApiFrames(ulCntFrameApiP);
showCanFrames(ulCntFrameCanP);
showErrFrames(ulCntFrameErrP);
//--------------------------------------------------------
// calculate messages per second
//
ulMsgPerSecT = ulCntFrameCanP - ulFrameCntSaveP;
ulMsgPerSecT = ulMsgPerSecT * 4;
//--------------------------------------------------------
// todo: calculate bus load
//
//--------------------------------------------------------
// signal bus load and msg/sec
//
showLoad(0, ulMsgPerSecT);
//--------------------------------------------------------
// store actual frame counter value
//
ulFrameCntSaveP = ulCntFrameCanP;
}
clDispatchTmrP.singleShot(ulDispatchTimeP, this, SLOT(onTimerEvent()));
}
//----------------------------------------------------------------------------//
// removeInterface() //
// remove physical CAN interface (plugin) //
//----------------------------------------------------------------------------//
void QCanNetwork::removeInterface(void)
{
if(pclInterfaceP.isNull() == false)
{
pclInterfaceP->disconnect();
}
pclInterfaceP.clear();
}
<|endoftext|>
|
<commit_before><commit_msg>Update VideoDevice.hpp<commit_after>#ifndef VIDEO_DEVICE_H
#define VIDEO_DEVICE_H
#include <opencv2/opencv.hpp>
using namespace cv;
class VideoDevice
{
public:
VideoDevice();
void startCapture(int id);
Mat getImage();
private:
void takeImage();
//data
VideoCapture camera;
Mat image;
int isFinished;
int isReady;
bool isInitialized;
};
#endif
<|endoftext|>
|
<commit_before>#include <eosio/chain/checktime_timer_calibrate.hpp>
#include <eosio/chain/checktime_timer.hpp>
#include <fc/time.hpp>
#include <fc/log/logger.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/weighted_mean.hpp>
#include <boost/accumulators/statistics/weighted_variance.hpp>
#include <chrono>
namespace eosio { namespace chain {
namespace bacc = boost::accumulators;
checktime_timer_calibrate::checktime_timer_calibrate() = default;
checktime_timer_calibrate::~checktime_timer_calibrate() = default;
void checktime_timer_calibrate::do_calibrate(checktime_timer& timer) {
static std::mutex m;
static bool once_is_enough;
std::lock_guard guard(m);
if(once_is_enough)
return;
bacc::accumulator_set<int, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::variance>, float> samples;
//keep longest first in list. You're effectively going to take test_intervals[0]*sizeof(test_intervals[0])
//time to do the the "calibration"
int test_intervals[] = {50000, 10000, 5000, 1000, 500, 100, 50, 10};
for(int& interval : test_intervals) {
unsigned int loops = test_intervals[0]/interval;
for(unsigned int i = 0; i < loops; ++i) {
auto start = std::chrono::high_resolution_clock::now();
timer.start(fc::time_point(fc::time_point::now().time_since_epoch() + fc::microseconds(interval)));
while(!timer.expired) {}
auto end = std::chrono::high_resolution_clock::now();
int timer_slop = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count() - interval;
//since more samples are run for the shorter expirations, weigh the longer expirations accordingly. This
//helps to make a few results more fair. Two such examples: AWS c4&i5 xen instances being rather stable
//down to 100us but then struggling with 50us and 10us. MacOS having performance that seems to correlate
//with expiry length; that is, long expirations have high error, short expirations have low error.
//That said, for these platforms, a tighter tolerance may possibly be achieved by taking performance
//metrics in mulitple bins and appliying the slop based on which bin a deadline resides in. Not clear
//if that's worth the extra complexity at this point.
samples(timer_slop, bacc::weight = interval/(float)test_intervals[0]);
}
}
_timer_overhead = bacc::mean(samples) + sqrt(bacc::variance(samples))*2; //target 95% of expirations before deadline
_use_timer = _timer_overhead < 1000;
#define TIMER_STATS_FORMAT "min:${min}us max:${max}us mean:${mean}us stddev:${stddev}us"
#define TIMER_STATS \
("min", bacc::min(samples))("max", bacc::max(samples)) \
("mean", (int)bacc::mean(samples))("stddev", (int)sqrt(bacc::variance(samples))) \
("t", _timer_overhead)
if(_use_timer)
ilog("Using ${t}us deadline timer for checktime: " TIMER_STATS_FORMAT, TIMER_STATS);
else
wlog("Using polled checktime; deadline timer too inaccurate: " TIMER_STATS_FORMAT, TIMER_STATS);
once_is_enough = true;
}
}}<commit_msg>add mutex header needed for some platforms<commit_after>#include <eosio/chain/checktime_timer_calibrate.hpp>
#include <eosio/chain/checktime_timer.hpp>
#include <fc/time.hpp>
#include <fc/log/logger.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/weighted_mean.hpp>
#include <boost/accumulators/statistics/weighted_variance.hpp>
#include <chrono>
#include <mutex>
namespace eosio { namespace chain {
namespace bacc = boost::accumulators;
checktime_timer_calibrate::checktime_timer_calibrate() = default;
checktime_timer_calibrate::~checktime_timer_calibrate() = default;
void checktime_timer_calibrate::do_calibrate(checktime_timer& timer) {
static std::mutex m;
static bool once_is_enough;
std::lock_guard guard(m);
if(once_is_enough)
return;
bacc::accumulator_set<int, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::variance>, float> samples;
//keep longest first in list. You're effectively going to take test_intervals[0]*sizeof(test_intervals[0])
//time to do the the "calibration"
int test_intervals[] = {50000, 10000, 5000, 1000, 500, 100, 50, 10};
for(int& interval : test_intervals) {
unsigned int loops = test_intervals[0]/interval;
for(unsigned int i = 0; i < loops; ++i) {
auto start = std::chrono::high_resolution_clock::now();
timer.start(fc::time_point(fc::time_point::now().time_since_epoch() + fc::microseconds(interval)));
while(!timer.expired) {}
auto end = std::chrono::high_resolution_clock::now();
int timer_slop = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count() - interval;
//since more samples are run for the shorter expirations, weigh the longer expirations accordingly. This
//helps to make a few results more fair. Two such examples: AWS c4&i5 xen instances being rather stable
//down to 100us but then struggling with 50us and 10us. MacOS having performance that seems to correlate
//with expiry length; that is, long expirations have high error, short expirations have low error.
//That said, for these platforms, a tighter tolerance may possibly be achieved by taking performance
//metrics in mulitple bins and appliying the slop based on which bin a deadline resides in. Not clear
//if that's worth the extra complexity at this point.
samples(timer_slop, bacc::weight = interval/(float)test_intervals[0]);
}
}
_timer_overhead = bacc::mean(samples) + sqrt(bacc::variance(samples))*2; //target 95% of expirations before deadline
_use_timer = _timer_overhead < 1000;
#define TIMER_STATS_FORMAT "min:${min}us max:${max}us mean:${mean}us stddev:${stddev}us"
#define TIMER_STATS \
("min", bacc::min(samples))("max", bacc::max(samples)) \
("mean", (int)bacc::mean(samples))("stddev", (int)sqrt(bacc::variance(samples))) \
("t", _timer_overhead)
if(_use_timer)
ilog("Using ${t}us deadline timer for checktime: " TIMER_STATS_FORMAT, TIMER_STATS);
else
wlog("Using polled checktime; deadline timer too inaccurate: " TIMER_STATS_FORMAT, TIMER_STATS);
once_is_enough = true;
}
}}<|endoftext|>
|
<commit_before>#ifndef MOUSEMANAGER_HPP
#define MOUSEMANAGER_HPP
#include <map>
#include <string>
#include <functional>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Mouse.hpp>
namespace swift
{
class MouseManager
{
public:
MouseManager() {}
~MouseManager() {};
sf::Vector2i getPosition(sf::Window* win = nullptr)
{
if(win != nullptr)
return sf::Mouse::getPosition(*win);
return sf::Mouse::getPosition();
}
void newBinding(const std::string& n, sf::Mouse::Button b, std::function<void()> f = [](){return true;}, bool onPress = false)
{
bindings.emplace(std::make_pair(n, ButtonBinding(b, f, onPress)));
}
void call(const std::string& k)
{
bindings.at(k).call();
}
bool operator()(sf::Event& e)
{
for(auto &b : bindings)
{
if(b.second(e))
return b.second.call();
}
return false;
}
private:
class ButtonBinding
{
public:
explicit ButtonBinding(sf::Mouse::Button b, std::function<void()> f, bool p)
{
button = b;
onPress = p;
func = f;
}
~ButtonBinding()
{
}
sf::Mouse::Button getButton() const
{
return button;
}
bool operator()(sf::Event& e)
{
return ((e.type == sf::Event::MouseButtonPressed && onPress) || (e.type == sf::Event::MouseButtonReleased && !onPress)) && e.mouseButton.button == button;
}
bool call()
{
if(!func)
return false;
func();
return true;
}
private:
sf::Mouse::Button button;
std::function<void()> func;
bool onPress; // if true, means if key is pressed, if false, means if key is released
};
std::map<std::string, ButtonBinding> bindings;
};
}
#endif // MOUSEMANAGER_HPP
<commit_msg>Mouse functions now accept a vector for the mouse position<commit_after>#ifndef MOUSEMANAGER_HPP
#define MOUSEMANAGER_HPP
#include <map>
#include <string>
#include <functional>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Mouse.hpp>
namespace swift
{
class MouseManager
{
public:
MouseManager() {}
~MouseManager() {};
void newBinding(const std::string& n, sf::Mouse::Button b, std::function<void(const sf::Vector2i&)> f = [](const sf::Vector2i&){return true;}, bool onPress = false)
{
bindings.emplace(std::make_pair(n, ButtonBinding(b, f, onPress)));
}
void call(const std::string& k, const sf::Vector2i& pos)
{
bindings.at(k).call(pos);
}
bool operator()(sf::Event& e)
{
for(auto &b : bindings)
{
if(b.second(e))
return b.second.call({e.mouseButton.x, e.mouseButton.y});
}
return false;
}
private:
class ButtonBinding
{
public:
explicit ButtonBinding(sf::Mouse::Button b, std::function<void(const sf::Vector2i&)> f, bool p)
{
button = b;
onPress = p;
func = f;
}
~ButtonBinding()
{
}
sf::Mouse::Button getButton() const
{
return button;
}
bool operator()(sf::Event& e)
{
return ((e.type == sf::Event::MouseButtonPressed && onPress) || (e.type == sf::Event::MouseButtonReleased && !onPress)) && e.mouseButton.button == button;
}
bool call(sf::Vector2i pos)
{
if(!func)
return false;
func(pos);
return true;
}
private:
sf::Mouse::Button button;
std::function<void(const sf::Vector2i&)> func;
bool onPress; // if true, means if key is pressed, if false, means if key is released
};
std::map<std::string, ButtonBinding> bindings;
};
}
#endif // MOUSEMANAGER_HPP
<|endoftext|>
|
<commit_before>#include "SpritePool.h"
#include "SpriteFactory.h"
#include <sprite2/S2_Sprite.h>
#include <Sprite2/S2_Symbol.h>
namespace gum
{
SINGLETON_DEFINITION(SpritePool);
SpritePool::SpritePool()
{
}
void SpritePool::GC()
{
while (true)
{
bool dirty = false;
std::map<uint32_t, s2::Sprite*>::iterator itr = m_sym_id_cache.begin();
while (itr != m_sym_id_cache.end())
{
if (itr->second->GetRefCount() == 1) {
itr->second->RemoveReference();
m_sym_id_cache.erase(itr++);
dirty = true;
} else {
++itr;
}
}
if (!dirty) {
break;
}
}
}
s2::Sprite* SpritePool::Fetch(const uint32_t sym_id)
{
std::map<uint32_t, s2::Sprite*>::iterator itr = m_sym_id_cache.find(sym_id);
if (itr != m_sym_id_cache.end()) {
s2::Sprite* ret = itr->second;
ret->AddReference();
return ret;
} else {
return SpriteFactory::Instance()->CreateFromSym(sym_id, true);
}
}
void SpritePool::Return(s2::Sprite* spr)
{
int sym_id = spr->GetSymbol()->GetID();
std::map<uint32_t, s2::Sprite*>::iterator itr
= m_sym_id_cache.find(sym_id);
if (itr == m_sym_id_cache.end()) {
spr->AddReference();
m_sym_id_cache.insert(std::make_pair(sym_id, spr));
}
}
}<commit_msg>fix include<commit_after>#include "SpritePool.h"
#include "SpriteFactory.h"
#include <sprite2/S2_Sprite.h>
#include <sprite2/S2_Symbol.h>
namespace gum
{
SINGLETON_DEFINITION(SpritePool);
SpritePool::SpritePool()
{
}
void SpritePool::GC()
{
while (true)
{
bool dirty = false;
std::map<uint32_t, s2::Sprite*>::iterator itr = m_sym_id_cache.begin();
while (itr != m_sym_id_cache.end())
{
if (itr->second->GetRefCount() == 1) {
itr->second->RemoveReference();
m_sym_id_cache.erase(itr++);
dirty = true;
} else {
++itr;
}
}
if (!dirty) {
break;
}
}
}
s2::Sprite* SpritePool::Fetch(const uint32_t sym_id)
{
std::map<uint32_t, s2::Sprite*>::iterator itr = m_sym_id_cache.find(sym_id);
if (itr != m_sym_id_cache.end()) {
s2::Sprite* ret = itr->second;
ret->AddReference();
return ret;
} else {
return SpriteFactory::Instance()->CreateFromSym(sym_id, true);
}
}
void SpritePool::Return(s2::Sprite* spr)
{
int sym_id = spr->GetSymbol()->GetID();
std::map<uint32_t, s2::Sprite*>::iterator itr
= m_sym_id_cache.find(sym_id);
if (itr == m_sym_id_cache.end()) {
spr->AddReference();
m_sym_id_cache.insert(std::make_pair(sym_id, spr));
}
}
}<|endoftext|>
|
<commit_before>#include "akt/shell.h"
#include "ch.h"
#include "hal.h"
#include "chprintf.h"
#include <cstring>
#include <cstdio>
using namespace akt;
Ring<ShellCommand> ShellCommand::commands __attribute__ ((init_priority(200)));
BaseSequentialStream *ShellCommand::tty = 0;
char ShellCommand::line[LINE_SIZE];
unsigned int ShellCommand::line_length;
char *ShellCommand::argv[MAX_ARGS];
unsigned int ShellCommand::argc;
const char *ShellCommand::prompt = "> ";
ShellCommand::ShellCommand(const char *n) :
Ring(),
name(n)
{
join(commands);
}
ShellCommand *ShellCommand::find_command(const char *name) {
if (!strcmp(name, "?")) name = "help";
for (Iterator i=commands.begin(); i != commands.end(); ++i) {
const char *cmd_name = i->name;
if (!strcmp(name, cmd_name)) return i;
}
return 0;
}
void ShellCommand::read_line() {
chprintf(tty, prompt);
line_length = 0;
while (line_length < LINE_SIZE) {
char c = (char) chSequentialStreamGet(tty);
switch (c) {
case 0x04 : // ctrl-D
chprintf(tty, "^D");
line[line_length] = 0;
return;
case 0x7f : // delete
case 0x08 : // ctrl-H
if (line_length > 0) {
chSequentialStreamPut(tty, 0x08);
chSequentialStreamPut(tty, ' ');
chSequentialStreamPut(tty, 0x08);
line_length--;
}
break;
case 0x15 : // ctrl-U
chprintf(tty, "^U\r\n%s", prompt);
line[line_length=0] = 0;
break;
case '\r' :
chprintf(tty, "\r\n");
line[line_length] = 0;
return;
default :
if (c < ' ' || c >= 0x80) {
//chprintf(tty, "<0x%02x>", c);
continue;
}
if (line_length >= LINE_SIZE-1) continue;
chSequentialStreamPut(tty, c);
line[line_length++] = c;
}
}
}
void ShellCommand::parse_line() {
unsigned int i=0;
argc = 0;
while (i < line_length && argc < MAX_ARGS) {
// start argument word
argv[argc++] = &line[i];
while (i < line_length && line[i] != ' ') i++;
line[i++] = 0;
// skip whitespace
while (i < line_length && line[i] == ' ') i++;
}
}
msg_t ShellCommand::run_loop(void *) {
chThdSelf()->p_name = "shell";
while (tty != 0) {
read_line();
parse_line();
if (argc > 0) {
ShellCommand *cmd = find_command(argv[0]);
if (cmd) {
cmd->exec(argc, argv);
} else {
chprintf(tty, "%s ?\r\n", argv[0]);
}
}
}
return 0;
}
template<class T>
bool ShellCommand::parse_number(const char *str, T &out) {
unsigned int hex;
int dec;
if (sscanf(str, "0x%x", &hex)) {
out = hex;
return true;
}
if (sscanf(str, "%d", &dec)) {
out = dec;
return true;
}
return false;
}
template bool ShellCommand::parse_number(const char *str, uint16_t &out);
template bool ShellCommand::parse_number(const char *str, uint8_t &out);
template bool ShellCommand::parse_number(const char *str, int &out);
HelpCommand::HelpCommand() :
ShellCommand("help")
{
}
void HelpCommand::exec(int argc, char *argv[]) {
if (argc == 0) {
chprintf(tty, "help -- list available commands\r\n");
} else {
for (Iterator i=commands.begin(); i != commands.end(); ++i) i->exec(0, 0);
}
}
InfoCommand::InfoCommand() :
ShellCommand("info")
{
}
void InfoCommand::exec(int argc, char *argv[]) {
if (argc == 0) {
chprintf(tty, "info -- program/toolchain information\r\n");
} else {
chprintf(tty, "Kernel: %s\r\n", CH_KERNEL_VERSION);
#ifdef CH_COMPILER_NAME
chprintf(tty, "Compiler: %s\r\n", CH_COMPILER_NAME);
#endif
chprintf(tty, "Architecture: %s\r\n", CH_ARCHITECTURE_NAME);
#ifdef CH_CORE_VARIANT_NAME
chprintf(tty, "Core Variant: %s\r\n", CH_CORE_VARIANT_NAME);
#endif
#ifdef CH_PORT_INFO
chprintf(tty, "Port Info: %s\r\n", CH_PORT_INFO);
#endif
#ifdef PLATFORM_NAME
chprintf(tty, "Platform: %s\r\n", PLATFORM_NAME);
#endif
#ifdef BOARD_NAME
chprintf(tty, "Board: %s\r\n", BOARD_NAME);
#endif
#ifdef __DATE__
#ifdef __TIME__
chprintf(tty, "Build time: %s%s%s\r\n", __DATE__, " - ", __TIME__);
#endif
#endif
}
}
#if CH_USE_REGISTRY
extern "C" {
extern uint8_t __main_thread_stack_end__;
};
ThreadsCommand::ThreadsCommand() :
ShellCommand("threads")
{
}
void ThreadsCommand::exec(int argc, char *argv[]) {
static const char *states[] = {THD_STATE_NAMES};
if (argc == 0) {
chprintf(tty, "threads -- list ChibiOS threads\r\n");
} else {
chprintf(tty, "%8s %4s %4s %4s %9s %8s %s\r\n",
"addr", "stku", "prio", "refs", "state", "time", "name");
for (::Thread *t=chRegFirstThread(); t; t = chRegNextThread(t)) {
#if defined(CH_DBG_HAVE_STKTOP) && defined(CH_DBG_ENABLE_STACK_CHECK)
uint8_t *stack_top, *untouched;
if (t->p_stktop == 0) { // must be the main thread
stack_top = &__main_thread_stack_end__;
} else {
stack_top = ((uint8_t *) t->p_stktop) ;
}
untouched = (uint8_t *) t->p_stklimit;
while (*untouched == CH_STACK_FILL_VALUE && untouched < stack_top) ++untouched;
uint32_t stack_used = untouched - (uint8_t *) t->p_stklimit;
#else
uint32_t stack_used = 0;
#endif
chprintf(tty, "%.8lx %.4lx %4lu %4lu %9s %.8lu %s\r\n",
(uint32_t)t, (uint32_t) stack_used /*t->p_ctx.r13*/,
(uint32_t)t->p_prio, (uint32_t)(t->p_refs - 1),
states[t->p_state], (uint32_t)t->p_time,
chRegGetThreadName(t));
}
}
}
#endif
extern "C" char __init_array_start;
extern "C" char _etext;
extern "C" char __main_stack_base__;
extern "C" char _data;
extern "C" char _edata;
extern "C" char _bss_start;
extern "C" char _bss_end;
MemoryCommand::MemoryCommand() :
ShellCommand("memory")
{
}
void MemoryCommand::exec(int argc, char *argv[]) {
if (argc == 0) {
chprintf(tty, "memory -- display RAM/ROM info\r\n");
} else {
size_t n, size;
n = chHeapStatus(NULL, &size);
#define MEM(fmt,start,end) chprintf(tty, fmt, (start), (end), (1023 + ((end)-(start))) >> 10)
MEM(".text : %.8x - %.8x (%dK)\r\n", &__init_array_start, &_etext);
MEM(".data : %.8x - %.8x (%dK)\r\n", &_data, &_edata);
MEM(".bss : %.8x - %.8x (%dK)\r\n", &_bss_start, &_bss_end);
#undef MEM
chprintf(tty, "core free memory : %u bytes\r\n", chCoreStatus());
chprintf(tty, "heap fragments : %u\r\n", n);
chprintf(tty, "heap free total : %u bytes\r\n", size);
}
}
ResetCommand::ResetCommand() :
ShellCommand("reset")
{
}
void ResetCommand::exec(int argc, char *argv[]) {
if (argc == 0) {
chprintf(tty, "reset -- force hard reset\r\n");
} else {
// Ensure all outstanding memory accesses included
// buffered write are completed before reset
asm volatile ("dsb");
// Keep priority group unchanged
SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) |
(SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) |
SCB_AIRCR_SYSRESETREQ_Msk);
asm volatile ("dsb");
// wait until reset
while(1);
}
}
<commit_msg>print SYSCLK in shell info command<commit_after>#include "akt/shell.h"
#include "ch.h"
#include "hal.h"
#include "chprintf.h"
#include <cstring>
#include <cstdio>
using namespace akt;
Ring<ShellCommand> ShellCommand::commands __attribute__ ((init_priority(200)));
BaseSequentialStream *ShellCommand::tty = 0;
char ShellCommand::line[LINE_SIZE];
unsigned int ShellCommand::line_length;
char *ShellCommand::argv[MAX_ARGS];
unsigned int ShellCommand::argc;
const char *ShellCommand::prompt = "> ";
ShellCommand::ShellCommand(const char *n) :
Ring(),
name(n)
{
join(commands);
}
ShellCommand *ShellCommand::find_command(const char *name) {
if (!strcmp(name, "?")) name = "help";
for (Iterator i=commands.begin(); i != commands.end(); ++i) {
const char *cmd_name = i->name;
if (!strcmp(name, cmd_name)) return i;
}
return 0;
}
void ShellCommand::read_line() {
chprintf(tty, prompt);
line_length = 0;
while (line_length < LINE_SIZE) {
char c = (char) chSequentialStreamGet(tty);
switch (c) {
case 0x04 : // ctrl-D
chprintf(tty, "^D");
line[line_length] = 0;
return;
case 0x7f : // delete
case 0x08 : // ctrl-H
if (line_length > 0) {
chSequentialStreamPut(tty, 0x08);
chSequentialStreamPut(tty, ' ');
chSequentialStreamPut(tty, 0x08);
line_length--;
}
break;
case 0x15 : // ctrl-U
chprintf(tty, "^U\r\n%s", prompt);
line[line_length=0] = 0;
break;
case '\r' :
chprintf(tty, "\r\n");
line[line_length] = 0;
return;
default :
if (c < ' ' || c >= 0x80) {
//chprintf(tty, "<0x%02x>", c);
continue;
}
if (line_length >= LINE_SIZE-1) continue;
chSequentialStreamPut(tty, c);
line[line_length++] = c;
}
}
}
void ShellCommand::parse_line() {
unsigned int i=0;
argc = 0;
while (i < line_length && argc < MAX_ARGS) {
// start argument word
argv[argc++] = &line[i];
while (i < line_length && line[i] != ' ') i++;
line[i++] = 0;
// skip whitespace
while (i < line_length && line[i] == ' ') i++;
}
}
msg_t ShellCommand::run_loop(void *) {
chThdSelf()->p_name = "shell";
while (tty != 0) {
read_line();
parse_line();
if (argc > 0) {
ShellCommand *cmd = find_command(argv[0]);
if (cmd) {
cmd->exec(argc, argv);
} else {
chprintf(tty, "%s ?\r\n", argv[0]);
}
}
}
return 0;
}
template<class T>
bool ShellCommand::parse_number(const char *str, T &out) {
unsigned int hex;
int dec;
if (sscanf(str, "0x%x", &hex)) {
out = hex;
return true;
}
if (sscanf(str, "%d", &dec)) {
out = dec;
return true;
}
return false;
}
template bool ShellCommand::parse_number(const char *str, uint16_t &out);
template bool ShellCommand::parse_number(const char *str, uint8_t &out);
template bool ShellCommand::parse_number(const char *str, int &out);
HelpCommand::HelpCommand() :
ShellCommand("help")
{
}
void HelpCommand::exec(int argc, char *argv[]) {
if (argc == 0) {
chprintf(tty, "help -- list available commands\r\n");
} else {
for (Iterator i=commands.begin(); i != commands.end(); ++i) i->exec(0, 0);
}
}
InfoCommand::InfoCommand() :
ShellCommand("info")
{
}
void InfoCommand::exec(int argc, char *argv[]) {
if (argc == 0) {
chprintf(tty, "info -- program/toolchain information\r\n");
} else {
chprintf(tty, "Kernel: %s\r\n", CH_KERNEL_VERSION);
#ifdef CH_COMPILER_NAME
chprintf(tty, "Compiler: %s\r\n", CH_COMPILER_NAME);
#endif
chprintf(tty, "Architecture: %s\r\n", CH_ARCHITECTURE_NAME);
#ifdef CH_CORE_VARIANT_NAME
chprintf(tty, "Core Variant: %s\r\n", CH_CORE_VARIANT_NAME);
#endif
#ifdef CH_PORT_INFO
chprintf(tty, "Port Info: %s\r\n", CH_PORT_INFO);
#endif
#ifdef PLATFORM_NAME
chprintf(tty, "Platform: %s\r\n", PLATFORM_NAME);
#endif
#ifdef BOARD_NAME
chprintf(tty, "Board: %s\r\n", BOARD_NAME);
#endif
#ifdef __DATE__
#ifdef __TIME__
chprintf(tty, "Build time: %s%s%s\r\n", __DATE__, " - ", __TIME__);
#endif
#endif
chprintf (tty, "System Clock: %d.%03dMHz\r\n",
STM32_SYSCLK/1000000,
(STM32_SYSCLK%1000000)/1000);
}
}
#if CH_USE_REGISTRY
extern "C" {
extern uint8_t __main_thread_stack_end__;
};
ThreadsCommand::ThreadsCommand() :
ShellCommand("threads")
{
}
void ThreadsCommand::exec(int argc, char *argv[]) {
static const char *states[] = {THD_STATE_NAMES};
if (argc == 0) {
chprintf(tty, "threads -- list ChibiOS threads\r\n");
} else {
chprintf(tty, "%8s %4s %4s %4s %9s %8s %s\r\n",
"addr", "stku", "prio", "refs", "state", "time", "name");
for (::Thread *t=chRegFirstThread(); t; t = chRegNextThread(t)) {
#if defined(CH_DBG_HAVE_STKTOP) && defined(CH_DBG_ENABLE_STACK_CHECK)
uint8_t *stack_top, *untouched;
if (t->p_stktop == 0) { // must be the main thread
stack_top = &__main_thread_stack_end__;
} else {
stack_top = ((uint8_t *) t->p_stktop) ;
}
untouched = (uint8_t *) t->p_stklimit;
while (*untouched == CH_STACK_FILL_VALUE && untouched < stack_top) ++untouched;
uint32_t stack_used = untouched - (uint8_t *) t->p_stklimit;
#else
uint32_t stack_used = 0;
#endif
chprintf(tty, "%.8lx %.4lx %4lu %4lu %9s %.8lu %s\r\n",
(uint32_t)t, (uint32_t) stack_used /*t->p_ctx.r13*/,
(uint32_t)t->p_prio, (uint32_t)(t->p_refs - 1),
states[t->p_state], (uint32_t)t->p_time,
chRegGetThreadName(t));
}
}
}
#endif
extern "C" char __init_array_start;
extern "C" char _etext;
extern "C" char __main_stack_base__;
extern "C" char _data;
extern "C" char _edata;
extern "C" char _bss_start;
extern "C" char _bss_end;
MemoryCommand::MemoryCommand() :
ShellCommand("memory")
{
}
void MemoryCommand::exec(int argc, char *argv[]) {
if (argc == 0) {
chprintf(tty, "memory -- display RAM/ROM info\r\n");
} else {
size_t n, size;
n = chHeapStatus(NULL, &size);
#define MEM(fmt,start,end) chprintf(tty, fmt, (start), (end), (1023 + ((end)-(start))) >> 10)
MEM(".text : %.8x - %.8x (%dK)\r\n", &__init_array_start, &_etext);
MEM(".data : %.8x - %.8x (%dK)\r\n", &_data, &_edata);
MEM(".bss : %.8x - %.8x (%dK)\r\n", &_bss_start, &_bss_end);
#undef MEM
chprintf(tty, "core free memory : %u bytes\r\n", chCoreStatus());
chprintf(tty, "heap fragments : %u\r\n", n);
chprintf(tty, "heap free total : %u bytes\r\n", size);
}
}
ResetCommand::ResetCommand() :
ShellCommand("reset")
{
}
void ResetCommand::exec(int argc, char *argv[]) {
if (argc == 0) {
chprintf(tty, "reset -- force hard reset\r\n");
} else {
// Ensure all outstanding memory accesses included
// buffered write are completed before reset
asm volatile ("dsb");
// Keep priority group unchanged
SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) |
(SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) |
SCB_AIRCR_SYSRESETREQ_Msk);
asm volatile ("dsb");
// wait until reset
while(1);
}
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_SKELETON_HPP
#define NAZARA_SKELETON_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Math/Box.hpp>
#include <Nazara/Utility/Joint.hpp>
#include <vector>
struct NzSkeletonImpl;
class NAZARA_API NzSkeleton
{
friend NzJoint;
public:
NzSkeleton() = default;
NzSkeleton(const NzSkeleton& skeleton);
~NzSkeleton();
bool Create(unsigned int jointCount);
void Destroy();
const NzBoxf& GetAABB() const;
NzJoint* GetJoint(const NzString& jointName);
NzJoint* GetJoint(unsigned int index);
const NzJoint* GetJoint(const NzString& jointName) const;
const NzJoint* GetJoint(unsigned int index) const;
NzJoint* GetJoints();
const NzJoint* GetJoints() const;
unsigned int GetJointCount() const;
int GetJointIndex(const NzString& jointName) const;
void Interpolate(const NzSkeleton& skeletonA, const NzSkeleton& skeletonB, float interpolation);
void Interpolate(const NzSkeleton& skeletonA, const NzSkeleton& skeletonB, float interpolation, unsigned int* indices, unsigned int indiceCount);
bool IsValid() const;
NzSkeleton& operator=(const NzSkeleton& skeleton);
private:
void InvalidateJointMap();
void UpdateJointMap() const;
NzSkeletonImpl* m_impl = nullptr;
};
#endif // NAZARA_SKELETON_HPP
<commit_msg>Commited forgotten file (from commit 11ebdd50c3df1e96d7d8cc5b885360675ca5c302 [formerly 39e74cabd80f85aadb4db40f558ffc699a580423])<commit_after>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_SKELETON_HPP
#define NAZARA_SKELETON_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Resource.hpp>
#include <Nazara/Math/Box.hpp>
#include <Nazara/Utility/Joint.hpp>
#include <vector>
struct NzSkeletonImpl;
class NAZARA_API NzSkeleton : public NzResource
{
friend NzJoint;
public:
NzSkeleton() = default;
NzSkeleton(const NzSkeleton& skeleton);
~NzSkeleton();
bool Create(unsigned int jointCount);
void Destroy();
const NzBoxf& GetAABB() const;
NzJoint* GetJoint(const NzString& jointName);
NzJoint* GetJoint(unsigned int index);
const NzJoint* GetJoint(const NzString& jointName) const;
const NzJoint* GetJoint(unsigned int index) const;
NzJoint* GetJoints();
const NzJoint* GetJoints() const;
unsigned int GetJointCount() const;
int GetJointIndex(const NzString& jointName) const;
void Interpolate(const NzSkeleton& skeletonA, const NzSkeleton& skeletonB, float interpolation);
void Interpolate(const NzSkeleton& skeletonA, const NzSkeleton& skeletonB, float interpolation, unsigned int* indices, unsigned int indiceCount);
bool IsValid() const;
NzSkeleton& operator=(const NzSkeleton& skeleton);
private:
void InvalidateJoints();
void InvalidateJointMap();
void UpdateJointMap() const;
NzSkeletonImpl* m_impl = nullptr;
};
#endif // NAZARA_SKELETON_HPP
<|endoftext|>
|
<commit_before>/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 1/12/2019, 9:05:30 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
typedef tuple<int, int> P;
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W;
string S[410];
bool visited[410][410];
int main()
{
cin >> H >> W;
for (auto i = 0; i < H; i++)
{
cin >> S[i];
}
fill(&visited[0][0], &visited[0][0] + 410 * 410, false);
ll ans = 0;
for (auto i = 0; i < H; i++)
{
for (auto j = 0; j < W; j++)
{
if (!visited[i][j])
{
stack<P> St;
St.push(P(i, j));
ll cnt[2] = {0, 0};
while (!St.empty())
{
int x = get<0>(St.top());
int y = get<1>(St.top());
St.pop();
if (!visited[x][y])
{
visited[x][y] = true;
cnt[S[x][y] == '#']++;
for (auto k = 0; k < 4; k++)
{
int nx = x + dx[k];
int ny = x + dy[k];
if (0 <= nx && nx < H && 0 <= ny && ny < W && !visited[nx][ny] && S[x][y] != S[nx][ny])
{
St.push(P(nx, ny));
}
}
}
}
// cerr << cnt[0] << " " << cnt[1] << endl;
ans += cnt[0] * cnt[1];
}
}
}
cout << ans << endl;
}<commit_msg>tried C.cpp to 'C'<commit_after>/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 1/12/2019, 9:05:30 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
typedef tuple<int, int> P;
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W;
string S[410];
bool visited[410][410];
int main()
{
cin >> H >> W;
for (auto i = 0; i < H; i++)
{
cin >> S[i];
}
fill(&visited[0][0], &visited[0][0] + 410 * 410, false);
ll ans = 0;
for (auto i = 0; i < H; i++)
{
for (auto j = 0; j < W; j++)
{
if (!visited[i][j])
{
stack<P> St;
St.push(P(i, j));
ll cnt[2] = {0, 0};
while (!St.empty())
{
int x = get<0>(St.top());
int y = get<1>(St.top());
St.pop();
if (!visited[x][y])
{
cerr << "(" << x << ", " << y << ")" << endl;
visited[x][y] = true;
cnt[S[x][y] == '#']++;
for (auto k = 0; k < 4; k++)
{
int nx = x + dx[k];
int ny = x + dy[k];
if (0 <= nx && nx < H && 0 <= ny && ny < W && !visited[nx][ny] && S[x][y] != S[nx][ny])
{
St.push(P(nx, ny));
}
}
}
}
cerr << cnt[0] << " " << cnt[1] << endl;
ans += cnt[0] * cnt[1];
}
}
}
cout << ans << endl;
}<|endoftext|>
|
<commit_before>/*!
\file file_lock.cpp
\brief File-lock synchronization primitive implementation
\author Ivan Shynkarenka
\date 01.09.2016
\copyright MIT License
*/
#include "threads/file_lock.h"
#include "errors/fatal.h"
#include "filesystem/exceptions.h"
#include "threads/thread.h"
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include <sys/file.h>
#include <fcntl.h>
#include <unistd.h>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#undef Yield
#endif
namespace CppCommon {
class FileLock::Impl
{
public:
Impl(const Path& path) : _path(path)
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
_file = open(_path.native().c_str(), O_CREAT | O_EXCL | O_RDWR, 0644);
if (_file < 0)
{
if (errno == EEXIST)
{
_file = open(_path.native().c_str(), O_CREAT | O_RDWR, 0644);
if (_file >= 0)
{
_owner = false;
return;
}
}
}
else
{
_owner = true;
return;
}
throwex FileSystemException("Cannot create or open file-lock! file").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
std::wstring wpath = _path.wstring();
// Retries in CreateFile, see http://support.microsoft.com/kb/316609
const int attempts = 5;
const int sleep = 250;
for (int attempt = 0; attempt < attempts; ++attempt)
{
_file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_NEW, FILE_ATTRIBUTE_HIDDEN, nullptr);
if (_file == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_SHARING_VIOLATION)
{
Sleep(sleep);
continue;
}
else
{
_file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_HIDDEN, nullptr);
if (_file == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_SHARING_VIOLATION)
{
Sleep(sleep);
continue;
}
else
break;
}
else
{
_owner = false;
return;
}
}
}
else
{
_owner = true;
return;
}
}
throwex FileSystemException("Cannot create or open file-lock file!").Attach(_path);
#endif
}
~Impl()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = close(_file);
if (result != 0)
fatality(FileSystemException("Cannot close the file-lock descriptor!").Attach(_path));
// Remove the file-lock file (owner only)
if (_owner)
{
result = unlink(_path.native().c_str());
if (result != 0)
fatality(FileSystemException("Cannot unlink the file-lock file!").Attach(_path));
}
#elif defined(_WIN32) || defined(_WIN64)
if (!CloseHandle(_file))
fatality(FileSystemException("Cannot close the file-lock handle!").Attach(_path));
// Remove the file-lock file (owner only)
if (_owner)
{
if (!DeleteFileW(_path.wstring().c_str()))
fatality(FileSystemException("Cannot delete the file-lock file!").Attach(_path));
}
#endif
}
const Path& path() const noexcept { return _path; }
bool TryLockRead()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_RDLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLK, &lock);
if (result == -1)
{
if (errno == EAGAIN)
return false;
else
throwex FileSystemException("Failed to try lock for read!").Attach(_path);
}
else
return true;
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_SH | LOCK_NB);
if (result != 0)
{
if (errno == EWOULDBLOCK)
return false;
else
throwex FileSystemException("Failed to try lock for read!").Attach(_path);
}
else
return true;
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
return LockFileEx(_file, LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) ? true : false;
#endif
}
bool TryLockWrite()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLK, &lock);
if (result == -1)
{
if (errno == EAGAIN)
return false;
else
throwex FileSystemException("Failed to try lock for write!").Attach(_path);
}
else
return true;
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_EX | LOCK_NB);
if (result != 0)
{
if (errno == EWOULDBLOCK)
return false;
else
throwex FileSystemException("Failed to try lock for write!").Attach(_path);
}
else
return true;
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
return LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) ? true : false;
#endif
}
void LockRead()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_RDLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLKW, &lock);
if (result == -1)
throwex FileSystemException("Failed to lock for read!").Attach(_path);
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_SH);
if (result != 0)
throwex FileSystemException("Failed to lock for read!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
if (!LockFileEx(_file, 0, 0, MAXDWORD, MAXDWORD, &overlapped))
throwex FileSystemException("Failed to lock for read!").Attach(_path);
#endif
}
void LockWrite()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLKW, &lock);
if (result == -1)
throwex FileSystemException("Failed to lock for write!").Attach(_path);
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_EX);
if (result != 0)
throwex FileSystemException("Failed to lock for write!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
if (!LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlapped))
throwex FileSystemException("Failed to lock for write!").Attach(_path);
#endif
}
void UnlockRead()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLK, &lock);
if (result != 0)
throwex FileSystemException("Failed to unlock the read lock!").Attach(_path);
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_UN);
if (result != 0)
throwex FileSystemException("Failed to unlock the read lock!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))
throwex FileSystemException("Failed to unlock the read lock!").Attach(_path);
#endif
}
void UnlockWrite()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLK, &lock);
if (result != 0)
throwex FileSystemException("Failed to unlock the write lock!").Attach(_path);
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_UN);
if (result != 0)
throwex FileSystemException("Failed to unlock the write lock!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))
throwex FileSystemException("Failed to unlock the write lock!").Attach(_path);
#endif
}
private:
Path _path;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int _file;
#elif defined(_WIN32) || defined(_WIN64)
HANDLE _file;
#endif
bool _owner;
};
FileLock::FileLock(const Path& path) : _pimpl(std::make_unique<Impl>(path))
{
}
FileLock::FileLock(FileLock&& lock) noexcept : _pimpl(std::move(lock._pimpl))
{
}
FileLock::~FileLock()
{
}
FileLock& FileLock::operator=(FileLock&& lock) noexcept
{
_pimpl = std::move(lock._pimpl);
return *this;
}
const Path& FileLock::path() const noexcept
{
return _pimpl->path();
}
bool FileLock::TryLockRead()
{
return _pimpl->TryLockRead();
}
bool FileLock::TryLockWrite()
{
return _pimpl->TryLockWrite();
}
bool FileLock::TryLockReadFor(const Timespan& timespan)
{
// Calculate a finish timestamp
Timestamp finish = NanoTimestamp() + timespan;
// Try to acquire read lock at least one time
if (TryLockRead())
return true;
else
{
// Try lock or yield for the given timespan
while (NanoTimestamp() < finish)
{
if (TryLockRead())
return true;
else
Thread::Yield();
}
// Failed to acquire read lock
return false;
}
}
bool FileLock::TryLockWriteFor(const Timespan& timespan)
{
// Calculate a finish timestamp
Timestamp finish = NanoTimestamp() + timespan;
// Try to acquire write lock at least one time
if (TryLockWrite())
return true;
else
{
// Try lock or yield for the given timespan
while (NanoTimestamp() < finish)
{
if (TryLockWrite())
return true;
else
Thread::Yield();
}
// Failed to acquire write lock
return false;
}
}
void FileLock::LockRead()
{
_pimpl->LockRead();
}
void FileLock::LockWrite()
{
_pimpl->LockWrite();
}
void FileLock::UnlockRead()
{
_pimpl->UnlockRead();
}
void FileLock::UnlockWrite()
{
_pimpl->UnlockWrite();
}
} // namespace CppCommon
<commit_msg>build<commit_after>/*!
\file file_lock.cpp
\brief File-lock synchronization primitive implementation
\author Ivan Shynkarenka
\date 01.09.2016
\copyright MIT License
*/
#include "threads/file_lock.h"
#include "errors/fatal.h"
#include "filesystem/exceptions.h"
#include "threads/thread.h"
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include <sys/file.h>
#include <fcntl.h>
#include <unistd.h>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#undef Yield
#endif
// In case we are on a system with glibc version earlier than 2.20
#ifndef F_OFD_GETLK
#define F_OFD_GETLK 36
#define F_OFD_SETLK 37
#define F_OFD_SETLKW 38
#endif
namespace CppCommon {
class FileLock::Impl
{
public:
Impl(const Path& path) : _path(path)
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
_file = open(_path.native().c_str(), O_CREAT | O_EXCL | O_RDWR, 0644);
if (_file < 0)
{
if (errno == EEXIST)
{
_file = open(_path.native().c_str(), O_CREAT | O_RDWR, 0644);
if (_file >= 0)
{
_owner = false;
return;
}
}
}
else
{
_owner = true;
return;
}
throwex FileSystemException("Cannot create or open file-lock! file").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
std::wstring wpath = _path.wstring();
// Retries in CreateFile, see http://support.microsoft.com/kb/316609
const int attempts = 5;
const int sleep = 250;
for (int attempt = 0; attempt < attempts; ++attempt)
{
_file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_NEW, FILE_ATTRIBUTE_HIDDEN, nullptr);
if (_file == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_SHARING_VIOLATION)
{
Sleep(sleep);
continue;
}
else
{
_file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_HIDDEN, nullptr);
if (_file == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_SHARING_VIOLATION)
{
Sleep(sleep);
continue;
}
else
break;
}
else
{
_owner = false;
return;
}
}
}
else
{
_owner = true;
return;
}
}
throwex FileSystemException("Cannot create or open file-lock file!").Attach(_path);
#endif
}
~Impl()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = close(_file);
if (result != 0)
fatality(FileSystemException("Cannot close the file-lock descriptor!").Attach(_path));
// Remove the file-lock file (owner only)
if (_owner)
{
result = unlink(_path.native().c_str());
if (result != 0)
fatality(FileSystemException("Cannot unlink the file-lock file!").Attach(_path));
}
#elif defined(_WIN32) || defined(_WIN64)
if (!CloseHandle(_file))
fatality(FileSystemException("Cannot close the file-lock handle!").Attach(_path));
// Remove the file-lock file (owner only)
if (_owner)
{
if (!DeleteFileW(_path.wstring().c_str()))
fatality(FileSystemException("Cannot delete the file-lock file!").Attach(_path));
}
#endif
}
const Path& path() const noexcept { return _path; }
bool TryLockRead()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_RDLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLK, &lock);
if (result == -1)
{
if (errno == EAGAIN)
return false;
else
throwex FileSystemException("Failed to try lock for read!").Attach(_path);
}
else
return true;
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_SH | LOCK_NB);
if (result != 0)
{
if (errno == EWOULDBLOCK)
return false;
else
throwex FileSystemException("Failed to try lock for read!").Attach(_path);
}
else
return true;
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
return LockFileEx(_file, LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) ? true : false;
#endif
}
bool TryLockWrite()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLK, &lock);
if (result == -1)
{
if (errno == EAGAIN)
return false;
else
throwex FileSystemException("Failed to try lock for write!").Attach(_path);
}
else
return true;
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_EX | LOCK_NB);
if (result != 0)
{
if (errno == EWOULDBLOCK)
return false;
else
throwex FileSystemException("Failed to try lock for write!").Attach(_path);
}
else
return true;
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
return LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) ? true : false;
#endif
}
void LockRead()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_RDLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLKW, &lock);
if (result == -1)
throwex FileSystemException("Failed to lock for read!").Attach(_path);
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_SH);
if (result != 0)
throwex FileSystemException("Failed to lock for read!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
if (!LockFileEx(_file, 0, 0, MAXDWORD, MAXDWORD, &overlapped))
throwex FileSystemException("Failed to lock for read!").Attach(_path);
#endif
}
void LockWrite()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLKW, &lock);
if (result == -1)
throwex FileSystemException("Failed to lock for write!").Attach(_path);
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_EX);
if (result != 0)
throwex FileSystemException("Failed to lock for write!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
if (!LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlapped))
throwex FileSystemException("Failed to lock for write!").Attach(_path);
#endif
}
void UnlockRead()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLK, &lock);
if (result != 0)
throwex FileSystemException("Failed to unlock the read lock!").Attach(_path);
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_UN);
if (result != 0)
throwex FileSystemException("Failed to unlock the read lock!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))
throwex FileSystemException("Failed to unlock the read lock!").Attach(_path);
#endif
}
void UnlockWrite()
{
#if defined(linux) || defined(__linux) || defined(__linux__) || defined(__APPLE__)
struct flock lock;
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_pid = 0;
int result = fcntl(_file, F_OFD_SETLK, &lock);
if (result != 0)
throwex FileSystemException("Failed to unlock the write lock!").Attach(_path);
#elif defined(unix) || defined(__unix) || defined(__unix__)
int result = flock(_file, LOCK_UN);
if (result != 0)
throwex FileSystemException("Failed to unlock the write lock!").Attach(_path);
#elif defined(_WIN32) || defined(_WIN64)
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))
throwex FileSystemException("Failed to unlock the write lock!").Attach(_path);
#endif
}
private:
Path _path;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int _file;
#elif defined(_WIN32) || defined(_WIN64)
HANDLE _file;
#endif
bool _owner;
};
FileLock::FileLock(const Path& path) : _pimpl(std::make_unique<Impl>(path))
{
}
FileLock::FileLock(FileLock&& lock) noexcept : _pimpl(std::move(lock._pimpl))
{
}
FileLock::~FileLock()
{
}
FileLock& FileLock::operator=(FileLock&& lock) noexcept
{
_pimpl = std::move(lock._pimpl);
return *this;
}
const Path& FileLock::path() const noexcept
{
return _pimpl->path();
}
bool FileLock::TryLockRead()
{
return _pimpl->TryLockRead();
}
bool FileLock::TryLockWrite()
{
return _pimpl->TryLockWrite();
}
bool FileLock::TryLockReadFor(const Timespan& timespan)
{
// Calculate a finish timestamp
Timestamp finish = NanoTimestamp() + timespan;
// Try to acquire read lock at least one time
if (TryLockRead())
return true;
else
{
// Try lock or yield for the given timespan
while (NanoTimestamp() < finish)
{
if (TryLockRead())
return true;
else
Thread::Yield();
}
// Failed to acquire read lock
return false;
}
}
bool FileLock::TryLockWriteFor(const Timespan& timespan)
{
// Calculate a finish timestamp
Timestamp finish = NanoTimestamp() + timespan;
// Try to acquire write lock at least one time
if (TryLockWrite())
return true;
else
{
// Try lock or yield for the given timespan
while (NanoTimestamp() < finish)
{
if (TryLockWrite())
return true;
else
Thread::Yield();
}
// Failed to acquire write lock
return false;
}
}
void FileLock::LockRead()
{
_pimpl->LockRead();
}
void FileLock::LockWrite()
{
_pimpl->LockWrite();
}
void FileLock::UnlockRead()
{
_pimpl->UnlockRead();
}
void FileLock::UnlockWrite()
{
_pimpl->UnlockWrite();
}
} // namespace CppCommon
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "MetaSema.h"
#include "Display.h"
#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Interpreter/Value.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "../lib/Interpreter/IncrementalParser.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Sema/Sema.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/SourceManager.h"
#include <cstdlib>
#include <iostream>
namespace cling {
MetaSema::MetaSema(Interpreter& interp, MetaProcessor& meta)
: m_Interpreter(interp), m_MetaProcessor(meta), m_IsQuitRequested(false) { }
MetaSema::ActionResult MetaSema::actOnLCommand(llvm::StringRef file) {
ActionResult result = actOnUCommand(file);
if (result != AR_Success)
return result;
// In case of libraries we get .L lib.so, which might automatically pull in
// decls (from header files). Thus we want to take the restore point before
// loading of the file and revert exclusively if needed.
const Transaction* unloadPoint = m_Interpreter.getLastTransaction();
// fprintf(stderr,"DEBUG: Load for %s unloadPoint is %p\n",file.str().c_str(),unloadPoint);
// TODO: extra checks. Eg if the path is readable, if the file exists...
std::string canFile = m_Interpreter.lookupFileOrLibrary(file);
if (canFile.empty())
canFile = file;
if (m_Interpreter.loadFile(canFile) == Interpreter::kSuccess) {
clang::SourceManager& SM = m_Interpreter.getSema().getSourceManager();
clang::FileManager& FM = SM.getFileManager();
const clang::FileEntry* Entry
= FM.getFile(canFile, /*OpenFile*/false, /*CacheFailure*/false);
if (Entry && !m_Watermarks[Entry]) { // register as a watermark
m_Watermarks[Entry] = unloadPoint;
m_ReverseWatermarks[unloadPoint] = Entry;
//fprintf(stderr,"DEBUG: Load for %s recorded unloadPoint %p\n",file.str().c_str(),unloadPoint);
}
return AR_Success;
}
return AR_Failure;
}
MetaSema::ActionResult MetaSema::actOnRedirectCommand(llvm::StringRef file,
MetaProcessor::RedirectionScope stream,
bool append) {
m_MetaProcessor.setStdStream(file, stream, append);
return AR_Success;
}
void MetaSema::actOnComment(llvm::StringRef comment) const {
// Some of the comments are meaningful for the cling::Interpreter
m_Interpreter.declare(comment);
}
MetaSema::ActionResult MetaSema::actOnxCommand(llvm::StringRef file,
llvm::StringRef args,
Value* result) {
MetaSema::ActionResult actionResult = actOnLCommand(file);
if (actionResult == AR_Success) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairPathFile = file.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
std::string expression = pairFuncExt.first.str() + "(" + args.str() + ")";
if (m_Interpreter.echo(expression, result) != Interpreter::kSuccess)
actionResult = AR_Failure;
}
return actionResult;
}
void MetaSema::actOnqCommand() {
m_IsQuitRequested = true;
}
MetaSema::ActionResult MetaSema::actOnUndoCommand(unsigned N/*=1*/) {
m_Interpreter.unload(N);
return AR_Success;
}
MetaSema::ActionResult MetaSema::actOnUCommand(llvm::StringRef file) {
// FIXME: unload, once implemented, must return success / failure
// Lookup the file
clang::SourceManager& SM = m_Interpreter.getSema().getSourceManager();
clang::FileManager& FM = SM.getFileManager();
//Get the canonical path, taking into account interp and system search paths
std::string canonicalFile = m_Interpreter.lookupFileOrLibrary(file);
const clang::FileEntry* Entry
= FM.getFile(canonicalFile, /*OpenFile*/false, /*CacheFailure*/false);
if (Entry) {
Watermarks::iterator Pos = m_Watermarks.find(Entry);
//fprintf(stderr,"DEBUG: unload request for %s\n",file.str().c_str());
if (Pos != m_Watermarks.end()) {
const Transaction* unloadPoint = Pos->second;
// Search for the transaction, i.e. verify that is has not already
// been unloaded ; This can be removed once all transaction unload
// properly information MetaSema that it has been unloaded.
bool found = false;
//for (auto t : m_Interpreter.m_IncrParser->getAllTransactions()) {
for(const Transaction *t = m_Interpreter.getFirstTransaction();
t != 0; t = t->getNext()) {
//fprintf(stderr,"DEBUG: On unload check For %s unloadPoint is %p are t == %p\n",file.str().c_str(),unloadPoint, t);
if (t == unloadPoint ) {
found = true;
break;
}
}
if (!found) {
m_MetaProcessor.getOuts() << "!!!ERROR: Transaction for file: " << file << " has already been unloaded\n";
} else {
//fprintf(stderr,"DEBUG: On Unload For %s unloadPoint is %p\n",file.str().c_str(),unloadPoint);
while(m_Interpreter.getLastTransaction() != unloadPoint) {
//fprintf(stderr,"DEBUG: unload transaction %p (searching for %p)\n",m_Interpreter.getLastTransaction(),unloadPoint);
const clang::FileEntry* EntryUnloaded
= m_ReverseWatermarks[m_Interpreter.getLastTransaction()];
if (EntryUnloaded) {
Watermarks::iterator PosUnloaded
= m_Watermarks.find(EntryUnloaded);
if (PosUnloaded != m_Watermarks.end()) {
m_Watermarks.erase(PosUnloaded);
}
}
m_Interpreter.unload(/*numberOfTransactions*/1);
}
}
DynamicLibraryManager* DLM = m_Interpreter.getDynamicLibraryManager();
if (DLM->isLibraryLoaded(canonicalFile))
DLM->unloadLibrary(canonicalFile);
m_Watermarks.erase(Pos);
}
}
return AR_Success;
}
void MetaSema::actOnICommand(llvm::StringRef path) const {
if (path.empty())
m_Interpreter.DumpIncludePath();
else
m_Interpreter.AddIncludePath(path.str());
}
void MetaSema::actOnrawInputCommand(SwitchMode mode/* = kToggle*/) const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isRawInputEnabled();
m_Interpreter.enableRawInput(flag);
// FIXME:
m_MetaProcessor.getOuts() << (flag ? "U" :"Not u") << "sing raw input\n";
}
else
m_Interpreter.enableRawInput(mode);
}
void MetaSema::actOnprintDebugCommand(SwitchMode mode/* = kToggle*/) const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isPrintingDebug();
m_Interpreter.enablePrintDebug(flag);
// FIXME:
m_MetaProcessor.getOuts() << (flag ? "P" : "Not p") << "rinting Debug\n";
}
else
m_Interpreter.enablePrintDebug(mode);
}
void MetaSema::actOnstoreStateCommand(llvm::StringRef name) const {
m_Interpreter.storeInterpreterState(name);
}
void MetaSema::actOncompareStateCommand(llvm::StringRef name) const {
m_Interpreter.compareInterpreterState(name);
}
void MetaSema::actOnstatsCommand(llvm::StringRef name) const {
if (name.equals("ast")) {
m_Interpreter.getCI()->getSema().getASTContext().PrintStats();
}
}
void MetaSema::actOndynamicExtensionsCommand(SwitchMode mode/* = kToggle*/)
const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isDynamicLookupEnabled();
m_Interpreter.enableDynamicLookup(flag);
// FIXME:
m_MetaProcessor.getOuts()
<< (flag ? "U" : "Not u") << "sing dynamic extensions\n";
}
else
m_Interpreter.enableDynamicLookup(mode);
}
void MetaSema::actOnhelpCommand() const {
std::string& metaString = m_Interpreter.getOptions().MetaString;
llvm::raw_ostream& outs = m_MetaProcessor.getOuts();
outs << "\nCling (C/C++ interpreter) meta commands usage\n"
"All commands must be preceded by a '" << metaString << "', except\n"
"for the evaluation statement { }\n"
"===============================================================================\n"
"Syntax: .Command [arg0 arg1 ... argN]\n"
"\n"
" " << metaString << "L <filename>\t\t- Load the given file or library\n"
" " << metaString << "(x|X) <filename>[args]\t- Same as .L and runs a "
"function with signature: ret_type filename(args)\n"
" " << metaString << "> <filename>\t\t- Redirect command to a given file\n"
"\t\t\t\t using '>' or '1>' redirects the stdout stream only\n"
"\t\t\t\t using '2>' redirects the stderr stream only\n"
"\t\t\t\t using '&>' (or '2>&1') redirects both stdout and stderr\n"
"\t\t\t\t using '>>' appends to the given file\n"
" " << metaString << "undo [n]\t\t\t- Unloads the last 'n' inputs lines\n"
" " << metaString << "U <filename>\t\t- Unloads the given file\n"
" " << metaString << "I [path]\t\t\t- Shows the include path. If a path is "
"given - adds the path to the include paths\n"
" " << metaString << "O <level>\t\t\t- Sets the optimization level (0-3) "
"(not yet implemented)\n"
" " << metaString << "class <name>\t\t- Prints out class <name> in a "
"CINT-like style\n"
" " << metaString << "files \t\t\t- Prints out some CINT-like file "
"statistics\n"
" " << metaString << "fileEx \t\t\t- Prints out some file statistics\n"
" " << metaString << "g \t\t\t\t- Prints out information about global "
"variable 'name' - if no name is given, print them all\n"
" " << metaString << "@ \t\t\t\t- Cancels and ignores the multiline input\n"
" " << metaString << "rawInput [0|1]\t\t- Toggle wrapping and printing "
"the execution results of the input\n"
" " << metaString << "dynamicExtensions [0|1]\t- Toggles the use of the "
"dynamic scopes and the late binding\n"
" " << metaString << "printDebug [0|1]\t\t- Toggles the printing of "
"input's corresponding state changes\n"
" " << metaString << "storeState <filename>\t- Store the interpreter's "
"state to a given file\n"
" " << metaString << "compareState <filename>\t- Compare the interpreter's "
"state with the one saved in a given file\n"
" " << metaString << "stats [name]\t\t- Show stats for various internal data "
"structures (only 'ast' for the time being)\n"
" " << metaString << "help\t\t\t- Shows this information\n"
" " << metaString << "q\t\t\t\t- Exit the program\n";
}
void MetaSema::actOnfileExCommand() const {
const clang::SourceManager& SM = m_Interpreter.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
m_MetaProcessor.getOuts() << "\n***\n\n";
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
m_MetaProcessor.getOuts() << (*I).first->getName();
m_MetaProcessor.getOuts() << "\n";
}
/* Only available in clang's trunk:
clang::ASTReader* Reader = m_Interpreter.getCI()->getModuleManager();
const clang::serialization::ModuleManager& ModMan
= Reader->getModuleManager();
for (clang::serialization::ModuleManager::ModuleConstIterator I
= ModMan.begin(), E = ModMan.end(); I != E; ++I) {
typedef
std::vector<llvm::PointerIntPair<const clang::FileEntry*, 1, bool> >
InputFiles_t;
const InputFiles_t& InputFiles = (*I)->InputFilesLoaded;
for (InputFiles_t::const_iterator IFI = InputFiles.begin(),
IFE = InputFiles.end(); IFI != IFE; ++IFI) {
m_MetaProcessor.getOuts() << IFI->getPointer()->getName();
m_MetaProcessor.getOuts() << "\n";
}
}
*/
}
void MetaSema::actOnfilesCommand() const {
m_Interpreter.printIncludedFiles(m_MetaProcessor.getOuts());
}
void MetaSema::actOnclassCommand(llvm::StringRef className) const {
if (!className.empty())
DisplayClass(m_MetaProcessor.getOuts(),
&m_Interpreter, className.str().c_str(), true);
else
DisplayClasses(m_MetaProcessor.getOuts(), &m_Interpreter, false);
}
void MetaSema::actOnClassCommand() const {
DisplayClasses(m_MetaProcessor.getOuts(), &m_Interpreter, true);
}
void MetaSema::actOnNamespaceCommand() const {
DisplayNamespaces(m_MetaProcessor.getOuts(), &m_Interpreter);
}
void MetaSema::actOngCommand(llvm::StringRef varName) const {
if (varName.empty())
DisplayGlobals(m_MetaProcessor.getOuts(), &m_Interpreter);
else
DisplayGlobal(m_MetaProcessor.getOuts(),
&m_Interpreter, varName.str().c_str());
}
void MetaSema::actOnTypedefCommand(llvm::StringRef typedefName) const {
if (typedefName.empty())
DisplayTypedefs(m_MetaProcessor.getOuts(), &m_Interpreter);
else
DisplayTypedef(m_MetaProcessor.getOuts(),
&m_Interpreter, typedefName.str().c_str());
}
MetaSema::ActionResult
MetaSema::actOnShellCommand(llvm::StringRef commandLine,
Value* result) const {
llvm::StringRef trimmed(commandLine.trim(" \t\n\v\f\r "));
if (!trimmed.empty()) {
int ret = std::system(trimmed.str().c_str());
// Build the result
clang::ASTContext& Ctx = m_Interpreter.getCI()->getASTContext();
if (result) {
*result = Value(Ctx.IntTy, m_Interpreter);
result->getAs<long long>() = ret;
}
return (ret == 0) ? AR_Success : AR_Failure;
}
if (result)
*result = Value();
// nothing to run - should this be success or failure?
return AR_Failure;
}
} // end namespace cling
<commit_msg>Another '.' to metaString replacement<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vvasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "MetaSema.h"
#include "Display.h"
#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Interpreter/Value.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "../lib/Interpreter/IncrementalParser.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Sema/Sema.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/SourceManager.h"
#include <cstdlib>
#include <iostream>
namespace cling {
MetaSema::MetaSema(Interpreter& interp, MetaProcessor& meta)
: m_Interpreter(interp), m_MetaProcessor(meta), m_IsQuitRequested(false) { }
MetaSema::ActionResult MetaSema::actOnLCommand(llvm::StringRef file) {
ActionResult result = actOnUCommand(file);
if (result != AR_Success)
return result;
// In case of libraries we get .L lib.so, which might automatically pull in
// decls (from header files). Thus we want to take the restore point before
// loading of the file and revert exclusively if needed.
const Transaction* unloadPoint = m_Interpreter.getLastTransaction();
// fprintf(stderr,"DEBUG: Load for %s unloadPoint is %p\n",file.str().c_str(),unloadPoint);
// TODO: extra checks. Eg if the path is readable, if the file exists...
std::string canFile = m_Interpreter.lookupFileOrLibrary(file);
if (canFile.empty())
canFile = file;
if (m_Interpreter.loadFile(canFile) == Interpreter::kSuccess) {
clang::SourceManager& SM = m_Interpreter.getSema().getSourceManager();
clang::FileManager& FM = SM.getFileManager();
const clang::FileEntry* Entry
= FM.getFile(canFile, /*OpenFile*/false, /*CacheFailure*/false);
if (Entry && !m_Watermarks[Entry]) { // register as a watermark
m_Watermarks[Entry] = unloadPoint;
m_ReverseWatermarks[unloadPoint] = Entry;
//fprintf(stderr,"DEBUG: Load for %s recorded unloadPoint %p\n",file.str().c_str(),unloadPoint);
}
return AR_Success;
}
return AR_Failure;
}
MetaSema::ActionResult MetaSema::actOnRedirectCommand(llvm::StringRef file,
MetaProcessor::RedirectionScope stream,
bool append) {
m_MetaProcessor.setStdStream(file, stream, append);
return AR_Success;
}
void MetaSema::actOnComment(llvm::StringRef comment) const {
// Some of the comments are meaningful for the cling::Interpreter
m_Interpreter.declare(comment);
}
MetaSema::ActionResult MetaSema::actOnxCommand(llvm::StringRef file,
llvm::StringRef args,
Value* result) {
MetaSema::ActionResult actionResult = actOnLCommand(file);
if (actionResult == AR_Success) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairPathFile = file.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
std::string expression = pairFuncExt.first.str() + "(" + args.str() + ")";
if (m_Interpreter.echo(expression, result) != Interpreter::kSuccess)
actionResult = AR_Failure;
}
return actionResult;
}
void MetaSema::actOnqCommand() {
m_IsQuitRequested = true;
}
MetaSema::ActionResult MetaSema::actOnUndoCommand(unsigned N/*=1*/) {
m_Interpreter.unload(N);
return AR_Success;
}
MetaSema::ActionResult MetaSema::actOnUCommand(llvm::StringRef file) {
// FIXME: unload, once implemented, must return success / failure
// Lookup the file
clang::SourceManager& SM = m_Interpreter.getSema().getSourceManager();
clang::FileManager& FM = SM.getFileManager();
//Get the canonical path, taking into account interp and system search paths
std::string canonicalFile = m_Interpreter.lookupFileOrLibrary(file);
const clang::FileEntry* Entry
= FM.getFile(canonicalFile, /*OpenFile*/false, /*CacheFailure*/false);
if (Entry) {
Watermarks::iterator Pos = m_Watermarks.find(Entry);
//fprintf(stderr,"DEBUG: unload request for %s\n",file.str().c_str());
if (Pos != m_Watermarks.end()) {
const Transaction* unloadPoint = Pos->second;
// Search for the transaction, i.e. verify that is has not already
// been unloaded ; This can be removed once all transaction unload
// properly information MetaSema that it has been unloaded.
bool found = false;
//for (auto t : m_Interpreter.m_IncrParser->getAllTransactions()) {
for(const Transaction *t = m_Interpreter.getFirstTransaction();
t != 0; t = t->getNext()) {
//fprintf(stderr,"DEBUG: On unload check For %s unloadPoint is %p are t == %p\n",file.str().c_str(),unloadPoint, t);
if (t == unloadPoint ) {
found = true;
break;
}
}
if (!found) {
m_MetaProcessor.getOuts() << "!!!ERROR: Transaction for file: " << file << " has already been unloaded\n";
} else {
//fprintf(stderr,"DEBUG: On Unload For %s unloadPoint is %p\n",file.str().c_str(),unloadPoint);
while(m_Interpreter.getLastTransaction() != unloadPoint) {
//fprintf(stderr,"DEBUG: unload transaction %p (searching for %p)\n",m_Interpreter.getLastTransaction(),unloadPoint);
const clang::FileEntry* EntryUnloaded
= m_ReverseWatermarks[m_Interpreter.getLastTransaction()];
if (EntryUnloaded) {
Watermarks::iterator PosUnloaded
= m_Watermarks.find(EntryUnloaded);
if (PosUnloaded != m_Watermarks.end()) {
m_Watermarks.erase(PosUnloaded);
}
}
m_Interpreter.unload(/*numberOfTransactions*/1);
}
}
DynamicLibraryManager* DLM = m_Interpreter.getDynamicLibraryManager();
if (DLM->isLibraryLoaded(canonicalFile))
DLM->unloadLibrary(canonicalFile);
m_Watermarks.erase(Pos);
}
}
return AR_Success;
}
void MetaSema::actOnICommand(llvm::StringRef path) const {
if (path.empty())
m_Interpreter.DumpIncludePath();
else
m_Interpreter.AddIncludePath(path.str());
}
void MetaSema::actOnrawInputCommand(SwitchMode mode/* = kToggle*/) const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isRawInputEnabled();
m_Interpreter.enableRawInput(flag);
// FIXME:
m_MetaProcessor.getOuts() << (flag ? "U" :"Not u") << "sing raw input\n";
}
else
m_Interpreter.enableRawInput(mode);
}
void MetaSema::actOnprintDebugCommand(SwitchMode mode/* = kToggle*/) const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isPrintingDebug();
m_Interpreter.enablePrintDebug(flag);
// FIXME:
m_MetaProcessor.getOuts() << (flag ? "P" : "Not p") << "rinting Debug\n";
}
else
m_Interpreter.enablePrintDebug(mode);
}
void MetaSema::actOnstoreStateCommand(llvm::StringRef name) const {
m_Interpreter.storeInterpreterState(name);
}
void MetaSema::actOncompareStateCommand(llvm::StringRef name) const {
m_Interpreter.compareInterpreterState(name);
}
void MetaSema::actOnstatsCommand(llvm::StringRef name) const {
if (name.equals("ast")) {
m_Interpreter.getCI()->getSema().getASTContext().PrintStats();
}
}
void MetaSema::actOndynamicExtensionsCommand(SwitchMode mode/* = kToggle*/)
const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isDynamicLookupEnabled();
m_Interpreter.enableDynamicLookup(flag);
// FIXME:
m_MetaProcessor.getOuts()
<< (flag ? "U" : "Not u") << "sing dynamic extensions\n";
}
else
m_Interpreter.enableDynamicLookup(mode);
}
void MetaSema::actOnhelpCommand() const {
std::string& metaString = m_Interpreter.getOptions().MetaString;
llvm::raw_ostream& outs = m_MetaProcessor.getOuts();
outs << "\nCling (C/C++ interpreter) meta commands usage\n"
"All commands must be preceded by a '" << metaString << "', except\n"
"for the evaluation statement { }\n"
"===============================================================================\n"
"Syntax: " << metaString << "Command [arg0 arg1 ... argN]\n"
"\n"
" " << metaString << "L <filename>\t\t- Load the given file or library\n"
" " << metaString << "(x|X) <filename>[args]\t- Same as .L and runs a "
"function with signature: ret_type filename(args)\n"
" " << metaString << "> <filename>\t\t- Redirect command to a given file\n"
"\t\t\t\t using '>' or '1>' redirects the stdout stream only\n"
"\t\t\t\t using '2>' redirects the stderr stream only\n"
"\t\t\t\t using '&>' (or '2>&1') redirects both stdout and stderr\n"
"\t\t\t\t using '>>' appends to the given file\n"
" " << metaString << "undo [n]\t\t\t- Unloads the last 'n' inputs lines\n"
" " << metaString << "U <filename>\t\t- Unloads the given file\n"
" " << metaString << "I [path]\t\t\t- Shows the include path. If a path is "
"given - adds the path to the include paths\n"
" " << metaString << "O <level>\t\t\t- Sets the optimization level (0-3) "
"(not yet implemented)\n"
" " << metaString << "class <name>\t\t- Prints out class <name> in a "
"CINT-like style\n"
" " << metaString << "files \t\t\t- Prints out some CINT-like file "
"statistics\n"
" " << metaString << "fileEx \t\t\t- Prints out some file statistics\n"
" " << metaString << "g \t\t\t\t- Prints out information about global "
"variable 'name' - if no name is given, print them all\n"
" " << metaString << "@ \t\t\t\t- Cancels and ignores the multiline input\n"
" " << metaString << "rawInput [0|1]\t\t- Toggle wrapping and printing "
"the execution results of the input\n"
" " << metaString << "dynamicExtensions [0|1]\t- Toggles the use of the "
"dynamic scopes and the late binding\n"
" " << metaString << "printDebug [0|1]\t\t- Toggles the printing of "
"input's corresponding state changes\n"
" " << metaString << "storeState <filename>\t- Store the interpreter's "
"state to a given file\n"
" " << metaString << "compareState <filename>\t- Compare the interpreter's "
"state with the one saved in a given file\n"
" " << metaString << "stats [name]\t\t- Show stats for various internal data "
"structures (only 'ast' for the time being)\n"
" " << metaString << "help\t\t\t- Shows this information\n"
" " << metaString << "q\t\t\t\t- Exit the program\n";
}
void MetaSema::actOnfileExCommand() const {
const clang::SourceManager& SM = m_Interpreter.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
m_MetaProcessor.getOuts() << "\n***\n\n";
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
m_MetaProcessor.getOuts() << (*I).first->getName();
m_MetaProcessor.getOuts() << "\n";
}
/* Only available in clang's trunk:
clang::ASTReader* Reader = m_Interpreter.getCI()->getModuleManager();
const clang::serialization::ModuleManager& ModMan
= Reader->getModuleManager();
for (clang::serialization::ModuleManager::ModuleConstIterator I
= ModMan.begin(), E = ModMan.end(); I != E; ++I) {
typedef
std::vector<llvm::PointerIntPair<const clang::FileEntry*, 1, bool> >
InputFiles_t;
const InputFiles_t& InputFiles = (*I)->InputFilesLoaded;
for (InputFiles_t::const_iterator IFI = InputFiles.begin(),
IFE = InputFiles.end(); IFI != IFE; ++IFI) {
m_MetaProcessor.getOuts() << IFI->getPointer()->getName();
m_MetaProcessor.getOuts() << "\n";
}
}
*/
}
void MetaSema::actOnfilesCommand() const {
m_Interpreter.printIncludedFiles(m_MetaProcessor.getOuts());
}
void MetaSema::actOnclassCommand(llvm::StringRef className) const {
if (!className.empty())
DisplayClass(m_MetaProcessor.getOuts(),
&m_Interpreter, className.str().c_str(), true);
else
DisplayClasses(m_MetaProcessor.getOuts(), &m_Interpreter, false);
}
void MetaSema::actOnClassCommand() const {
DisplayClasses(m_MetaProcessor.getOuts(), &m_Interpreter, true);
}
void MetaSema::actOnNamespaceCommand() const {
DisplayNamespaces(m_MetaProcessor.getOuts(), &m_Interpreter);
}
void MetaSema::actOngCommand(llvm::StringRef varName) const {
if (varName.empty())
DisplayGlobals(m_MetaProcessor.getOuts(), &m_Interpreter);
else
DisplayGlobal(m_MetaProcessor.getOuts(),
&m_Interpreter, varName.str().c_str());
}
void MetaSema::actOnTypedefCommand(llvm::StringRef typedefName) const {
if (typedefName.empty())
DisplayTypedefs(m_MetaProcessor.getOuts(), &m_Interpreter);
else
DisplayTypedef(m_MetaProcessor.getOuts(),
&m_Interpreter, typedefName.str().c_str());
}
MetaSema::ActionResult
MetaSema::actOnShellCommand(llvm::StringRef commandLine,
Value* result) const {
llvm::StringRef trimmed(commandLine.trim(" \t\n\v\f\r "));
if (!trimmed.empty()) {
int ret = std::system(trimmed.str().c_str());
// Build the result
clang::ASTContext& Ctx = m_Interpreter.getCI()->getASTContext();
if (result) {
*result = Value(Ctx.IntTy, m_Interpreter);
result->getAs<long long>() = ret;
}
return (ret == 0) ? AR_Success : AR_Failure;
}
if (result)
*result = Value();
// nothing to run - should this be success or failure?
return AR_Failure;
}
} // end namespace cling
<|endoftext|>
|
<commit_before>#pragma once
#include <cilantro/kd_tree.hpp>
namespace cilantro {
template <typename ScalarT>
struct Correspondence {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Correspondence(size_t i, size_t j, ScalarT val) : indexInFirst(i), indexInSecond(j), value(val) {}
size_t indexInFirst;
size_t indexInSecond;
ScalarT value;
struct ValueLessComparator {
inline bool operator()(const Correspondence &c1, const Correspondence &c2) const {
return c1.value < c2.value;
}
};
struct ValueGreaterComparator {
inline bool operator()(const Correspondence &c1, const Correspondence &c2) const {
return c1.value > c2.value;
}
};
struct IndicesLexicographicalComparator {
inline bool operator()(const Correspondence &c1, const Correspondence &c2) const {
return std::tie(c1.indexInFirst, c1.indexInSecond) < std::tie(c2.indexInFirst, c2.indexInSecond);
}
};
};
template <typename ScalarT>
struct CorrespondenceDistanceEvaluator {
inline ScalarT operator()(size_t first_ind, size_t second_ind, ScalarT dist) const {
return dist;
}
};
template <typename ScalarT>
using CorrespondenceSet = std::vector<Correspondence<ScalarT>>;
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
void selectFirstSetCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first,
VectorSet<ScalarT,EigenDim> &first_corr)
{
first_corr.resize(first.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
first_corr.col(i) = first.col(correspondences[i].indexInFirst);
}
}
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
VectorSet<ScalarT,EigenDim> selectFirstSetCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first)
{
VectorSet<ScalarT,EigenDim> first_corr(first.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
first_corr.col(i) = first.col(correspondences[i].indexInFirst);
}
return first_corr;
}
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
void selectSecondSetCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second,
VectorSet<ScalarT,EigenDim> &second_corr)
{
second_corr.resize(second.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
second_corr.col(i) = second.col(correspondences[i].indexInSecond);
}
}
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
VectorSet<ScalarT,EigenDim> selectSecondSetCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second)
{
VectorSet<ScalarT,EigenDim> second_corr(second.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
second_corr.col(i) = second.col(correspondences[i].indexInSecond);
}
return second_corr;
}
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
void selectCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second,
VectorSet<ScalarT,EigenDim> &first_corr,
VectorSet<ScalarT,EigenDim> &second_corr)
{
first_corr.resize(first.rows(), correspondences.size());
second_corr.resize(second.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
first_corr.col(i) = first.col(correspondences[i].indexInFirst);
second_corr.col(i) = second.col(correspondences[i].indexInSecond);
}
}
template <typename ScalarT, class ComparatorT = typename Correspondence<ScalarT>::ValueLessComparator>
void filterCorrespondencesFraction(CorrespondenceSet<ScalarT> &correspondences, double fraction_to_keep) {
if (fraction_to_keep > 0.0 && fraction_to_keep < 1.0) {
std::sort(correspondences.begin(), correspondences.end(), ComparatorT());
correspondences.erase(correspondences.begin() + std::llround(fraction_to_keep*correspondences.size()), correspondences.end());
}
}
template <typename ScalarT, class ComparatorT = typename Correspondence<ScalarT>::ValueLessComparator>
inline CorrespondenceSet<ScalarT> filterCorrespondencesFraction(const CorrespondenceSet<ScalarT> &correspondences, double fraction_to_keep) {
CorrespondenceSet<ScalarT> corr_res(correspondences);
filterCorrespondencesFraction<ScalarT,ComparatorT>(corr_res, fraction_to_keep);
return corr_res;
}
template <typename ScalarT, ptrdiff_t EigenDim, template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, class EvaluatorT = CorrespondenceDistanceEvaluator<ScalarT>, typename CorrValueT = decltype(std::declval<EvaluatorT>().operator()((size_t)0,(size_t)0,(ScalarT)0))>
void findNNCorrespondencesUnidirectional(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
const KDTree<ScalarT,EigenDim,DistAdaptor> &ref_tree,
bool ref_is_first,
CorrespondenceSet<CorrValueT> &correspondences,
CorrValueT max_distance,
const EvaluatorT &evaluator = EvaluatorT())
{
correspondences.clear();
correspondences.reserve(query_pts.cols());
NearestNeighborSearchResult<ScalarT> nn;
if (ref_is_first) {
#pragma omp parallel for shared (correspondences) private (nn)
for (size_t i = 0; i < query_pts.cols(); i++) {
ref_tree.nearestNeighborSearch(query_pts.col(i), nn);
if (nn.value < max_distance) {
#pragma omp critical
correspondences.emplace_back(nn.index, i, evaluator(nn.index, i, nn.value));
}
}
} else {
#pragma omp parallel for shared (correspondences) private (nn)
for (size_t i = 0; i < query_pts.cols(); i++) {
ref_tree.nearestNeighborSearch(query_pts.col(i), nn);
if (nn.value < max_distance) {
#pragma omp critical
correspondences.emplace_back(i, nn.index, evaluator(i, nn.index, nn.value));
}
}
}
}
template <typename ScalarT, ptrdiff_t EigenDim, template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, class EvaluatorT = CorrespondenceDistanceEvaluator<ScalarT>, typename CorrValueT = decltype(std::declval<EvaluatorT>().operator()((size_t)0,(size_t)0,(ScalarT)0))>
inline CorrespondenceSet<CorrValueT> findNNCorrespondencesUnidirectional(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
const KDTree<ScalarT,EigenDim,DistAdaptor> &ref_tree,
bool ref_is_first,
CorrValueT max_distance,
const EvaluatorT &evaluator = EvaluatorT())
{
CorrespondenceSet<CorrValueT> corr_set;
findNNCorrespondencesUnidirectional<ScalarT,EigenDim,DistAdaptor,EvaluatorT,CorrValueT>(query_pts, ref_tree, ref_is_first, corr_set, max_distance, evaluator);
return corr_set;
}
template <typename ScalarT, ptrdiff_t EigenDim, template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, class EvaluatorT = CorrespondenceDistanceEvaluator<ScalarT>, typename CorrValueT = decltype(std::declval<EvaluatorT>().operator()((size_t)0,(size_t)0,(ScalarT)0))>
void findNNCorrespondencesBidirectional(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first_points,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second_points,
const KDTree<ScalarT,EigenDim,DistAdaptor> &first_tree,
const KDTree<ScalarT,EigenDim,DistAdaptor> &second_tree,
CorrespondenceSet<CorrValueT> &correspondences,
CorrValueT max_distance,
bool require_reciprocal = false,
const EvaluatorT &evaluator = EvaluatorT())
{
CorrespondenceSet<CorrValueT> corr_first_to_second, corr_second_to_first;
findNNCorrespondencesUnidirectional<ScalarT,EigenDim,DistAdaptor,EvaluatorT,CorrValueT>(first_points, second_tree, false, corr_first_to_second, max_distance, evaluator);
findNNCorrespondencesUnidirectional<ScalarT,EigenDim,DistAdaptor,EvaluatorT,CorrValueT>(second_points, first_tree, true, corr_second_to_first, max_distance, evaluator);
typename Correspondence<CorrValueT>::IndicesLexicographicalComparator comparator;
std::sort(corr_first_to_second.begin(), corr_first_to_second.end(), comparator);
std::sort(corr_second_to_first.begin(), corr_second_to_first.end(), comparator);
correspondences.clear();
correspondences.reserve(corr_first_to_second.size()+corr_second_to_first.size());
if (require_reciprocal) {
std::set_intersection(corr_first_to_second.begin(), corr_first_to_second.end(),
corr_second_to_first.begin(), corr_second_to_first.end(),
std::back_inserter(correspondences), comparator);
} else {
std::set_union(corr_first_to_second.begin(), corr_first_to_second.end(),
corr_second_to_first.begin(), corr_second_to_first.end(),
std::back_inserter(correspondences), comparator);
}
}
template <typename ScalarT, ptrdiff_t EigenDim, template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, class EvaluatorT = CorrespondenceDistanceEvaluator<ScalarT>, typename CorrValueT = decltype(std::declval<EvaluatorT>().operator()((size_t)0,(size_t)0,(ScalarT)0))>
inline CorrespondenceSet<CorrValueT> findNNCorrespondencesBidirectional(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first_points,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second_points,
const KDTree<ScalarT,EigenDim,DistAdaptor> &first_tree,
const KDTree<ScalarT,EigenDim,DistAdaptor> &second_tree,
CorrValueT max_distance,
bool require_reciprocal = false,
const EvaluatorT &evaluator = EvaluatorT())
{
CorrespondenceSet<CorrValueT> corr_set;
findNNCorrespondencesBidirectional<ScalarT,EigenDim,DistAdaptor,EvaluatorT,CorrValueT>(first_points, second_points, first_tree, second_tree, corr_set, max_distance, require_reciprocal, evaluator);
return corr_set;
}
}
<commit_msg>Minor fix/clean-up<commit_after>#pragma once
#include <cilantro/kd_tree.hpp>
namespace cilantro {
template <typename ScalarT>
struct Correspondence {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
Correspondence(size_t i, size_t j, ScalarT val) : indexInFirst(i), indexInSecond(j), value(val) {}
size_t indexInFirst;
size_t indexInSecond;
ScalarT value;
struct ValueLessComparator {
inline bool operator()(const Correspondence &c1, const Correspondence &c2) const {
return c1.value < c2.value;
}
};
struct ValueGreaterComparator {
inline bool operator()(const Correspondence &c1, const Correspondence &c2) const {
return c1.value > c2.value;
}
};
struct IndicesLexicographicalComparator {
inline bool operator()(const Correspondence &c1, const Correspondence &c2) const {
return std::tie(c1.indexInFirst, c1.indexInSecond) < std::tie(c2.indexInFirst, c2.indexInSecond);
}
};
};
template <typename ScalarT>
struct CorrespondenceDistanceEvaluator {
inline ScalarT operator()(size_t first_ind, size_t second_ind, ScalarT dist) const {
return dist;
}
};
template <typename ScalarT>
using CorrespondenceSet = std::vector<Correspondence<ScalarT>>;
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
void selectFirstSetCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first,
VectorSet<ScalarT,EigenDim> &first_corr)
{
first_corr.resize(first.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
first_corr.col(i) = first.col(correspondences[i].indexInFirst);
}
}
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
VectorSet<ScalarT,EigenDim> selectFirstSetCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first)
{
VectorSet<ScalarT,EigenDim> first_corr(first.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
first_corr.col(i) = first.col(correspondences[i].indexInFirst);
}
return first_corr;
}
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
void selectSecondSetCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second,
VectorSet<ScalarT,EigenDim> &second_corr)
{
second_corr.resize(second.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
second_corr.col(i) = second.col(correspondences[i].indexInSecond);
}
}
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
VectorSet<ScalarT,EigenDim> selectSecondSetCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second)
{
VectorSet<ScalarT,EigenDim> second_corr(second.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
second_corr.col(i) = second.col(correspondences[i].indexInSecond);
}
return second_corr;
}
template <typename ScalarT, ptrdiff_t EigenDim, typename CorrValueT = ScalarT>
void selectCorrespondingPoints(const CorrespondenceSet<CorrValueT> &correspondences,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second,
VectorSet<ScalarT,EigenDim> &first_corr,
VectorSet<ScalarT,EigenDim> &second_corr)
{
first_corr.resize(first.rows(), correspondences.size());
second_corr.resize(second.rows(), correspondences.size());
#pragma omp parallel for
for (size_t i = 0; i < correspondences.size(); i++) {
first_corr.col(i) = first.col(correspondences[i].indexInFirst);
second_corr.col(i) = second.col(correspondences[i].indexInSecond);
}
}
template <typename ScalarT, class ComparatorT = typename Correspondence<ScalarT>::ValueLessComparator>
void filterCorrespondencesFraction(CorrespondenceSet<ScalarT> &correspondences,
double fraction_to_keep,
const ComparatorT &comparator = ComparatorT())
{
if (fraction_to_keep > 0.0 && fraction_to_keep < 1.0) {
std::sort(correspondences.begin(), correspondences.end(), comparator);
correspondences.erase(correspondences.begin() + std::llround(fraction_to_keep*correspondences.size()), correspondences.end());
}
}
template <typename ScalarT, ptrdiff_t EigenDim, template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, class EvaluatorT = CorrespondenceDistanceEvaluator<ScalarT>, typename CorrValueT = decltype(std::declval<EvaluatorT>().operator()((size_t)0,(size_t)0,(ScalarT)0))>
void findNNCorrespondencesUnidirectional(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
const KDTree<ScalarT,EigenDim,DistAdaptor> &ref_tree,
bool ref_is_first,
CorrespondenceSet<CorrValueT> &correspondences,
CorrValueT max_distance,
const EvaluatorT &evaluator = EvaluatorT())
{
correspondences.clear();
correspondences.reserve(query_pts.cols());
NearestNeighborSearchResult<ScalarT> nn;
if (ref_is_first) {
#pragma omp parallel for shared (correspondences) private (nn)
for (size_t i = 0; i < query_pts.cols(); i++) {
ref_tree.nearestNeighborSearch(query_pts.col(i), nn);
if (nn.value < max_distance) {
#pragma omp critical
correspondences.emplace_back(nn.index, i, evaluator(nn.index, i, nn.value));
}
}
} else {
#pragma omp parallel for shared (correspondences) private (nn)
for (size_t i = 0; i < query_pts.cols(); i++) {
ref_tree.nearestNeighborSearch(query_pts.col(i), nn);
if (nn.value < max_distance) {
#pragma omp critical
correspondences.emplace_back(i, nn.index, evaluator(i, nn.index, nn.value));
}
}
}
}
template <typename ScalarT, ptrdiff_t EigenDim, template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, class EvaluatorT = CorrespondenceDistanceEvaluator<ScalarT>, typename CorrValueT = decltype(std::declval<EvaluatorT>().operator()((size_t)0,(size_t)0,(ScalarT)0))>
inline CorrespondenceSet<CorrValueT> findNNCorrespondencesUnidirectional(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &query_pts,
const KDTree<ScalarT,EigenDim,DistAdaptor> &ref_tree,
bool ref_is_first,
CorrValueT max_distance,
const EvaluatorT &evaluator = EvaluatorT())
{
CorrespondenceSet<CorrValueT> corr_set;
findNNCorrespondencesUnidirectional<ScalarT,EigenDim,DistAdaptor,EvaluatorT,CorrValueT>(query_pts, ref_tree, ref_is_first, corr_set, max_distance, evaluator);
return corr_set;
}
template <typename ScalarT, ptrdiff_t EigenDim, template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, class EvaluatorT = CorrespondenceDistanceEvaluator<ScalarT>, typename CorrValueT = decltype(std::declval<EvaluatorT>().operator()((size_t)0,(size_t)0,(ScalarT)0))>
void findNNCorrespondencesBidirectional(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first_points,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second_points,
const KDTree<ScalarT,EigenDim,DistAdaptor> &first_tree,
const KDTree<ScalarT,EigenDim,DistAdaptor> &second_tree,
CorrespondenceSet<CorrValueT> &correspondences,
CorrValueT max_distance,
bool require_reciprocal = false,
const EvaluatorT &evaluator = EvaluatorT())
{
CorrespondenceSet<CorrValueT> corr_first_to_second, corr_second_to_first;
findNNCorrespondencesUnidirectional<ScalarT,EigenDim,DistAdaptor,EvaluatorT,CorrValueT>(first_points, second_tree, false, corr_first_to_second, max_distance, evaluator);
findNNCorrespondencesUnidirectional<ScalarT,EigenDim,DistAdaptor,EvaluatorT,CorrValueT>(second_points, first_tree, true, corr_second_to_first, max_distance, evaluator);
typename Correspondence<CorrValueT>::IndicesLexicographicalComparator comparator;
std::sort(corr_first_to_second.begin(), corr_first_to_second.end(), comparator);
std::sort(corr_second_to_first.begin(), corr_second_to_first.end(), comparator);
correspondences.clear();
correspondences.reserve(corr_first_to_second.size()+corr_second_to_first.size());
if (require_reciprocal) {
std::set_intersection(corr_first_to_second.begin(), corr_first_to_second.end(),
corr_second_to_first.begin(), corr_second_to_first.end(),
std::back_inserter(correspondences), comparator);
} else {
std::set_union(corr_first_to_second.begin(), corr_first_to_second.end(),
corr_second_to_first.begin(), corr_second_to_first.end(),
std::back_inserter(correspondences), comparator);
}
}
template <typename ScalarT, ptrdiff_t EigenDim, template <class> class DistAdaptor = KDTreeDistanceAdaptors::L2, class EvaluatorT = CorrespondenceDistanceEvaluator<ScalarT>, typename CorrValueT = decltype(std::declval<EvaluatorT>().operator()((size_t)0,(size_t)0,(ScalarT)0))>
inline CorrespondenceSet<CorrValueT> findNNCorrespondencesBidirectional(const ConstVectorSetMatrixMap<ScalarT,EigenDim> &first_points,
const ConstVectorSetMatrixMap<ScalarT,EigenDim> &second_points,
const KDTree<ScalarT,EigenDim,DistAdaptor> &first_tree,
const KDTree<ScalarT,EigenDim,DistAdaptor> &second_tree,
CorrValueT max_distance,
bool require_reciprocal = false,
const EvaluatorT &evaluator = EvaluatorT())
{
CorrespondenceSet<CorrValueT> corr_set;
findNNCorrespondencesBidirectional<ScalarT,EigenDim,DistAdaptor,EvaluatorT,CorrValueT>(first_points, second_points, first_tree, second_tree, corr_set, max_distance, require_reciprocal, evaluator);
return corr_set;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <utility>
#include <algorithm>
using namespace std;
//vector<int> dx = {0, 1, 0, -1};
//vector<int> dy = {1, 0, -1, 0};
template<typename T>
void show(T a){
for(auto i : a){ cout << i << " "; }
cout << endl;
}
template<typename T>
void showmatrix(T a){
for(auto j: a){for(auto i : j){ cout << i; }cout << endl;}
cout << endl;
}
void check(int i = 0){
cout << "checkpoint:[" << i << "]" << endl;
}
/*
1:9
2:4
3:4
4:2
5:1
6:1
7:4
8:2
9:2
*/
int getNum(long a, long b){
if(b == 0) return 1;
int ia = a%10;
if(ia == 0 || ia == 5 || ia ==6) return ia;
int c;
if(ia == 1){
c = 9;
}
if(ia == 2 || ia ==3 || ia==7){
c = 4;
}
if(ia ==4 ||ia==8 ||ia==9){
c = 2;
}
c = (b-1) % c;
int res = ia;
for(int i = 0; i < c; i++){
res = res * ia;
res = res % 10;
// cout << "res:" << res <<endl;
}
return res % 10;
}
int main(int argc, char *argv[]){
ios::sync_with_stdio(false);
cin.tie(NULL);
// cout << getNum(7, 1) << endl;
// cout << getNum(7, 2) << endl;
// cout << getNum(7, 3) << endl;
// cout << getNum(7, 4) << endl;
// cout << getNum(7, 5) << endl;
int a, b, c;
cin >> a >> b>> c;
if( c == 0)
b = 1;
int r = getNum(a, b);
cout << r <<endl;
}
<commit_msg>disable b, write it later<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <utility>
#include <algorithm>
using namespace std;
//vector<int> dx = {0, 1, 0, -1};
//vector<int> dy = {1, 0, -1, 0};
template<typename T>
void show(T a){
for(auto i : a){ cout << i << " "; }
cout << endl;
}
template<typename T>
void showmatrix(T a){
for(auto j: a){for(auto i : j){ cout << i; }cout << endl;}
cout << endl;
}
void check(int i = 0){
cout << "checkpoint:[" << i << "]" << endl;
}
/*
1:9
2:4
3:4
4:2
5:1
6:1
7:4
8:2
9:2
*/
int getNum(long a, long b){
if(b == 0) return 1;
int ia = a%10;
if(ia == 0 || ia == 5 || ia ==6) return ia;
int c;
if(ia == 1){
c = 9;
}
if(ia == 2 || ia ==3 || ia==7){
c = 4;
}
if(ia ==4 ||ia==8 ||ia==9){
c = 2;
}
c = (b-1) % c;
int res = ia;
for(int i = 0; i < c; i++){
res = res * ia;
res = res % 10;
// cout << "res:" << res <<endl;
}
return res % 10;
}
int main(int argc, char *argv[]){
ios::sync_with_stdio(false);
cin.tie(NULL);
// cout << getNum(7, 1) << endl;
// cout << getNum(7, 2) << endl;
// cout << getNum(7, 3) << endl;
// cout << getNum(7, 4) << endl;
// cout << getNum(7, 5) << endl;
// int a, b, c;
// cin >> a >> b>> c;
// if( c == 0)
// b = 1;
// int r = getNum(a, b);
// cout << r <<endl;
}
<|endoftext|>
|
<commit_before>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "WireDecoder.h"
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include "internal.h"
#include "leb128.h"
using namespace ntimpl;
static double ReadDouble(char*& buf) {
// Fast but non-portable!
std::uint64_t val = (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
return *reinterpret_cast<double*>(&val);
}
WireDecoder::WireDecoder(raw_istream& is, unsigned int proto_rev) : m_is(is) {
// Start with a 1K temporary buffer. Use malloc instead of new so we can
// realloc.
m_allocated = 1024;
m_buf = static_cast<char*>(std::malloc(m_allocated));
m_proto_rev = proto_rev;
m_error = nullptr;
}
WireDecoder::~WireDecoder() { std::free(m_buf); }
bool WireDecoder::ReadDouble(double* val) {
char* buf;
if (!Read(&buf, 8)) return false;
*val = ::ReadDouble(buf);
return true;
}
void WireDecoder::Realloc(std::size_t len) {
// Double current buffer size until we have enough space.
if (m_allocated >= len) return;
std::size_t newlen = m_allocated * 2;
while (newlen < len) newlen *= 2;
m_buf = static_cast<char*>(std::realloc(m_buf, newlen));
m_allocated = newlen;
}
bool WireDecoder::ReadType(NT_Type* type) {
unsigned int itype;
if (!Read8(&itype)) return false;
// Convert from byte value to enum
switch (itype) {
case 0x00:
*type = NT_BOOLEAN;
break;
case 0x01:
*type = NT_DOUBLE;
break;
case 0x02:
*type = NT_STRING;
break;
case 0x03:
*type = NT_RAW;
break;
case 0x10:
*type = NT_BOOLEAN_ARRAY;
break;
case 0x11:
*type = NT_DOUBLE_ARRAY;
break;
case 0x12:
*type = NT_STRING_ARRAY;
break;
case 0x20:
*type = NT_RPC;
break;
default:
m_error = "unrecognized value type";
return false;
}
return true;
}
bool WireDecoder::ReadValue(NT_Type type, NT_Value* value) {
value->type = type;
value->last_change = 0;
switch (type) {
case NT_BOOLEAN: {
unsigned int v;
if (!Read8(&v)) return false;
value->data.v_boolean = v ? 1 : 0;
break;
}
case NT_DOUBLE: {
if (!ReadDouble(&value->data.v_double)) return false;
break;
}
case NT_STRING:
if (!ReadString(&value->data.v_string)) return false;
break;
case NT_RAW:
case NT_RPC:
if (m_proto_rev < 0x0300u) {
m_error = "received raw or RPC value in protocol < 3.0";
return false;
}
if (!ReadString(&value->data.v_raw)) return false;
break;
case NT_BOOLEAN_ARRAY: {
// size
unsigned int size;
if (!Read8(&size)) return false;
value->data.arr_boolean.size = size;
// array values
char* buf;
if (!Read(&buf, size)) return false;
value->data.arr_boolean.arr =
static_cast<int*>(std::malloc(size * sizeof(int)));
for (unsigned int i = 0; i < size; ++i)
value->data.arr_boolean.arr[i] = buf[i] ? 1 : 0;
break;
}
case NT_DOUBLE_ARRAY: {
// size
unsigned int size;
if (!Read8(&size)) return false;
value->data.arr_double.size = size;
// array values
char* buf;
if (!Read(&buf, size * 8)) return false;
value->data.arr_double.arr =
static_cast<double*>(std::malloc(size * sizeof(double)));
for (unsigned int i = 0; i < size; ++i)
value->data.arr_double.arr[i] = ::ReadDouble(buf);
break;
}
case NT_STRING_ARRAY: {
// size
unsigned int size;
if (!Read8(&size)) return false;
value->data.arr_string.size = size;
// array values
value->data.arr_string.arr =
static_cast<NT_String*>(std::malloc(size * sizeof(NT_String)));
for (unsigned int i = 0; i < size; ++i) {
if (!ReadString(&value->data.arr_string.arr[i])) {
// cleanup to avoid memory leaks
for (unsigned int j = 0; j < i; ++j) {
std::free(value->data.arr_string.arr[j].str);
}
std::free(value->data.arr_string.arr);
return false;
}
}
break;
}
default:
m_error = "invalid type when trying to read value";
return false;
}
return true;
}
bool WireDecoder::ReadString(NT_String* str) {
if (m_proto_rev < 0x0300u) {
unsigned int v;
if (!Read16(&v)) return false;
str->len = v;
} else {
unsigned long v;
if (!ReadUleb128(&v)) return false;
str->len = v;
}
str->str = static_cast<char*>(std::malloc(str->len + 1)); // +1 for nul
if (!m_is.read(str->str, str->len)) {
std::free(str->str);
str->str = 0;
return false;
}
str->str[str->len] = '\0'; // be nice and nul-terminate it
return true;
}
<commit_msg>WireDecoder ReadDouble: Use ref cast.<commit_after>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2015. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "WireDecoder.h"
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include "internal.h"
#include "leb128.h"
using namespace ntimpl;
static double ReadDouble(char*& buf) {
// Fast but non-portable!
std::uint64_t val = (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
val <<= 8;
val |= (*((unsigned char*)buf)) & 0xff;
++buf;
return reinterpret_cast<double&>(val);
}
WireDecoder::WireDecoder(raw_istream& is, unsigned int proto_rev) : m_is(is) {
// Start with a 1K temporary buffer. Use malloc instead of new so we can
// realloc.
m_allocated = 1024;
m_buf = static_cast<char*>(std::malloc(m_allocated));
m_proto_rev = proto_rev;
m_error = nullptr;
}
WireDecoder::~WireDecoder() { std::free(m_buf); }
bool WireDecoder::ReadDouble(double* val) {
char* buf;
if (!Read(&buf, 8)) return false;
*val = ::ReadDouble(buf);
return true;
}
void WireDecoder::Realloc(std::size_t len) {
// Double current buffer size until we have enough space.
if (m_allocated >= len) return;
std::size_t newlen = m_allocated * 2;
while (newlen < len) newlen *= 2;
m_buf = static_cast<char*>(std::realloc(m_buf, newlen));
m_allocated = newlen;
}
bool WireDecoder::ReadType(NT_Type* type) {
unsigned int itype;
if (!Read8(&itype)) return false;
// Convert from byte value to enum
switch (itype) {
case 0x00:
*type = NT_BOOLEAN;
break;
case 0x01:
*type = NT_DOUBLE;
break;
case 0x02:
*type = NT_STRING;
break;
case 0x03:
*type = NT_RAW;
break;
case 0x10:
*type = NT_BOOLEAN_ARRAY;
break;
case 0x11:
*type = NT_DOUBLE_ARRAY;
break;
case 0x12:
*type = NT_STRING_ARRAY;
break;
case 0x20:
*type = NT_RPC;
break;
default:
m_error = "unrecognized value type";
return false;
}
return true;
}
bool WireDecoder::ReadValue(NT_Type type, NT_Value* value) {
value->type = type;
value->last_change = 0;
switch (type) {
case NT_BOOLEAN: {
unsigned int v;
if (!Read8(&v)) return false;
value->data.v_boolean = v ? 1 : 0;
break;
}
case NT_DOUBLE: {
if (!ReadDouble(&value->data.v_double)) return false;
break;
}
case NT_STRING:
if (!ReadString(&value->data.v_string)) return false;
break;
case NT_RAW:
case NT_RPC:
if (m_proto_rev < 0x0300u) {
m_error = "received raw or RPC value in protocol < 3.0";
return false;
}
if (!ReadString(&value->data.v_raw)) return false;
break;
case NT_BOOLEAN_ARRAY: {
// size
unsigned int size;
if (!Read8(&size)) return false;
value->data.arr_boolean.size = size;
// array values
char* buf;
if (!Read(&buf, size)) return false;
value->data.arr_boolean.arr =
static_cast<int*>(std::malloc(size * sizeof(int)));
for (unsigned int i = 0; i < size; ++i)
value->data.arr_boolean.arr[i] = buf[i] ? 1 : 0;
break;
}
case NT_DOUBLE_ARRAY: {
// size
unsigned int size;
if (!Read8(&size)) return false;
value->data.arr_double.size = size;
// array values
char* buf;
if (!Read(&buf, size * 8)) return false;
value->data.arr_double.arr =
static_cast<double*>(std::malloc(size * sizeof(double)));
for (unsigned int i = 0; i < size; ++i)
value->data.arr_double.arr[i] = ::ReadDouble(buf);
break;
}
case NT_STRING_ARRAY: {
// size
unsigned int size;
if (!Read8(&size)) return false;
value->data.arr_string.size = size;
// array values
value->data.arr_string.arr =
static_cast<NT_String*>(std::malloc(size * sizeof(NT_String)));
for (unsigned int i = 0; i < size; ++i) {
if (!ReadString(&value->data.arr_string.arr[i])) {
// cleanup to avoid memory leaks
for (unsigned int j = 0; j < i; ++j) {
std::free(value->data.arr_string.arr[j].str);
}
std::free(value->data.arr_string.arr);
return false;
}
}
break;
}
default:
m_error = "invalid type when trying to read value";
return false;
}
return true;
}
bool WireDecoder::ReadString(NT_String* str) {
if (m_proto_rev < 0x0300u) {
unsigned int v;
if (!Read16(&v)) return false;
str->len = v;
} else {
unsigned long v;
if (!ReadUleb128(&v)) return false;
str->len = v;
}
str->str = static_cast<char*>(std::malloc(str->len + 1)); // +1 for nul
if (!m_is.read(str->str, str->len)) {
std::free(str->str);
str->str = 0;
return false;
}
str->str[str->len] = '\0'; // be nice and nul-terminate it
return true;
}
<|endoftext|>
|
<commit_before>#pragma once
/**
@file
@brief string operation for cybozu::String
Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
@note
modifying functions are almost the following type:
void function(String& out, String& in, bool doAppend = false);
if doAppend is true then the function will append string to <out>.
*/
#include <algorithm>
#include <cybozu/string.hpp>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4389) // compare signed and unsigned
#endif
namespace cybozu {
namespace string {
static const bool DoAppend = true;
} // string
/**
verify whether c is a space or 0xfeff(BOM)
the definition of space is
http://unicode.org/Public/UNIDATA/PropList.txt
0009..000D ; White_Space # Cc [5] <control-0009>..<control-000D>
0020 ; White_Space # Zs SPACE
0085 ; White_Space # Cc <control-0085>
00A0 ; White_Space # Zs NO-BREAK SPACE
1680 ; White_Space # Zs OGHAM SPACE MARK
180E ; White_Space # Zs MONGOLIAN VOWEL SEPARATOR
2000..200A ; White_Space # Zs [11] EN QUAD..HAIR SPACE
2028 ; White_Space # Zl LINE SEPARATOR
2029 ; White_Space # Zp PARAGRAPH SEPARATOR
202F ; White_Space # Zs NARROW NO-BREAK SPACE
205F ; White_Space # Zs MEDIUM MATHEMATICAL SPACE
3000 ; White_Space # Zs IDEOGRAPHIC SPACE
+
0xfeff // zero width no-break space
*/
inline bool IsSpace(Char c)
{
if (c == 0x20 || c == 0x3000) return true;
if (unsigned(c - 0x09) <= 0x0d - 0x09) return true;
if (c == 0x85 || c == 0xa0) return true;
if (c < 0x1680) return false;
if (c == 0x1680 || c == 0x180e) return true;
if (unsigned(c - 0x2000) <= 0x200a - 0x2000) return true;
if (unsigned(c - 0x2028) <= 0x2029 - 0x2028) return true;
if (c == 0x202f || c == 0x205f || c == 0xfeff) return true;
return false;
}
/*
c is space or tab(Don't modify this condition)
*/
inline bool IsSpace(char c)
{
if (c == ' ' || c == '\t') return true;
return false;
}
template<typename Iterator>
inline Iterator* SkipSpace(Iterator *begin, Iterator *end)
{
while (begin < end) {
if (!cybozu::IsSpace(*begin)) break;
++begin;
}
return begin;
}
namespace string_local {
/**
get trimed position [begin, end)
@param begin [in] begin of string
@param end [inout] end of string
return new begin position
*/
template<typename Iterator>
inline Iterator* GetTrimPosition(Iterator *begin, Iterator *&end)
{
begin = cybozu::SkipSpace(begin, end);
while (begin < end) {
if (!cybozu::IsSpace(end[-1])) break;
--end;
}
return begin;
}
template<class StringT1, class StringT2, class Func>
void ChangeCase(StringT1& out, const StringT2& in, Func f, bool doAppend)
{
size_t offset = doAppend ? out.size() : 0;
out.resize(offset + in.size());
std::transform(in.begin(), in.end(), out.begin() + offset, f);
}
template<class CharT>struct SelectString;
template<> struct SelectString<char> { typedef std::string string_type; };
template<> struct SelectString<cybozu::Char> { typedef cybozu::String string_type; };
} // string_local
/**
trim space
@param str [inout] string to be trimed
*/
template<class StringT>
inline void Trim(StringT& str)
{
typedef typename StringT::value_type CharT;
if (str.empty()) return;
CharT *begin = &str[0];
CharT *end = begin + str.size();
CharT *newBegin = cybozu::string_local::GetTrimPosition(begin, end);
size_t size = end - newBegin;
if (begin != newBegin) {
for (size_t i = 0; i < size; i++) {
*begin++ = *newBegin++;
}
}
str.resize(size);
}
template<class StringT>
inline StringT TrimCopy(const StringT& str)
{
typedef typename StringT::value_type CharT;
if (str.empty()) return "";
const CharT *begin = &str[0];
const CharT *end = begin + str.size();
const CharT *newBegin = cybozu::string_local::GetTrimPosition(begin, end);
return StringT(newBegin, end);
}
template<class StringT1, class StringT2>
void ToLower(StringT1& out, const StringT2& in, bool doAppend = false)
{
string_local::ChangeCase(out, in, cybozu::tolower<typename StringT1::value_type>, doAppend);
}
template<class StringT1, class StringT2>
void ToUpper(StringT1& out, const StringT2& in, bool doAppend = false)
{
string_local::ChangeCase(out, in, cybozu::toupper<typename StringT1::value_type>, doAppend);
}
template<class StringT>
void ToLower(StringT& str)
{
ToLower(str, str);
}
template<class StringT>
void ToUpper(StringT& str)
{
ToUpper(str, str);
}
/**
case insensitive compare function
not depend on locale, not depend on compiler
*/
template<class CharT>
int CaseCompare(const CharT *lhs, size_t lhsSize, const CharT *rhs, size_t rhsSize)
{
size_t n = std::min(lhsSize, rhsSize);
for (size_t i = 0; i < n; i++) {
CharT cR = cybozu::tolower(lhs[i]);
CharT cL = cybozu::tolower(rhs[i]);
if (cR < cL) return -1;
if (cR > cL) return 1;
}
if (lhsSize < rhsSize) return -1;
if (lhsSize > rhsSize) return 1;
return 0;
}
template<class CharT1, class CharT2>
bool CaseEqual(const CharT1 *lhs, size_t lhsSize, const CharT2 *rhs, size_t rhsSize)
{
if (lhsSize != rhsSize) return false;
for (size_t i = 0; i < lhsSize; i++) {
CharT1 cR = cybozu::tolower(lhs[i]);
CharT2 cL = cybozu::tolower(rhs[i]);
if (cR != cL) return false;
}
return true;
}
/**
case insensitive compare lhs with rhs
@param lhs [in] left side string
@param rhs [in] right side string
@retval 1 if lhs > rhs
@retval 0 if lhs == rhs
@retval -1 if lhs < rhs
*/
template<class StringT>
int CaseCompare(const StringT& lhs, const StringT& rhs)
{
return cybozu::CaseCompare(&lhs[0], lhs.size(), &rhs[0], rhs.size());
}
/**
whether lhs is equal to rhs with case insensitive
@param lhs [in] left side string
@param rhs [in] right side string
*/
template<class StringT>
bool CaseEqual(const StringT& lhs, const StringT& rhs)
{
return cybozu::CaseEqual(&lhs[0], lhs.size(), &rhs[0], rhs.size());
}
template<class StringT>
bool CaseEqual(const StringT& lhs, const char *rhs)
{
return cybozu::CaseEqual(&lhs[0], lhs.size(), rhs, strlen(rhs));
}
/**
find target in [begin, end) with case insensitive
@param begin [in] begin of string
@param end [in] end of string
@param targetBegin [in] begin of *small* target
@param targetEnd [in] end of *small* target string(if NULL then use null terminate string)
@retval !0 if found
@retval 0 if not found
*/
template<class CharT>
const CharT *CaseFind(const CharT *begin, const CharT *end, const char *targetBegin, const char *targetEnd = 0)
{
const size_t n = targetEnd ? targetEnd - targetBegin : ::strlen(targetBegin);
typename string_local::SelectString<CharT>::string_type t(targetBegin, n);
ToLower(t);
while (begin + n <= end) {
bool found = true;
for (size_t i = 0; i < n; i++) {
if (cybozu::tolower(begin[i]) != t[i]) {
found = false;
break;
}
}
if (found) return begin;
begin++;
}
return 0;
}
template<class CharT>
size_t CaseFind(const typename string_local::SelectString<CharT>::string_type& str, const char *targetBegin, const char *targetEnd = 0)
{
if (!str.empty()) {
const CharT *p = CaseFind(&str[0], &str[0] + str.size(), targetBegin, targetEnd);
if (p) {
return p - &str[0];
}
}
return std::string::npos;
}
/**
whether lhs is equal to rhs[0..N) with case insensitive
@param lhs [in] left side string
@param rhs [in] right side string
*/
template<class StringT, size_t N>
bool CaseEqualStartWith(const StringT& lhs, const char (&rhs)[N])
{
if (lhs.size() < N - 1) return false;
return cybozu::CaseEqual(&lhs[0], N - 1, rhs, N - 1);
}
/**
split inStr into out at splitChar
maxNum is maximum number of split str
out must have clear() and push_back()
*/
template<class Out, class StringT>
size_t Split(Out& out, const StringT& inStr, typename StringT::value_type splitChar = ',', size_t maxNum = 0x7fffffff)
{
typedef StringT String;
size_t splitNum = 0;
size_t cur = 0;
out.clear();
for (;;) {
size_t pos = inStr.find_first_of(splitChar, cur);
if (pos == String::npos || splitNum == maxNum - 1) {
out.push_back(String(&inStr[cur], &inStr[0] + inStr.size()));
splitNum++;
break;
}
out.push_back(String(&inStr[cur], &inStr[pos]));
cur = pos + 1;
splitNum++;
}
return splitNum;
}
} // cybozu
#ifdef _MSC_VER
#pragma warning(pop)
#endif
<commit_msg>support string::iterator<commit_after>#pragma once
/**
@file
@brief string operation for cybozu::String
Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
@note
modifying functions are almost the following type:
void function(String& out, String& in, bool doAppend = false);
if doAppend is true then the function will append string to <out>.
*/
#include <algorithm>
#include <cybozu/string.hpp>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4389) // compare signed and unsigned
#endif
namespace cybozu {
namespace string {
static const bool DoAppend = true;
} // string
/**
verify whether c is a space or 0xfeff(BOM)
the definition of space is
http://unicode.org/Public/UNIDATA/PropList.txt
0009..000D ; White_Space # Cc [5] <control-0009>..<control-000D>
0020 ; White_Space # Zs SPACE
0085 ; White_Space # Cc <control-0085>
00A0 ; White_Space # Zs NO-BREAK SPACE
1680 ; White_Space # Zs OGHAM SPACE MARK
180E ; White_Space # Zs MONGOLIAN VOWEL SEPARATOR
2000..200A ; White_Space # Zs [11] EN QUAD..HAIR SPACE
2028 ; White_Space # Zl LINE SEPARATOR
2029 ; White_Space # Zp PARAGRAPH SEPARATOR
202F ; White_Space # Zs NARROW NO-BREAK SPACE
205F ; White_Space # Zs MEDIUM MATHEMATICAL SPACE
3000 ; White_Space # Zs IDEOGRAPHIC SPACE
+
0xfeff // zero width no-break space
*/
inline bool IsSpace(Char c)
{
if (c == 0x20 || c == 0x3000) return true;
if (unsigned(c - 0x09) <= 0x0d - 0x09) return true;
if (c == 0x85 || c == 0xa0) return true;
if (c < 0x1680) return false;
if (c == 0x1680 || c == 0x180e) return true;
if (unsigned(c - 0x2000) <= 0x200a - 0x2000) return true;
if (unsigned(c - 0x2028) <= 0x2029 - 0x2028) return true;
if (c == 0x202f || c == 0x205f || c == 0xfeff) return true;
return false;
}
/*
c is space or tab(Don't modify this condition)
*/
inline bool IsSpace(char c)
{
if (c == ' ' || c == '\t') return true;
return false;
}
template<typename Iterator>
inline Iterator SkipSpace(Iterator begin, Iterator end)
{
while (begin < end) {
if (!cybozu::IsSpace(*begin)) break;
++begin;
}
return begin;
}
namespace string_local {
/**
get trimed position [begin, end)
@param begin [in] begin of string
@param end [inout] end of string
return new begin position
*/
template<typename Iterator>
inline Iterator GetTrimPosition(Iterator begin, Iterator &end)
{
begin = cybozu::SkipSpace(begin, end);
while (begin < end) {
if (!cybozu::IsSpace(end[-1])) break;
--end;
}
return begin;
}
template<class StringT1, class StringT2, class Func>
void ChangeCase(StringT1& out, const StringT2& in, Func f, bool doAppend)
{
size_t offset = doAppend ? out.size() : 0;
out.resize(offset + in.size());
std::transform(in.begin(), in.end(), out.begin() + offset, f);
}
template<class CharT>struct SelectString;
template<> struct SelectString<char> { typedef std::string string_type; };
template<> struct SelectString<cybozu::Char> { typedef cybozu::String string_type; };
} // string_local
/**
trim space
@param str [inout] string to be trimed
*/
template<class StringT>
inline void Trim(StringT& str)
{
typedef typename StringT::value_type CharT;
if (str.empty()) return;
CharT *begin = &str[0];
CharT *end = begin + str.size();
CharT *newBegin = cybozu::string_local::GetTrimPosition(begin, end);
size_t size = end - newBegin;
if (begin != newBegin) {
for (size_t i = 0; i < size; i++) {
*begin++ = *newBegin++;
}
}
str.resize(size);
}
template<class StringT>
inline StringT TrimCopy(const StringT& str)
{
typedef typename StringT::value_type CharT;
if (str.empty()) return "";
const CharT *begin = &str[0];
const CharT *end = begin + str.size();
const CharT *newBegin = cybozu::string_local::GetTrimPosition(begin, end);
return StringT(newBegin, end);
}
template<class StringT1, class StringT2>
void ToLower(StringT1& out, const StringT2& in, bool doAppend = false)
{
string_local::ChangeCase(out, in, cybozu::tolower<typename StringT1::value_type>, doAppend);
}
template<class StringT1, class StringT2>
void ToUpper(StringT1& out, const StringT2& in, bool doAppend = false)
{
string_local::ChangeCase(out, in, cybozu::toupper<typename StringT1::value_type>, doAppend);
}
template<class StringT>
void ToLower(StringT& str)
{
ToLower(str, str);
}
template<class StringT>
void ToUpper(StringT& str)
{
ToUpper(str, str);
}
/**
case insensitive compare function
not depend on locale, not depend on compiler
*/
template<class CharT>
int CaseCompare(const CharT *lhs, size_t lhsSize, const CharT *rhs, size_t rhsSize)
{
size_t n = std::min(lhsSize, rhsSize);
for (size_t i = 0; i < n; i++) {
CharT cR = cybozu::tolower(lhs[i]);
CharT cL = cybozu::tolower(rhs[i]);
if (cR < cL) return -1;
if (cR > cL) return 1;
}
if (lhsSize < rhsSize) return -1;
if (lhsSize > rhsSize) return 1;
return 0;
}
template<class CharT1, class CharT2>
bool CaseEqual(const CharT1 *lhs, size_t lhsSize, const CharT2 *rhs, size_t rhsSize)
{
if (lhsSize != rhsSize) return false;
for (size_t i = 0; i < lhsSize; i++) {
CharT1 cR = cybozu::tolower(lhs[i]);
CharT2 cL = cybozu::tolower(rhs[i]);
if (cR != cL) return false;
}
return true;
}
/**
case insensitive compare lhs with rhs
@param lhs [in] left side string
@param rhs [in] right side string
@retval 1 if lhs > rhs
@retval 0 if lhs == rhs
@retval -1 if lhs < rhs
*/
template<class StringT>
int CaseCompare(const StringT& lhs, const StringT& rhs)
{
return cybozu::CaseCompare(&lhs[0], lhs.size(), &rhs[0], rhs.size());
}
/**
whether lhs is equal to rhs with case insensitive
@param lhs [in] left side string
@param rhs [in] right side string
*/
template<class StringT>
bool CaseEqual(const StringT& lhs, const StringT& rhs)
{
return cybozu::CaseEqual(&lhs[0], lhs.size(), &rhs[0], rhs.size());
}
template<class StringT>
bool CaseEqual(const StringT& lhs, const char *rhs)
{
return cybozu::CaseEqual(&lhs[0], lhs.size(), rhs, strlen(rhs));
}
/**
find target in [begin, end) with case insensitive
@param begin [in] begin of string
@param end [in] end of string
@param targetBegin [in] begin of *small* target
@param targetEnd [in] end of *small* target string(if NULL then use null terminate string)
@retval !0 if found
@retval 0 if not found
*/
template<class CharT>
const CharT *CaseFind(const CharT *begin, const CharT *end, const char *targetBegin, const char *targetEnd = 0)
{
const size_t n = targetEnd ? targetEnd - targetBegin : ::strlen(targetBegin);
typename string_local::SelectString<CharT>::string_type t(targetBegin, n);
ToLower(t);
while (begin + n <= end) {
bool found = true;
for (size_t i = 0; i < n; i++) {
if (cybozu::tolower(begin[i]) != t[i]) {
found = false;
break;
}
}
if (found) return begin;
begin++;
}
return 0;
}
template<class CharT>
size_t CaseFind(const typename string_local::SelectString<CharT>::string_type& str, const char *targetBegin, const char *targetEnd = 0)
{
if (!str.empty()) {
const CharT *p = CaseFind(&str[0], &str[0] + str.size(), targetBegin, targetEnd);
if (p) {
return p - &str[0];
}
}
return std::string::npos;
}
/**
whether lhs is equal to rhs[0..N) with case insensitive
@param lhs [in] left side string
@param rhs [in] right side string
*/
template<class StringT, size_t N>
bool CaseEqualStartWith(const StringT& lhs, const char (&rhs)[N])
{
if (lhs.size() < N - 1) return false;
return cybozu::CaseEqual(&lhs[0], N - 1, rhs, N - 1);
}
/**
split inStr into out at splitChar
maxNum is maximum number of split str
out must have clear() and push_back()
*/
template<class Out, class StringT>
size_t Split(Out& out, const StringT& inStr, typename StringT::value_type splitChar = ',', size_t maxNum = 0x7fffffff)
{
typedef StringT String;
size_t splitNum = 0;
size_t cur = 0;
out.clear();
for (;;) {
size_t pos = inStr.find_first_of(splitChar, cur);
if (pos == String::npos || splitNum == maxNum - 1) {
out.push_back(String(&inStr[cur], &inStr[0] + inStr.size()));
splitNum++;
break;
}
out.push_back(String(&inStr[cur], &inStr[pos]));
cur = pos + 1;
splitNum++;
}
return splitNum;
}
} // cybozu
#ifdef _MSC_VER
#pragma warning(pop)
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/node_main.h"
#include "atom/app/uv_task_runner.h"
#include "atom/browser/javascript_environment.h"
#include "atom/browser/node_debugger.h"
#include "atom/common/api/atom_bindings.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/threading/thread_task_runner_handle.h"
#include "gin/array_buffer.h"
#include "gin/public/isolate_holder.h"
#include "gin/v8_initializer.h"
#if defined(OS_WIN)
#include "atom/common/native_mate_converters/string16_converter.h"
#include "native_mate/dictionary.h"
#endif
#include "atom/common/node_includes.h"
namespace atom {
int NodeMain(int argc, char *argv[]) {
base::CommandLine::Init(argc, argv);
int exit_code = 1;
{
// Feed gin::PerIsolateData with a task runner.
argv = uv_setup_args(argc, argv);
uv_loop_t* loop = uv_default_loop();
scoped_refptr<UvTaskRunner> uv_task_runner(new UvTaskRunner(loop));
base::ThreadTaskRunnerHandle handle(uv_task_runner);
// Initialize feature list.
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
gin::V8Initializer::LoadV8Snapshot();
gin::V8Initializer::LoadV8Natives();
JavascriptEnvironment gin_env;
int exec_argc;
const char** exec_argv;
node::Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
node::Environment* env = node::CreateEnvironment(
gin_env.isolate(), loop, gin_env.context(), argc, argv,
exec_argc, exec_argv);
// Start our custom debugger implementation.
NodeDebugger node_debugger(gin_env.isolate());
if (node_debugger.IsRunning())
env->AssignToContext(v8::Debug::GetDebugContext());
#if defined(OS_WIN)
mate::Dictionary process(gin_env.isolate(), env->process_object());
process.SetMethod("log", &AtomBindings::Log);
#endif
node::LoadEnvironment(env);
bool more;
do {
more = uv_run(env->event_loop(), UV_RUN_ONCE);
if (more == false) {
node::EmitBeforeExit(env);
// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
if (uv_run(env->event_loop(), UV_RUN_NOWAIT) != 0)
more = true;
}
} while (more == true);
exit_code = node::EmitExit(env);
node::RunAtExit(env);
node::FreeEnvironment(env);
}
v8::V8::Dispose();
return exit_code;
}
} // namespace atom
<commit_msg>Moving atom_bindings include to Windows block<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/app/node_main.h"
#include "atom/app/uv_task_runner.h"
#include "atom/browser/javascript_environment.h"
#include "atom/browser/node_debugger.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/threading/thread_task_runner_handle.h"
#include "gin/array_buffer.h"
#include "gin/public/isolate_holder.h"
#include "gin/v8_initializer.h"
#if defined(OS_WIN)
#include "atom/common/api/atom_bindings.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "native_mate/dictionary.h"
#endif
#include "atom/common/node_includes.h"
namespace atom {
int NodeMain(int argc, char *argv[]) {
base::CommandLine::Init(argc, argv);
int exit_code = 1;
{
// Feed gin::PerIsolateData with a task runner.
argv = uv_setup_args(argc, argv);
uv_loop_t* loop = uv_default_loop();
scoped_refptr<UvTaskRunner> uv_task_runner(new UvTaskRunner(loop));
base::ThreadTaskRunnerHandle handle(uv_task_runner);
// Initialize feature list.
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
gin::V8Initializer::LoadV8Snapshot();
gin::V8Initializer::LoadV8Natives();
JavascriptEnvironment gin_env;
int exec_argc;
const char** exec_argv;
node::Init(&argc, const_cast<const char**>(argv), &exec_argc, &exec_argv);
node::Environment* env = node::CreateEnvironment(
gin_env.isolate(), loop, gin_env.context(), argc, argv,
exec_argc, exec_argv);
// Start our custom debugger implementation.
NodeDebugger node_debugger(gin_env.isolate());
if (node_debugger.IsRunning())
env->AssignToContext(v8::Debug::GetDebugContext());
#if defined(OS_WIN)
mate::Dictionary process(gin_env.isolate(), env->process_object());
process.SetMethod("log", &AtomBindings::Log);
#endif
node::LoadEnvironment(env);
bool more;
do {
more = uv_run(env->event_loop(), UV_RUN_ONCE);
if (more == false) {
node::EmitBeforeExit(env);
// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env->event_loop());
if (uv_run(env->event_loop(), UV_RUN_NOWAIT) != 0)
more = true;
}
} while (more == true);
exit_code = node::EmitExit(env);
node::RunAtExit(env);
node::FreeEnvironment(env);
}
v8::V8::Dispose();
return exit_code;
}
} // namespace atom
<|endoftext|>
|
<commit_before>// RUN: %clangxx -frtti -fsanitize=vptr -fno-sanitize-recover=vptr -I%p/Helpers -g %s -fPIC -shared -o %dynamiclib -DBUILD_SO %ld_flags_rpath_so
// RUN: %clangxx -frtti -fsanitize=vptr -fno-sanitize-recover=vptr -I%p/Helpers -g %s -O3 -o %t %ld_flags_rpath_exe
// RUN: %run %t
//
// REQUIRES: cxxabi
// UNSUPPORTED: windows-msvc
struct X {
virtual ~X() {}
};
X *libCall();
#ifdef BUILD_SO
X *libCall() {
return new X;
}
#else
int main() {
X *px = libCall();
delete px;
}
#endif
<commit_msg>Mark vptr-non-unique-typeinfo as a broken test for NetBSD/i386<commit_after>// RUN: %clangxx -frtti -fsanitize=vptr -fno-sanitize-recover=vptr -I%p/Helpers -g %s -fPIC -shared -o %dynamiclib -DBUILD_SO %ld_flags_rpath_so
// RUN: %clangxx -frtti -fsanitize=vptr -fno-sanitize-recover=vptr -I%p/Helpers -g %s -O3 -o %t %ld_flags_rpath_exe
// RUN: %run %t
//
// REQUIRES: cxxabi
// UNSUPPORTED: windows-msvc
// XFAIL: i386-netbsd
struct X {
virtual ~X() {}
};
X *libCall();
#ifdef BUILD_SO
X *libCall() {
return new X;
}
#else
int main() {
X *px = libCall();
delete px;
}
#endif
<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------------
| This file is distributed under the BSD 2-Clause License.
| See LICENSE for details.
*-----------------------------------------------------------------------------*/
#include <cstdio>
#include <vector>
#include <utility> /* std::pair */
#include <cuddObj.hh>
extern "C" {
#include "aig/gia/gia.h"
#include "cudd.h"
}
namespace lsy {
/* Black magic */
static inline int test(DdManager *dd, DdNode *l)
{
if (l == NULL)
return 0;
DdNode *lb = l;
::Cudd_Ref(lb);
while (lb != ::Cudd_ReadLogicZero(dd)) {
DdNode *implicant = ::Cudd_LargestCube(dd, lb, NULL);
if (implicant == NULL) {
::Cudd_RecursiveDeref(dd, lb);
return 0;
}
::Cudd_Ref(implicant);
DdNode *prime = ::Cudd_bddMakePrime(dd, implicant, l);
if (prime == NULL) {
::Cudd_RecursiveDeref(dd, lb);
::Cudd_RecursiveDeref(dd, implicant);
return 0;
}
::Cudd_Ref(prime);
::Cudd_RecursiveDeref(dd, implicant);
DdNode *tmp = ::Cudd_bddAnd(dd, lb, Cudd_Not(prime));
if (tmp == NULL) {
::Cudd_RecursiveDeref(dd, lb);
::Cudd_RecursiveDeref(dd, prime);
return 0;
}
::Cudd_Ref(tmp);
::Cudd_RecursiveDeref(dd, lb);
::Cudd_RecursiveDeref(dd, prime);
lb = tmp;
}
::Cudd_RecursiveDeref(dd, lb);
return 1;
}
std::pair<Cudd, std::vector<BDD>> aig_to_bdd(Gia_Man_t *aig, int verbose)
{
uint32_t i, id;
Gia_Obj_t* obj;
Cudd bdd_mngr;
std::vector<BDD> nodes(Gia_ManObjNum(aig));
//bdd_mngr.AutodynEnable();
//bdd_mngr.AutodynEnable(CUDD_REORDER_EXACT);
printf("[i] Converting AIG to BDD\n");
Gia_ManForEachCiId(aig, id, i) {
nodes[id] = bdd_mngr.bddVar(i);
}
Gia_ManForEachAnd(aig, obj, i) {
const auto b1 = nodes[Gia_ObjFaninId0(obj, i)];
const auto c1 = Gia_ObjFaninC0(obj);
const auto b2 = nodes[Gia_ObjFaninId1(obj, i)];
const auto c2 = Gia_ObjFaninC1(obj);
nodes[i] = (c1 ? !b1 : b1) & (c2 ? !b2 : b2);
if (verbose) {
fprintf(stdout, "\rNode %4d / %4d", i, nodes.size());
fflush(stdout);
}
}
//bdd_mngr.ReduceHeap();
//bdd_mngr.ReduceHeap(CUDD_REORDER_EXACT);
if (verbose) {
fprintf(stdout, " Done\n");
}
/* Outputs */
std::vector<BDD> outputs;
Gia_ManForEachCo(aig, obj, i) {
const auto b = nodes[Gia_ObjFaninId0p(aig, obj)];
const auto c = Gia_ObjFaninC0(obj);
outputs.push_back(c ? !b : b);
test(bdd_mngr.getManager(), outputs.back().getNode());
outputs.back().summary(Gia_ManCiNum(aig));
// outputs.back().PrintCover();
}
fprintf(stdout, " [Done]\n");
//bdd_mngr.AutodynDisable();
return std::make_pair(bdd_mngr, outputs);
}
} // namespace lsy
<commit_msg>Taking into account that DD can be empty.<commit_after>/*------------------------------------------------------------------------------
| This file is distributed under the BSD 2-Clause License.
| See LICENSE for details.
*-----------------------------------------------------------------------------*/
#include <cstdio>
#include <vector>
#include <utility> /* std::pair */
#include <cuddObj.hh>
extern "C" {
#include "aig/gia/gia.h"
#include "cudd.h"
}
namespace lsy {
/* Black magic */
static inline int test(DdManager *dd, DdNode *l)
{
if (l == NULL)
return 0;
DdNode *lb = l;
::Cudd_Ref(lb);
while (lb != ::Cudd_ReadLogicZero(dd)) {
DdNode *implicant = ::Cudd_LargestCube(dd, lb, NULL);
if (implicant == NULL) {
::Cudd_RecursiveDeref(dd, lb);
return 0;
}
::Cudd_Ref(implicant);
DdNode *prime = ::Cudd_bddMakePrime(dd, implicant, l);
if (prime == NULL) {
::Cudd_RecursiveDeref(dd, lb);
::Cudd_RecursiveDeref(dd, implicant);
return 0;
}
::Cudd_Ref(prime);
::Cudd_RecursiveDeref(dd, implicant);
DdNode *tmp = ::Cudd_bddAnd(dd, lb, Cudd_Not(prime));
if (tmp == NULL) {
::Cudd_RecursiveDeref(dd, lb);
::Cudd_RecursiveDeref(dd, prime);
return 0;
}
::Cudd_Ref(tmp);
::Cudd_RecursiveDeref(dd, lb);
::Cudd_RecursiveDeref(dd, prime);
lb = tmp;
}
::Cudd_RecursiveDeref(dd, lb);
return 1;
}
std::pair<Cudd, std::vector<BDD>> aig_to_bdd(Gia_Man_t *aig, int verbose)
{
uint32_t i, id;
Gia_Obj_t* obj;
Cudd bdd_mngr;
std::vector<BDD> nodes(Gia_ManObjNum(aig));
//bdd_mngr.AutodynEnable();
//bdd_mngr.AutodynEnable(CUDD_REORDER_EXACT);
printf("[i] Converting AIG to BDD\n");
Gia_ManForEachCiId(aig, id, i) {
nodes[id] = bdd_mngr.bddVar(i);
}
Gia_ManForEachAnd(aig, obj, i) {
const auto b1 = nodes[Gia_ObjFaninId0(obj, i)];
const auto c1 = Gia_ObjFaninC0(obj);
const auto b2 = nodes[Gia_ObjFaninId1(obj, i)];
const auto c2 = Gia_ObjFaninC1(obj);
nodes[i] = (c1 ? !b1 : b1) & (c2 ? !b2 : b2);
if (verbose) {
fprintf(stdout, "\rNode %4d / %4d", i, nodes.size());
fflush(stdout);
}
}
//bdd_mngr.ReduceHeap();
//bdd_mngr.ReduceHeap(CUDD_REORDER_EXACT);
if (verbose) {
fprintf(stdout, " Done\n");
}
/* Outputs */
std::vector<BDD> outputs;
Gia_ManForEachCo(aig, obj, i) {
const auto b = nodes[Gia_ObjFaninId0p(aig, obj)];
const auto c = Gia_ObjFaninC0(obj);
outputs.push_back(c ? !b : b);
test(bdd_mngr.getManager(), outputs.back().getNode());
fprintf(stdout, "[%d] ", i);
if (outputs.back().getNode() == NULL) {
fprintf(stdout, "empty DD.\n");
continue;
}
outputs.back().summary(Gia_ManCiNum(aig));
// outputs.back().PrintCover();
}
fprintf(stdout, " [Done]\n");
//bdd_mngr.AutodynDisable();
return std::make_pair(bdd_mngr, outputs);
}
} // namespace lsy
<|endoftext|>
|
<commit_before>// (C) Copyright 2013 Florian Plaza Oate
// Use, modification and distribution is subject to the MIT License (MIT)
// (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
#include "XsqConverter.hh"
#include <memory>
auto XsqConverter::convert(const fs::path& input_file, const fs::path& output_dir, const boost::optional<std::vector<std::string>>& prefixes_wanted) -> void
{
Xsq::XsqFile file(input_file.string());
const auto& used_tags_names = file.get_used_tags_names();
std::map<std::string, char*> qual_ofs_buffers;
std::map<std::string, char*> csfasta_ofs_buffers;
// Create buffers for latter use in qual and csfasta ofstreams
for(const auto& tag_name: used_tags_names)
{
qual_ofs_buffers[tag_name] = new char[BUFFERS_SIZE];
csfasta_ofs_buffers[tag_name] = new char[BUFFERS_SIZE];
}
const auto& libraries = prefixes_wanted ?
file.get_libraries_by_prefix(*prefixes_wanted) : file.get_libraries();
for(const auto& library: libraries)
{
// Create the library output directory
const fs::path& library_output_dir
= output_dir / fs::path(library.get_sample_name());
fs::create_directory(library_output_dir);
// Create and open csfasta and qval output files
std::map<std::string, std::unique_ptr<std::ofstream>> qual_ofs;
std::map<std::string, std::unique_ptr< std::ofstream>> csfasta_ofs;
for(const auto& tag_name: used_tags_names)
{
const std::string& library_output_filename =
file.get_path().stem().string() + '_' + library.get_complete_name() + '_' + tag_name;
const fs::path& output_qual_file_path =
library_output_dir / fs::path(library_output_filename + QUAL_FILE_EXT);
const fs::path& output_csfasta_file_path =
library_output_dir / fs::path(library_output_filename + CSFASTA_FILE_EXT);
// Create streams
qual_ofs[tag_name] = std::unique_ptr<std::ofstream>(new std::ofstream());
qual_ofs[tag_name]->open(output_qual_file_path.string().c_str());
// Make streams use buffers
qual_ofs[tag_name]->rdbuf()->pubsetbuf(qual_ofs_buffers[tag_name], BUFFERS_SIZE);
csfasta_ofs[tag_name] = std::unique_ptr<std::ofstream>(new std::ofstream(output_csfasta_file_path.string().c_str()));
qual_ofs[tag_name]->rdbuf()->pubsetbuf(csfasta_ofs_buffers[tag_name], BUFFERS_SIZE);
}
std::cout << "info: Extracting library " << library.get_complete_name() << ". Please wait..." << std::endl;
// Extract all reads of the library in csfasta and qval files
for(const auto& tile: library.get_tiles())
{
const std::string& tile_name = tile.get_name();
const Xsq::YxLocation& tile_yxLocation = tile.get_yxLocation();
for(const auto& tag: tile.get_tags())
{
const std::string& tag_name = tag.get_name();
convert_reads(
tag.get_reads(), *qual_ofs[tag_name], *csfasta_ofs[tag_name], tile_name, tile_yxLocation, tag_name, tag.get_start_nucleotide());
}
}
for(const auto& tag_name: used_tags_names)
{
qual_ofs[tag_name]->close();
csfasta_ofs[tag_name]->close();
}
}
for(const auto& tag_name: used_tags_names)
{
delete [] qual_ofs_buffers[tag_name];
delete [] csfasta_ofs_buffers[tag_name];
}
}
auto XsqConverter::convert_reads(const Xsq::Reads& reads, std::ofstream& qual_ofs, std::ofstream& csfasta_ofs, const std::string& tile_name, const Xsq::YxLocation& yxLocation, const std::string& tag_name, char start_nucleotide) -> void
{
unsigned nb_reads = reads.get_nb_reads();
unsigned reads_length = reads.get_reads_length();
for (unsigned read_id = 0; read_id < nb_reads; read_id++)
{
const auto& location =
yxLocation.get_location(read_id);
const std::string& read_header =
'>' + tile_name + '_' +
std::to_string(location.first) + '_' + std::to_string(location.second) + '_' +
tag_name + '\n';
qual_ofs << read_header;
csfasta_ofs << read_header;
csfasta_ofs << start_nucleotide;
// Hackish handmade loop unrolling.
// 3-4% performance boost on big xsq files
uint8_t* read_data = reads.get_read(read_id);
unsigned i;
for (i = 0; i <= reads_length-4; i += 4)
{
unsigned values = *(unsigned*)(read_data+i);
uint8_t value[4];
value[0] = values & 0xff;
value[1] = (values >> 8) & 0xff;
value[2] = (values >> 16) & 0xff;
value[3] = (values >> 24) & 0xff;
qual_ofs << qv_map[value[0]]
<< qv_map[value[1]]
<< qv_map[value[2]]
<< qv_map[value[3]];
csfasta_ofs << cs_map[value[0]]
<< cs_map[value[1]]
<< cs_map[value[2]]
<< cs_map[value[3]];
}
for (; i < reads_length; i++)
{
uint8_t value = read_data[i];
qual_ofs << qv_map[value];
csfasta_ofs << cs_map[value];
}
qual_ofs << '\n';
csfasta_ofs << '\n';
}
}
const std::string XsqConverter::QUAL_FILE_EXT = ".QV.qual";
const std::string XsqConverter::CSFASTA_FILE_EXT = ".csfasta";
// Map CallQV -> qv
//
const char* XsqConverter::qv_map[256] = {
"0 ","0 ","0 ","0 ","1 ","1 ","1 ","1 ","2 ","2 ","2 ","2 ","3 ","3 ","3 ","3 ",
"4 ","4 ","4 ","4 ","5 ","5 ","5 ","5 ","6 ","6 ","6 ","6 ","7 ","7 ","7 ","7 ",
"8 ","8 ","8 ","8 ","9 ","9 ","9 ","9 ","10 ","10 ","10 ","10 ","11 ","11 ","11 ","11 ",
"12 ","12 ","12 ","12 ","13 ","13 ","13 ","13 ","14 ","14 ","14 ","14 ","15 ","15 ","15 ","15 ",
"16 ","16 ","16 ","16 ","17 ","17 ","17 ","17 ","18 ","18 ","18 ","18 ","19 ","19 ","19 ","19 ",
"20 ","20 ","20 ","20 ","21 ","21 ","21 ","21 ","22 ","22 ","22 ","22 ","23 ","23 ","23 ","23 ",
"24 ","24 ","24 ","24 ","25 ","25 ","25 ","25 ","26 ","26 ","26 ","26 ","27 ","27 ","27 ","27 ",
"28 ","28 ","28 ","28 ","29 ","29 ","29 ","29 ","30 ","30 ","30 ","30 ","31 ","31 ","31 ","31 ",
"32 ","32 ","32 ","32 ","33 ","33 ","33 ","33 ","34 ","34 ","34 ","34 ","35 ","35 ","35 ","35 ",
"36 ","36 ","36 ","36 ","37 ","37 ","37 ","37 ","38 ","38 ","38 ","38 ","39 ","39 ","39 ","39 ",
"40 ","40 ","40 ","40 ","41 ","41 ","41 ","41 ","42 ","42 ","42 ","42 ","43 ","43 ","43 ","43 ",
"44 ","44 ","44 ","44 ","45 ","45 ","45 ","45 ","46 ","46 ","46 ","46 ","47 ","47 ","47 ","47 ",
"48 ","48 ","48 ","48 ","49 ","49 ","49 ","49 ","50 ","50 ","50 ","50 ","51 ","51 ","51 ","51 ",
"52 ","52 ","52 ","52 ","53 ","53 ","53 ","53 ","54 ","54 ","54 ","54 ","55 ","55 ","55 ","55 ",
"56 ","56 ","56 ","56 ","57 ","57 ","57 ","57 ","58 ","58 ","58 ","58 ","59 ","59 ","59 ","59 ",
"60 ","60 ","60 ","60 ","61 ","61 ","61 ","61 ","62 ","62 ","62 ","62 ","63 ","63 ","63 ","63 "
};
const char XsqConverter::cs_map[256] = {
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '.', '.', '.', '.'
};
// 1 MB
const unsigned XsqConverter::BUFFERS_SIZE = 1 << 20;<commit_msg>Replace raw pointers by smart unique_ptr objects.<commit_after>// (C) Copyright 2013 Florian Plaza Oate
// Use, modification and distribution is subject to the MIT License (MIT)
// (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
#include "XsqConverter.hh"
#include <memory>
auto XsqConverter::convert(const fs::path& input_file, const fs::path& output_dir, const boost::optional<std::vector<std::string>>& prefixes_wanted) -> void
{
Xsq::XsqFile file(input_file.string());
const auto& used_tags_names = file.get_used_tags_names();
std::map<std::string, char*> qual_ofs_buffers;
std::map<std::string, char*> csfasta_ofs_buffers;
// Create buffers for latter use in qual and csfasta ofstreams
for(const auto& tag_name: used_tags_names)
{
qual_ofs_buffers[tag_name] = new char[BUFFERS_SIZE];
csfasta_ofs_buffers[tag_name] = new char[BUFFERS_SIZE];
}
const auto& libraries = prefixes_wanted ?
file.get_libraries_by_prefix(*prefixes_wanted) : file.get_libraries();
for(const auto& library: libraries)
{
// Create the library output directory
const fs::path& library_output_dir
= output_dir / fs::path(library.get_sample_name());
fs::create_directory(library_output_dir);
// Create and open csfasta and qval output files
std::map<std::string, std::unique_ptr<std::ofstream>> qual_ofs;
std::map<std::string, std::unique_ptr< std::ofstream>> csfasta_ofs;
for(const auto& tag_name: used_tags_names)
{
const std::string& library_output_filename =
file.get_path().stem().string() + '_' + library.get_complete_name() + '_' + tag_name;
const fs::path& output_qual_file_path =
library_output_dir / fs::path(library_output_filename + QUAL_FILE_EXT);
const fs::path& output_csfasta_file_path =
library_output_dir / fs::path(library_output_filename + CSFASTA_FILE_EXT);
// Create streams
qual_ofs[tag_name] = std::unique_ptr<std::ofstream>(new std::ofstream());
qual_ofs[tag_name]->open(output_qual_file_path.string().c_str());
csfasta_ofs[tag_name] = std::unique_ptr<std::ofstream>(new std::ofstream());
csfasta_ofs[tag_name]->open(output_csfasta_file_path.string().c_str());
// Make streams use buffers
qual_ofs[tag_name]->rdbuf()->pubsetbuf(qual_ofs_buffers[tag_name], BUFFERS_SIZE);
qual_ofs[tag_name]->rdbuf()->pubsetbuf(csfasta_ofs_buffers[tag_name], BUFFERS_SIZE);
}
std::cout << "info: Extracting library " << library.get_complete_name() << ". Please wait..." << std::endl;
// Extract all reads of the library in csfasta and qval files
for(const auto& tile: library.get_tiles())
{
const std::string& tile_name = tile.get_name();
const Xsq::YxLocation& tile_yxLocation = tile.get_yxLocation();
for(const auto& tag: tile.get_tags())
{
const std::string& tag_name = tag.get_name();
convert_reads(
tag.get_reads(), *qual_ofs[tag_name], *csfasta_ofs[tag_name], tile_name, tile_yxLocation, tag_name, tag.get_start_nucleotide());
}
}
for(const auto& tag_name: used_tags_names)
{
qual_ofs[tag_name]->close();
csfasta_ofs[tag_name]->close();
}
}
for(const auto& tag_name: used_tags_names)
{
delete [] qual_ofs_buffers[tag_name];
delete [] csfasta_ofs_buffers[tag_name];
}
}
auto XsqConverter::convert_reads(const Xsq::Reads& reads, std::ofstream& qual_ofs, std::ofstream& csfasta_ofs, const std::string& tile_name, const Xsq::YxLocation& yxLocation, const std::string& tag_name, char start_nucleotide) -> void
{
unsigned nb_reads = reads.get_nb_reads();
unsigned reads_length = reads.get_reads_length();
for (unsigned read_id = 0; read_id < nb_reads; read_id++)
{
const auto& location =
yxLocation.get_location(read_id);
const std::string& read_header =
'>' + tile_name + '_' +
std::to_string(location.first) + '_' + std::to_string(location.second) + '_' +
tag_name + '\n';
qual_ofs << read_header;
csfasta_ofs << read_header;
csfasta_ofs << start_nucleotide;
// Hackish handmade loop unrolling.
// 3-4% performance boost on big xsq files
uint8_t* read_data = reads.get_read(read_id);
unsigned i;
for (i = 0; i <= reads_length-4; i += 4)
{
unsigned values = *(unsigned*)(read_data+i);
uint8_t value[4];
value[0] = values & 0xff;
value[1] = (values >> 8) & 0xff;
value[2] = (values >> 16) & 0xff;
value[3] = (values >> 24) & 0xff;
qual_ofs << qv_map[value[0]]
<< qv_map[value[1]]
<< qv_map[value[2]]
<< qv_map[value[3]];
csfasta_ofs << cs_map[value[0]]
<< cs_map[value[1]]
<< cs_map[value[2]]
<< cs_map[value[3]];
}
for (; i < reads_length; i++)
{
uint8_t value = read_data[i];
qual_ofs << qv_map[value];
csfasta_ofs << cs_map[value];
}
qual_ofs << '\n';
csfasta_ofs << '\n';
}
}
const std::string XsqConverter::QUAL_FILE_EXT = ".QV.qual";
const std::string XsqConverter::CSFASTA_FILE_EXT = ".csfasta";
// Map CallQV -> qv
//
const char* XsqConverter::qv_map[256] = {
"0 ","0 ","0 ","0 ","1 ","1 ","1 ","1 ","2 ","2 ","2 ","2 ","3 ","3 ","3 ","3 ",
"4 ","4 ","4 ","4 ","5 ","5 ","5 ","5 ","6 ","6 ","6 ","6 ","7 ","7 ","7 ","7 ",
"8 ","8 ","8 ","8 ","9 ","9 ","9 ","9 ","10 ","10 ","10 ","10 ","11 ","11 ","11 ","11 ",
"12 ","12 ","12 ","12 ","13 ","13 ","13 ","13 ","14 ","14 ","14 ","14 ","15 ","15 ","15 ","15 ",
"16 ","16 ","16 ","16 ","17 ","17 ","17 ","17 ","18 ","18 ","18 ","18 ","19 ","19 ","19 ","19 ",
"20 ","20 ","20 ","20 ","21 ","21 ","21 ","21 ","22 ","22 ","22 ","22 ","23 ","23 ","23 ","23 ",
"24 ","24 ","24 ","24 ","25 ","25 ","25 ","25 ","26 ","26 ","26 ","26 ","27 ","27 ","27 ","27 ",
"28 ","28 ","28 ","28 ","29 ","29 ","29 ","29 ","30 ","30 ","30 ","30 ","31 ","31 ","31 ","31 ",
"32 ","32 ","32 ","32 ","33 ","33 ","33 ","33 ","34 ","34 ","34 ","34 ","35 ","35 ","35 ","35 ",
"36 ","36 ","36 ","36 ","37 ","37 ","37 ","37 ","38 ","38 ","38 ","38 ","39 ","39 ","39 ","39 ",
"40 ","40 ","40 ","40 ","41 ","41 ","41 ","41 ","42 ","42 ","42 ","42 ","43 ","43 ","43 ","43 ",
"44 ","44 ","44 ","44 ","45 ","45 ","45 ","45 ","46 ","46 ","46 ","46 ","47 ","47 ","47 ","47 ",
"48 ","48 ","48 ","48 ","49 ","49 ","49 ","49 ","50 ","50 ","50 ","50 ","51 ","51 ","51 ","51 ",
"52 ","52 ","52 ","52 ","53 ","53 ","53 ","53 ","54 ","54 ","54 ","54 ","55 ","55 ","55 ","55 ",
"56 ","56 ","56 ","56 ","57 ","57 ","57 ","57 ","58 ","58 ","58 ","58 ","59 ","59 ","59 ","59 ",
"60 ","60 ","60 ","60 ","61 ","61 ","61 ","61 ","62 ","62 ","62 ","62 ","63 ","63 ","63 ","63 "
};
const char XsqConverter::cs_map[256] = {
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3',
'0', '1', '2', '3', '0', '1', '2', '3', '0', '1', '2', '3', '.', '.', '.', '.'
};
// 1 MB
const unsigned XsqConverter::BUFFERS_SIZE = 1 << 20;<|endoftext|>
|
<commit_before>#ifdef STAN_OPENCL
#undef STAN_OPENCL
#include <test\unit\math\rev\mat\prob\normal_id_glm_lpdf_test.cpp>
#endif<commit_msg>fix cpplint<commit_after>#ifdef STAN_OPENCL
#undef STAN_OPENCL
#include <test\unit\math\rev\mat\prob\normal_id_glm_lpdf_test.cpp>
#endif
<|endoftext|>
|
<commit_before>#include <QDBusReply>
#include <QMenu>
#include <QMessageBox>
#include "iconproducer.h"
#include "agentadaptor.h"
#include "dbus_types.h"
#include "controller.h"
Controller::Controller() :
manager(),
agent(),
model(),
servicesWindow(),
trayIcon(),
connectionTypesItem("Connection types"),
servicesItem("Services")
{
QDBusObjectPath agentPath("/org/lxqt/lxqt_connman_agent");
new AgentAdaptor(&agent);
QDBusConnection::systemBus().registerObject(agentPath.path(), &agent);
manager.call("RegisterAgent", QVariant::fromValue(agentPath));
model.insertRow(0, &connectionTypesItem);
model.insertRow(1, &servicesItem);
connect(&manager,
SIGNAL(TechnologyAdded(const QDBusObjectPath&, const QVariantMap&)),
SLOT(onTechnologyAdded(const QDBusObjectPath&, const QVariantMap&)));
connect(&manager,
SIGNAL(TechnologyRemoved(const QDBusObjectPath&)),
SLOT(onTechnologyRemoved(const QDBusObjectPath&)));
connect(&manager,
SIGNAL(ServicesChanged(ObjectPropertiesList, const QList<QDBusObjectPath>&)),
SLOT(onServicesUpdated(const ObjectPropertiesList&, const QList<QDBusObjectPath>&)));
connect(&manager, SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)), SLOT(updateTrayIcon()));
connect(&IconProducer::instance(), SIGNAL(iconsChanged()), &model, SIGNAL(layoutChanged()));
connect(&IconProducer::instance(), SIGNAL(iconsChanged()), SLOT(updateTrayIcon()));
connect(&servicesWindow, SIGNAL(activated(const QModelIndex&)), SLOT(onItemActivated(const QModelIndex&)));
QDBusReply<ObjectPropertiesList> GetTechnologiesReply = manager.call("GetTechnologies");;
for (ObjectProperties op : GetTechnologiesReply.value()) {
onTechnologyAdded(op.first, op.second);
}
QDBusReply<ObjectPropertiesList> GetServicesReply = manager.call("GetServices");
onServicesUpdated(GetServicesReply.value(), QList<QDBusObjectPath>());
servicesWindow.setModel(&model);
QMenu *menu = new QMenu();
menu->addAction(tr("Services..."), &servicesWindow, SLOT(show()));
menu->addAction(QIcon::fromTheme("help-about"), tr("About"), this, SLOT(about()));
menu->addAction(QIcon::fromTheme("application-exit"), tr("Quit"), qApp, SLOT(quit()));
connect(&trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
SLOT(onTrayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon.setContextMenu(menu);
updateTrayIcon();
trayIcon.show();
}
void Controller::updateTechnologyPresentationData(QStandardItem* item)
{
ConnmanObject& technology = *connmanObject(item);
QString type = technology["Type"].toString();
bool powered = technology["Powered"].toBool();
QString name = technology["Name"].toString();
item->setData(name, Qt::DisplayRole);
QIcon icon;
if (type == "ethernet") {
icon = IconProducer::instance().wiredConnected();
}
else if (type == "wifi") {
icon = IconProducer::instance().wireless(80);
}
else {
icon = IconProducer::instance().blanc();
}
item->setData(icon, Qt::DecorationRole);
QFont font;
QColor color;
if (! powered) {
font.setItalic(true);
color = QColor("lightgrey");
}
item->setData(font, Qt::FontRole);
item->setData(color, Qt::ForegroundRole);
}
void Controller::updateServicePresentationData(QStandardItem* item)
{
ConnmanObject& service = *connmanObject(item);
QString state = service["State"].toString();
QString type = service["Type"].toString();
QString displayData = service["Name"].toString();
int strength = service["Strength"].toInt();
if (state == "online") {
displayData = displayData + " " + QChar(0x2713);
}
else if (state != "idle" && state != "ready"){
displayData = displayData + " (" + state + ")";
}
item->setData(displayData, Qt::DisplayRole);
QFont font;
if (state == "ready" || state == "online") {
font.setBold(true);
}
item->setData(font, Qt::FontRole);
QIcon icon;
if (type == "wifi") {
icon = IconProducer::instance().wireless(strength);
}
else {
// TODO: This means that everything else than wifi is depicted as wired. We should
// do something for bluetooth, p2p ..
icon = state == "offline" ? IconProducer::instance().disconnected() : IconProducer::instance().wiredConnected();
}
item->setData(icon, Qt::DecorationRole);
}
ConnmanObject* Controller::connmanObject(QStandardItem* item)
{
return item->data(Qt::UserRole).value<ConnmanObject*>();
}
void Controller::remove(const QString& path)
{
QStandardItem *item = items.take(path);
connmanObject(item)->deleteLater();
item->parent()->removeRow(item->row());
}
void Controller::onTechnologyAdded(const QDBusObjectPath& path, const QVariantMap& properties)
{
QStandardItem* item = new QStandardItem();
ConnmanObject* technology = new ConnmanObject(path.path(), "net.connman.Technology", properties);
connect(technology, SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),
SLOT(onTechnologyPropertyChanged(const QString&, const QDBusVariant&)));
item->setData(QVariant::fromValue(technology), Qt::UserRole);
updateTechnologyPresentationData(item);
item->setEditable(false);
items[path.path()] = item;
connectionTypesItem.appendRow(QList<QStandardItem*>({item}));
}
void Controller::onTechnologyRemoved(const QDBusObjectPath& path)
{
remove(path.path());
}
void Controller::onServicesUpdated(ObjectPropertiesList services, const QList<QDBusObjectPath>& removed)
{
for (const auto& path : removed) {
remove(path.path());
}
QList<QStandardItem*> newItems;
int count = 0;
for (const auto& op : services) {
QString path = op.first.path();
QVariantMap properties = op.second;
if ((!properties.contains("Name")) || properties["Name"].toString().isEmpty()) {
// This would be a hidden service. We leave them out as we don't (yet) have
// functionality to handle them
continue;
}
count++;
QStandardItem* item = items[path];
if (item == 0) {
item = new QStandardItem();
ConnmanObject* service = new ConnmanObject(path, "net.connman.Service", properties);
connect(service, SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),
SLOT(onServicePropertyChanged(const QString&, const QDBusVariant&)));
item->setData(QVariant::fromValue(service), Qt::UserRole);
updateServicePresentationData(item);
item->setEditable(false);
items[path] = item;
newItems.append(item);
}
item->setData(count, Qt::UserRole + 1);
}
if (newItems.size() > 0) {
servicesItem.appendRows(newItems);
}
}
void Controller::onTechnologyPropertyChanged(const QString& name, const QDBusVariant& newValue)
{
QString path = dynamic_cast<ConnmanObject*>(sender())->path();
if (items.contains(path)) {
connmanObject(items[path])->insert(name, newValue.variant());
updateTechnologyPresentationData(items[path]);
}
}
void Controller::onServicePropertyChanged(const QString& name, const QDBusVariant& newValue)
{
QString path = dynamic_cast<ConnmanObject*>(sender())->path();
if (items.contains(path)) {
connmanObject(items[path])->insert(name, newValue.variant());
updateServicePresentationData(items[path]);
}
}
void Controller::onItemActivated(const QModelIndex& index)
{
ConnmanObject* connmanObject = index.data(Qt::UserRole).value<ConnmanObject*>();
if (connmanObject != 0) {
if (connmanObject->path().startsWith("/net/connman/technology")) { // TODO Can we trust this?
bool newPowered = !(connmanObject->value("Powered").toBool());
connmanObject->asyncCall("SetProperty", QVariant("Powered"), QVariant::fromValue(QDBusVariant(newPowered)));
}
else if (connmanObject->path().startsWith("/net/connman/service")) { // ..do
QString state = connmanObject->value("State").toString();
if (state == "idle" || state == "failure") {
connmanObject->asyncCall("Connect");
}
else if (state == "association" || state == "configuration" || state == "ready" || state == "online") {
connmanObject->asyncCall("Disconnect");
}
}
}
}
void Controller::updateTrayIcon()
{
for (QStandardItem* item : items.values()) {
ConnmanObject* obj = connmanObject(item);
if (obj->path().startsWith("/net/connman/service")) {
QString state = obj->value("State").toString();
int signalStrength = obj->value("Strength").toInt();
if (state == "ready" || state == "online") {
if (signalStrength > 0) {
trayIcon.setIcon(IconProducer::instance().wireless(signalStrength));
}
else {
trayIcon.setIcon(IconProducer::instance().wiredConnected());
}
return;
}
}
}
trayIcon.setIcon(IconProducer::instance().disconnected());
}
void Controller::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
servicesWindow.show();
}
void Controller::about()
{
QMessageBox::about(0,
tr("About"),
tr( "<p>"
" <b>LXQt Connman Client</b>"
"</p>"
"<p>"
"Copyright 2014, 2015, 2016"
"</p>"
"<p>"
"Christian Surlykke"
"</p>"
));
}
<commit_msg>Show proper service names in agent dialog<commit_after>#include <QDBusReply>
#include <QMenu>
#include <QMessageBox>
#include "iconproducer.h"
#include "agentadaptor.h"
#include "dbus_types.h"
#include "controller.h"
Controller::Controller() :
manager(),
agent(),
model(),
servicesWindow(),
trayIcon(),
connectionTypesItem("Connection types"),
servicesItem("Services")
{
QDBusObjectPath agentPath("/org/lxqt/lxqt_connman_agent");
new AgentAdaptor(&agent);
QDBusConnection::systemBus().registerObject(agentPath.path(), &agent);
manager.call("RegisterAgent", QVariant::fromValue(agentPath));
model.insertRow(0, &connectionTypesItem);
model.insertRow(1, &servicesItem);
connect(&manager,
SIGNAL(TechnologyAdded(const QDBusObjectPath&, const QVariantMap&)),
SLOT(onTechnologyAdded(const QDBusObjectPath&, const QVariantMap&)));
connect(&manager,
SIGNAL(TechnologyRemoved(const QDBusObjectPath&)),
SLOT(onTechnologyRemoved(const QDBusObjectPath&)));
connect(&manager,
SIGNAL(ServicesChanged(ObjectPropertiesList, const QList<QDBusObjectPath>&)),
SLOT(onServicesUpdated(const ObjectPropertiesList&, const QList<QDBusObjectPath>&)));
connect(&manager, SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)), SLOT(updateTrayIcon()));
connect(&IconProducer::instance(), SIGNAL(iconsChanged()), &model, SIGNAL(layoutChanged()));
connect(&IconProducer::instance(), SIGNAL(iconsChanged()), SLOT(updateTrayIcon()));
connect(&servicesWindow, SIGNAL(activated(const QModelIndex&)), SLOT(onItemActivated(const QModelIndex&)));
QDBusReply<ObjectPropertiesList> GetTechnologiesReply = manager.call("GetTechnologies");;
for (ObjectProperties op : GetTechnologiesReply.value()) {
onTechnologyAdded(op.first, op.second);
}
QDBusReply<ObjectPropertiesList> GetServicesReply = manager.call("GetServices");
onServicesUpdated(GetServicesReply.value(), QList<QDBusObjectPath>());
servicesWindow.setModel(&model);
QMenu *menu = new QMenu();
menu->addAction(tr("Services..."), &servicesWindow, SLOT(show()));
menu->addAction(QIcon::fromTheme("help-about"), tr("About"), this, SLOT(about()));
menu->addAction(QIcon::fromTheme("application-exit"), tr("Quit"), qApp, SLOT(quit()));
connect(&trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
SLOT(onTrayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon.setContextMenu(menu);
updateTrayIcon();
trayIcon.show();
}
void Controller::updateTechnologyPresentationData(QStandardItem* item)
{
ConnmanObject& technology = *connmanObject(item);
QString type = technology["Type"].toString();
bool powered = technology["Powered"].toBool();
QString name = technology["Name"].toString();
item->setData(name, Qt::DisplayRole);
QIcon icon;
if (type == "ethernet") {
icon = IconProducer::instance().wiredConnected();
}
else if (type == "wifi") {
icon = IconProducer::instance().wireless(80);
}
else {
icon = IconProducer::instance().blanc();
}
item->setData(icon, Qt::DecorationRole);
QFont font;
QColor color;
if (! powered) {
font.setItalic(true);
color = QColor("lightgrey");
}
item->setData(font, Qt::FontRole);
item->setData(color, Qt::ForegroundRole);
}
void Controller::updateServicePresentationData(QStandardItem* item)
{
ConnmanObject& service = *connmanObject(item);
QString state = service["State"].toString();
QString type = service["Type"].toString();
QString displayData = service["Name"].toString();
int strength = service["Strength"].toInt();
if (state == "online") {
displayData = displayData + " " + QChar(0x2713);
}
else if (state != "idle" && state != "ready"){
displayData = displayData + " (" + state + ")";
}
item->setData(displayData, Qt::DisplayRole);
QFont font;
if (state == "ready" || state == "online") {
font.setBold(true);
}
item->setData(font, Qt::FontRole);
QIcon icon;
if (type == "wifi") {
icon = IconProducer::instance().wireless(strength);
}
else {
// TODO: This means that everything else than wifi is depicted as wired. We should
// do something for bluetooth, p2p ..
icon = state == "offline" ? IconProducer::instance().disconnected() : IconProducer::instance().wiredConnected();
}
item->setData(icon, Qt::DecorationRole);
agent.setEntityName(service.path(), service["Name"].toString());
}
ConnmanObject* Controller::connmanObject(QStandardItem* item)
{
return item->data(Qt::UserRole).value<ConnmanObject*>();
}
void Controller::remove(const QString& path)
{
QStandardItem *item = items.take(path);
connmanObject(item)->deleteLater();
item->parent()->removeRow(item->row());
}
void Controller::onTechnologyAdded(const QDBusObjectPath& path, const QVariantMap& properties)
{
QStandardItem* item = new QStandardItem();
ConnmanObject* technology = new ConnmanObject(path.path(), "net.connman.Technology", properties);
connect(technology, SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),
SLOT(onTechnologyPropertyChanged(const QString&, const QDBusVariant&)));
item->setData(QVariant::fromValue(technology), Qt::UserRole);
updateTechnologyPresentationData(item);
item->setEditable(false);
items[path.path()] = item;
connectionTypesItem.appendRow(QList<QStandardItem*>({item}));
}
void Controller::onTechnologyRemoved(const QDBusObjectPath& path)
{
remove(path.path());
}
void Controller::onServicesUpdated(ObjectPropertiesList services, const QList<QDBusObjectPath>& removed)
{
for (const auto& path : removed) {
remove(path.path());
}
QList<QStandardItem*> newItems;
int count = 0;
for (const auto& op : services) {
QString path = op.first.path();
QVariantMap properties = op.second;
if ((!properties.contains("Name")) || properties["Name"].toString().isEmpty()) {
// This would be a hidden service. We leave them out as we don't (yet) have
// functionality to handle them
continue;
}
count++;
QStandardItem* item = items[path];
if (item == 0) {
item = new QStandardItem();
ConnmanObject* service = new ConnmanObject(path, "net.connman.Service", properties);
connect(service, SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),
SLOT(onServicePropertyChanged(const QString&, const QDBusVariant&)));
item->setData(QVariant::fromValue(service), Qt::UserRole);
updateServicePresentationData(item);
item->setEditable(false);
items[path] = item;
newItems.append(item);
}
item->setData(count, Qt::UserRole + 1);
}
if (newItems.size() > 0) {
servicesItem.appendRows(newItems);
}
}
void Controller::onTechnologyPropertyChanged(const QString& name, const QDBusVariant& newValue)
{
QString path = dynamic_cast<ConnmanObject*>(sender())->path();
if (items.contains(path)) {
connmanObject(items[path])->insert(name, newValue.variant());
updateTechnologyPresentationData(items[path]);
}
}
void Controller::onServicePropertyChanged(const QString& name, const QDBusVariant& newValue)
{
QString path = dynamic_cast<ConnmanObject*>(sender())->path();
if (items.contains(path)) {
connmanObject(items[path])->insert(name, newValue.variant());
updateServicePresentationData(items[path]);
}
}
void Controller::onItemActivated(const QModelIndex& index)
{
ConnmanObject* connmanObject = index.data(Qt::UserRole).value<ConnmanObject*>();
if (connmanObject != 0) {
if (connmanObject->path().startsWith("/net/connman/technology")) { // TODO Can we trust this?
bool newPowered = !(connmanObject->value("Powered").toBool());
connmanObject->asyncCall("SetProperty", QVariant("Powered"), QVariant::fromValue(QDBusVariant(newPowered)));
}
else if (connmanObject->path().startsWith("/net/connman/service")) { // ..do
QString state = connmanObject->value("State").toString();
if (state == "idle" || state == "failure") {
connmanObject->asyncCall("Connect");
}
else if (state == "association" || state == "configuration" || state == "ready" || state == "online") {
connmanObject->asyncCall("Disconnect");
}
}
}
}
void Controller::updateTrayIcon()
{
for (QStandardItem* item : items.values()) {
ConnmanObject* obj = connmanObject(item);
if (obj->path().startsWith("/net/connman/service")) {
QString state = obj->value("State").toString();
int signalStrength = obj->value("Strength").toInt();
if (state == "ready" || state == "online") {
if (signalStrength > 0) {
trayIcon.setIcon(IconProducer::instance().wireless(signalStrength));
}
else {
trayIcon.setIcon(IconProducer::instance().wiredConnected());
}
return;
}
}
}
trayIcon.setIcon(IconProducer::instance().disconnected());
}
void Controller::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
servicesWindow.show();
}
void Controller::about()
{
QMessageBox::about(0,
tr("About"),
tr( "<p>"
" <b>LXQt Connman Client</b>"
"</p>"
"<p>"
"Copyright 2014, 2015, 2016"
"</p>"
"<p>"
"Christian Surlykke"
"</p>"
));
}
<|endoftext|>
|
<commit_before>/*
* Created on: 10 Oct 2017
* Author: Yiming Yang
*
* Copyright (c) 2017, University of Edinburgh
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <ompl/util/RandomNumbers.h>
#include <ompl_solver/ompl_solver.h>
namespace exotica
{
template <class ProblemType>
OMPLsolver<ProblemType>::OMPLsolver() : multiQuery(false)
{
}
template <class ProblemType>
OMPLsolver<ProblemType>::~OMPLsolver()
{
}
template <class ProblemType>
void OMPLsolver<ProblemType>::specifyProblem(PlanningProblem_ptr pointer)
{
MotionSolver::specifyProblem(pointer);
prob_ = std::static_pointer_cast<ProblemType>(pointer);
if (prob_->getScene()->getBaseType() == BASE_TYPE::FIXED)
state_space_.reset(new OMPLRNStateSpace(prob_, init_));
else if (prob_->getScene()->getBaseType() == BASE_TYPE::PLANAR)
state_space_.reset(new OMPLSE2RNStateSpace(prob_, init_));
else if (prob_->getScene()->getBaseType() == BASE_TYPE::FLOATING)
state_space_.reset(new OMPLSE3RNStateSpace(prob_, init_));
else
throw_named("Unsupported base type " << prob_->getScene()->getBaseType());
ompl_simple_setup_.reset(new ompl::geometric::SimpleSetup(state_space_));
ompl_simple_setup_->setStateValidityChecker(ompl::base::StateValidityCheckerPtr(new OMPLStateValidityChecker(ompl_simple_setup_->getSpaceInformation(), prob_)));
ompl_simple_setup_->setPlannerAllocator(boost::bind(planner_allocator_, _1, algorithm_));
if (init_.Projection.rows() > 0)
{
std::vector<int> project_vars(init_.Projection.rows());
for (int i = 0; i < init_.Projection.rows(); i++)
{
project_vars[i] = (int)init_.Projection(i);
if (project_vars[i] < 0 || project_vars[i] >= prob_->N) throw_named("Invalid projection index! " << project_vars[i]);
}
if (prob_->getScene()->getBaseType() == BASE_TYPE::FIXED)
ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLRNProjection(state_space_, project_vars)));
else if (prob_->getScene()->getBaseType() == BASE_TYPE::PLANAR)
ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLSE2RNProjection(state_space_, project_vars)));
else if (prob_->getScene()->getBaseType() == BASE_TYPE::FLOATING)
ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLSE3RNProjection(state_space_, project_vars)));
}
ompl_simple_setup_->getSpaceInformation()->setup();
ompl_simple_setup_->setup();
if (ompl_simple_setup_->getPlanner()->params().hasParam("range"))
ompl_simple_setup_->getPlanner()->params().setParam("range", init_.Range);
if (ompl_simple_setup_->getPlanner()->params().hasParam("goal_bias"))
ompl_simple_setup_->getPlanner()->params().setParam("goal_bias", init_.GoalBias);
if (init_.RandomSeed != -1)
{
HIGHLIGHT_NAMED(algorithm_, "Setting random seed to " << init_.RandomSeed);
ompl::RNG::setSeed(init_.RandomSeed);
}
}
template <class ProblemType>
int OMPLsolver<ProblemType>::getRandomSeed()
{
return ompl::RNG::getSeed();
}
template <class ProblemType>
void OMPLsolver<ProblemType>::preSolve()
{
// clear previously computed solutions
if (!multiQuery)
{
ompl_simple_setup_->getProblemDefinition()->clearSolutionPaths();
const ompl::base::PlannerPtr planner = ompl_simple_setup_->getPlanner();
if (planner)
planner->clear();
ompl_simple_setup_->getPlanner()->setProblemDefinition(ompl_simple_setup_->getProblemDefinition());
}
ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->resetMotionCounter();
}
template <class ProblemType>
void OMPLsolver<ProblemType>::postSolve()
{
ompl_simple_setup_->clearStartStates();
int v = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getValidMotionCount();
int iv = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getInvalidMotionCount();
CONSOLE_BRIDGE_logDebug("There were %d valid motions and %d invalid motions.", v, iv);
if (ompl_simple_setup_->getProblemDefinition()->hasApproximateSolution())
CONSOLE_BRIDGE_logWarn("Computed solution is approximate");
}
template <class ProblemType>
void OMPLsolver<ProblemType>::setGoalState(const Eigen::VectorXd &qT, const double eps)
{
ompl::base::ScopedState<> gs(state_space_);
state_space_->as<OMPLStateSpace>()->ExoticaToOMPLState(qT, gs.get());
if (!ompl_simple_setup_->getStateValidityChecker()->isValid(gs.get()))
{
throw_named("Goal state is not valid!");
}
if (!ompl_simple_setup_->getSpaceInformation()->satisfiesBounds(gs.get()))
{
state_space_->as<OMPLStateSpace>()->stateDebug(qT);
// Debug state and bounds
std::string out_of_bounds_joint_ids = "";
for (int i = 0; i < qT.rows(); i++)
if (qT(i) < prob_->getBounds()[i] || qT(i) > prob_->getBounds()[i + qT.rows()])
out_of_bounds_joint_ids += "[j" + std::to_string(i) + "=" + std::to_string(qT(i)) + ", ll=" + std::to_string(prob_->getBounds()[i]) + ", ul=" + std::to_string(prob_->getBounds()[i + qT.rows()]) + "]\n";
throw_named("Invalid goal state [Invalid joint bounds for joint indices: \n"
<< out_of_bounds_joint_ids << "]");
}
ompl_simple_setup_->setGoalState(gs, eps);
}
template <class ProblemType>
void OMPLsolver<ProblemType>::getPath(Eigen::MatrixXd &traj, ompl::base::PlannerTerminationCondition &ptc)
{
ompl::geometric::PathSimplifierPtr psf_ = ompl_simple_setup_->getPathSimplifier();
const ompl::base::SpaceInformationPtr &si = ompl_simple_setup_->getSpaceInformation();
ompl::geometric::PathGeometric pg = ompl_simple_setup_->getSolutionPath();
if (init_.Smooth)
{
bool tryMore = true;
int times = 0;
while (init_.ReduceVertices && times < init_.SimplifyTryCnt && tryMore && ptc == false)
{
pg.interpolate(init_.SimplifyInterpolationLength);
tryMore = psf_->reduceVertices(pg, 0, 0, init_.RangeRatio);
times++;
}
if (init_.ShortcutPath && si->getStateSpace()->isMetricSpace())
{
times = 0;
while (times < init_.SimplifyTryCnt && tryMore && ptc == false)
{
pg.interpolate(init_.SimplifyInterpolationLength);
tryMore = psf_->shortcutPath(pg, 0, 0, init_.RangeRatio, init_.SnapToVertex);
times++;
}
}
}
std::vector<ompl::base::State *> &states = pg.getStates();
unsigned int length = 0;
if(init_.FinalInterpolationLength > 3)
length = init_.FinalInterpolationLength;
else
{
const int n1 = states.size() - 1;
for (int i = 0; i < n1; ++i)
length += si->getStateSpace()->validSegmentCount(states[i], states[i + 1]);
}
pg.interpolate(int(length * init_.SmoothnessFactor));
traj.resize(pg.getStateCount(), prob_->getSpaceDim());
Eigen::VectorXd tmp(prob_->getSpaceDim());
for (int i = 0; i < (int)pg.getStateCount(); ++i)
{
state_space_->as<OMPLStateSpace>()->OMPLToExoticaState(pg.getState(i), tmp);
traj.row(i) = tmp;
}
}
template <class ProblemType>
void OMPLsolver<ProblemType>::Solve(Eigen::MatrixXd &solution)
{
Eigen::VectorXd q0 = prob_->applyStartState();
setGoalState(prob_->getGoalState(), init_.Epsilon);
ompl::base::ScopedState<> ompl_start_state(state_space_);
state_space_->as<OMPLStateSpace>()->ExoticaToOMPLState(q0, ompl_start_state.get());
ompl_simple_setup_->setStartState(ompl_start_state);
preSolve();
ompl::time::point start = ompl::time::now();
ompl::base::PlannerTerminationCondition ptc = ompl::base::timedPlannerTerminationCondition(init_.Timeout - ompl::time::seconds(ompl::time::now() - start));
if (ompl_simple_setup_->solve(ptc) == ompl::base::PlannerStatus::EXACT_SOLUTION && ompl_simple_setup_->haveSolutionPath())
{
getPath(solution, ptc);
}
postSolve();
}
template class OMPLsolver<SamplingProblem>;
}
<commit_msg>[ompl_solver] Apply formatting<commit_after>/*
* Created on: 10 Oct 2017
* Author: Yiming Yang
*
* Copyright (c) 2017, University of Edinburgh
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <ompl/util/RandomNumbers.h>
#include <ompl_solver/ompl_solver.h>
namespace exotica
{
template <class ProblemType>
OMPLsolver<ProblemType>::OMPLsolver() : multiQuery(false)
{
}
template <class ProblemType>
OMPLsolver<ProblemType>::~OMPLsolver()
{
}
template <class ProblemType>
void OMPLsolver<ProblemType>::specifyProblem(PlanningProblem_ptr pointer)
{
MotionSolver::specifyProblem(pointer);
prob_ = std::static_pointer_cast<ProblemType>(pointer);
if (prob_->getScene()->getBaseType() == BASE_TYPE::FIXED)
state_space_.reset(new OMPLRNStateSpace(prob_, init_));
else if (prob_->getScene()->getBaseType() == BASE_TYPE::PLANAR)
state_space_.reset(new OMPLSE2RNStateSpace(prob_, init_));
else if (prob_->getScene()->getBaseType() == BASE_TYPE::FLOATING)
state_space_.reset(new OMPLSE3RNStateSpace(prob_, init_));
else
throw_named("Unsupported base type " << prob_->getScene()->getBaseType());
ompl_simple_setup_.reset(new ompl::geometric::SimpleSetup(state_space_));
ompl_simple_setup_->setStateValidityChecker(ompl::base::StateValidityCheckerPtr(new OMPLStateValidityChecker(ompl_simple_setup_->getSpaceInformation(), prob_)));
ompl_simple_setup_->setPlannerAllocator(boost::bind(planner_allocator_, _1, algorithm_));
if (init_.Projection.rows() > 0)
{
std::vector<int> project_vars(init_.Projection.rows());
for (int i = 0; i < init_.Projection.rows(); i++)
{
project_vars[i] = (int)init_.Projection(i);
if (project_vars[i] < 0 || project_vars[i] >= prob_->N) throw_named("Invalid projection index! " << project_vars[i]);
}
if (prob_->getScene()->getBaseType() == BASE_TYPE::FIXED)
ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLRNProjection(state_space_, project_vars)));
else if (prob_->getScene()->getBaseType() == BASE_TYPE::PLANAR)
ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLSE2RNProjection(state_space_, project_vars)));
else if (prob_->getScene()->getBaseType() == BASE_TYPE::FLOATING)
ompl_simple_setup_->getStateSpace()->registerDefaultProjection(ompl::base::ProjectionEvaluatorPtr(new OMPLSE3RNProjection(state_space_, project_vars)));
}
ompl_simple_setup_->getSpaceInformation()->setup();
ompl_simple_setup_->setup();
if (ompl_simple_setup_->getPlanner()->params().hasParam("range"))
ompl_simple_setup_->getPlanner()->params().setParam("range", init_.Range);
if (ompl_simple_setup_->getPlanner()->params().hasParam("goal_bias"))
ompl_simple_setup_->getPlanner()->params().setParam("goal_bias", init_.GoalBias);
if (init_.RandomSeed != -1)
{
HIGHLIGHT_NAMED(algorithm_, "Setting random seed to " << init_.RandomSeed);
ompl::RNG::setSeed(init_.RandomSeed);
}
}
template <class ProblemType>
int OMPLsolver<ProblemType>::getRandomSeed()
{
return ompl::RNG::getSeed();
}
template <class ProblemType>
void OMPLsolver<ProblemType>::preSolve()
{
// clear previously computed solutions
if (!multiQuery)
{
ompl_simple_setup_->getProblemDefinition()->clearSolutionPaths();
const ompl::base::PlannerPtr planner = ompl_simple_setup_->getPlanner();
if (planner)
planner->clear();
ompl_simple_setup_->getPlanner()->setProblemDefinition(ompl_simple_setup_->getProblemDefinition());
}
ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->resetMotionCounter();
}
template <class ProblemType>
void OMPLsolver<ProblemType>::postSolve()
{
ompl_simple_setup_->clearStartStates();
int v = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getValidMotionCount();
int iv = ompl_simple_setup_->getSpaceInformation()->getMotionValidator()->getInvalidMotionCount();
CONSOLE_BRIDGE_logDebug("There were %d valid motions and %d invalid motions.", v, iv);
if (ompl_simple_setup_->getProblemDefinition()->hasApproximateSolution())
CONSOLE_BRIDGE_logWarn("Computed solution is approximate");
}
template <class ProblemType>
void OMPLsolver<ProblemType>::setGoalState(const Eigen::VectorXd &qT, const double eps)
{
ompl::base::ScopedState<> gs(state_space_);
state_space_->as<OMPLStateSpace>()->ExoticaToOMPLState(qT, gs.get());
if (!ompl_simple_setup_->getStateValidityChecker()->isValid(gs.get()))
{
throw_named("Goal state is not valid!");
}
if (!ompl_simple_setup_->getSpaceInformation()->satisfiesBounds(gs.get()))
{
state_space_->as<OMPLStateSpace>()->stateDebug(qT);
// Debug state and bounds
std::string out_of_bounds_joint_ids = "";
for (int i = 0; i < qT.rows(); i++)
if (qT(i) < prob_->getBounds()[i] || qT(i) > prob_->getBounds()[i + qT.rows()])
out_of_bounds_joint_ids += "[j" + std::to_string(i) + "=" + std::to_string(qT(i)) + ", ll=" + std::to_string(prob_->getBounds()[i]) + ", ul=" + std::to_string(prob_->getBounds()[i + qT.rows()]) + "]\n";
throw_named("Invalid goal state [Invalid joint bounds for joint indices: \n"
<< out_of_bounds_joint_ids << "]");
}
ompl_simple_setup_->setGoalState(gs, eps);
}
template <class ProblemType>
void OMPLsolver<ProblemType>::getPath(Eigen::MatrixXd &traj, ompl::base::PlannerTerminationCondition &ptc)
{
ompl::geometric::PathSimplifierPtr psf_ = ompl_simple_setup_->getPathSimplifier();
const ompl::base::SpaceInformationPtr &si = ompl_simple_setup_->getSpaceInformation();
ompl::geometric::PathGeometric pg = ompl_simple_setup_->getSolutionPath();
if (init_.Smooth)
{
bool tryMore = true;
int times = 0;
while (init_.ReduceVertices && times < init_.SimplifyTryCnt && tryMore && ptc == false)
{
pg.interpolate(init_.SimplifyInterpolationLength);
tryMore = psf_->reduceVertices(pg, 0, 0, init_.RangeRatio);
times++;
}
if (init_.ShortcutPath && si->getStateSpace()->isMetricSpace())
{
times = 0;
while (times < init_.SimplifyTryCnt && tryMore && ptc == false)
{
pg.interpolate(init_.SimplifyInterpolationLength);
tryMore = psf_->shortcutPath(pg, 0, 0, init_.RangeRatio, init_.SnapToVertex);
times++;
}
}
}
std::vector<ompl::base::State *> &states = pg.getStates();
unsigned int length = 0;
if (init_.FinalInterpolationLength > 3)
length = init_.FinalInterpolationLength;
else
{
const int n1 = states.size() - 1;
for (int i = 0; i < n1; ++i)
length += si->getStateSpace()->validSegmentCount(states[i], states[i + 1]);
}
pg.interpolate(int(length * init_.SmoothnessFactor));
traj.resize(pg.getStateCount(), prob_->getSpaceDim());
Eigen::VectorXd tmp(prob_->getSpaceDim());
for (int i = 0; i < (int)pg.getStateCount(); ++i)
{
state_space_->as<OMPLStateSpace>()->OMPLToExoticaState(pg.getState(i), tmp);
traj.row(i) = tmp;
}
}
template <class ProblemType>
void OMPLsolver<ProblemType>::Solve(Eigen::MatrixXd &solution)
{
Eigen::VectorXd q0 = prob_->applyStartState();
setGoalState(prob_->getGoalState(), init_.Epsilon);
ompl::base::ScopedState<> ompl_start_state(state_space_);
state_space_->as<OMPLStateSpace>()->ExoticaToOMPLState(q0, ompl_start_state.get());
ompl_simple_setup_->setStartState(ompl_start_state);
preSolve();
ompl::time::point start = ompl::time::now();
ompl::base::PlannerTerminationCondition ptc = ompl::base::timedPlannerTerminationCondition(init_.Timeout - ompl::time::seconds(ompl::time::now() - start));
if (ompl_simple_setup_->solve(ptc) == ompl::base::PlannerStatus::EXACT_SOLUTION && ompl_simple_setup_->haveSolutionPath())
{
getPath(solution, ptc);
}
postSolve();
}
template class OMPLsolver<SamplingProblem>;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
* Copyright (C) 2006 10East Corp.
*
* 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.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef __PLACEMENT_FINDER__
#define __PLACEMENT_FINDER__
#include <queue>
#include <mapnik/ctrans.hpp>
#include <mapnik/label_collision_detector.hpp>
#include <mapnik/text_symbolizer.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/text_path.hpp>
namespace mapnik
{
struct placement
{
typedef coord_transform2<CoordTransform,geometry_type> path_type;
//For shields
placement(string_info *info_, CoordTransform *ctrans_, const proj_transform *proj_trans_, geometry_ptr geom_, std::pair<double, double> dimensions_);
//For text
placement(string_info *info_, CoordTransform *ctrans_, const proj_transform *proj_trans_, geometry_ptr geom_, label_placement_e placement_);
~placement();
string_info *info;
CoordTransform *ctrans;
const proj_transform *proj_trans;
geometry_ptr geom;
label_placement_e label_placement;
std::pair<double, double> dimensions;
bool has_dimensions;
path_type shape_path;
std::queue< Envelope<double> > envelopes;
//output
double starting_x;
double starting_y;
text_path path;
//helpers
std::pair<double, double> get_position_at_distance(double target_distance);
double get_total_distance();
void placement::clear_envelopes();
double total_distance_; //cache for distance
};
class placement_finder : boost::noncopyable
{
public:
placement_finder(Envelope<double> e);
bool find_placement(placement *placement);
protected:
bool find_placement_follow(placement *p);
bool find_placement_horizontal(placement *p);
bool build_path_follow(placement *p, double target_distance);
bool build_path_horizontal(placement *p, double target_distance);
void update_detector(placement *p);
label_collision_detector3 detector_;
};
}
#endif
<commit_msg>removed extra qualifier (GCC >= 4.1 reports as an error).<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
* Copyright (C) 2006 10East Corp.
*
* 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.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef __PLACEMENT_FINDER__
#define __PLACEMENT_FINDER__
#include <queue>
#include <mapnik/ctrans.hpp>
#include <mapnik/label_collision_detector.hpp>
#include <mapnik/text_symbolizer.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/text_path.hpp>
namespace mapnik
{
struct placement
{
typedef coord_transform2<CoordTransform,geometry_type> path_type;
//For shields
placement(string_info *info_, CoordTransform *ctrans_, const proj_transform *proj_trans_, geometry_ptr geom_, std::pair<double, double> dimensions_);
//For text
placement(string_info *info_, CoordTransform *ctrans_, const proj_transform *proj_trans_, geometry_ptr geom_, label_placement_e placement_);
~placement();
string_info *info;
CoordTransform *ctrans;
const proj_transform *proj_trans;
geometry_ptr geom;
label_placement_e label_placement;
std::pair<double, double> dimensions;
bool has_dimensions;
path_type shape_path;
std::queue< Envelope<double> > envelopes;
//output
double starting_x;
double starting_y;
text_path path;
//helpers
std::pair<double, double> get_position_at_distance(double target_distance);
double get_total_distance();
void clear_envelopes();
double total_distance_; //cache for distance
};
class placement_finder : boost::noncopyable
{
public:
placement_finder(Envelope<double> e);
bool find_placement(placement *placement);
protected:
bool find_placement_follow(placement *p);
bool find_placement_horizontal(placement *p);
bool build_path_follow(placement *p, double target_distance);
bool build_path_horizontal(placement *p, double target_distance);
void update_detector(placement *p);
label_collision_detector3 detector_;
};
}
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* 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.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_VERTEX_TRANSFORM_HPP
#define MAPNIK_VERTEX_TRANSFORM_HPP
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/vertex.hpp>
namespace mapnik
{
template <typename T0 ,typename T1,int shift=8>
struct Shift
{
typedef T0 value_type;
typedef T1 return_type;
static return_type apply(value_type val)
{
return static_cast<return_type>(val*(1<<shift));
}
};
template <typename T0,typename T1>
struct Shift<T0,T1,0>
{
typedef T0 value_type;
typedef T1 return_type;
static return_type apply(value_type val)
{
return static_cast<return_type>(val);
}
};
template <typename T>
struct Shift<T,T,0>
{
typedef T value_type;
typedef T return_type;
static T& apply(T& val)
{
return val;
}
};
typedef Shift<double,double,0> NO_SHIFT;
typedef Shift<double,int,0> SHIFT0;
typedef Shift<double,int,8> SHIFT8;
template <typename T0,typename T1,typename Trans>
struct view_transform;
template <typename Trans>
struct view_transform <vertex2d,vertex2d,Trans>
{
};
template <typename Trans>
struct view_transform <vertex2d,vertex2i,Trans>
{
};
template <typename Trans>
struct view_transform<box2d<double>,box2d<double>,Trans>
{
};
}
#endif //VERTEX_TRANSFORM_HPP
<commit_msg>- small cosmetics<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* 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.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_VERTEX_TRANSFORM_HPP
#define MAPNIK_VERTEX_TRANSFORM_HPP
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/vertex.hpp>
namespace mapnik
{
template <typename T0 ,typename T1,int shift=8>
struct Shift
{
typedef T0 value_type;
typedef T1 return_type;
static return_type apply(value_type val)
{
return static_cast<return_type>(val*(1<<shift));
}
};
template <typename T0,typename T1>
struct Shift<T0,T1,0>
{
typedef T0 value_type;
typedef T1 return_type;
static return_type apply(value_type val)
{
return static_cast<return_type>(val);
}
};
template <typename T>
struct Shift<T,T,0>
{
typedef T value_type;
typedef T return_type;
static T& apply(T& val)
{
return val;
}
};
typedef Shift<double,double,0> NO_SHIFT;
typedef Shift<double,int,0> SHIFT0;
typedef Shift<double,int,8> SHIFT8;
template <typename T0,typename T1,typename Trans>
struct view_transform;
template <typename Trans>
struct view_transform <vertex2d,vertex2d,Trans>
{
};
template <typename Trans>
struct view_transform <vertex2d,vertex2i,Trans>
{
};
template <typename Trans>
struct view_transform<box2d<double>,box2d<double>,Trans>
{
};
}
#endif // MAPNIK_VERTEX_TRANSFORM_HPP
<|endoftext|>
|
<commit_before>/**
* $Id$
*
* Copyright (C)
* 2015 - $Date$
* Martin Wolf <ndhist@martin-wolf.org>
*
* This file is distributed under the BSD 2-Clause Open Source License
* (See LICENSE file).
*
*/
#ifndef NDHIST_DETAIL_BIN_VALUE_HPP_INCLUDED
#define NDHIST_DETAIL_BIN_VALUE_HPP_INCLUDED
namespace ndhist {
namespace detail {
template <typename WeightValueType>
struct bin_value
{
uintptr_t * noe_;
WeightValueType * sow_;
WeightValueType * sows_;
};
template <>
struct bin_value<bp::object>
{
uintptr_t * noe_;
uintptr_t * sow_obj_ptr_;
bp::object sow_obj_;
bp::object * sow_;
uintptr_t * sows_obj_ptr_;
bp::object sows_obj_;
bp::object * sows_;
};
}//namespace detail
}//namespace ndhist
#endif // !NDHIST_DETAIL_BIN_VALUE_HPP_INCLUDED
<commit_msg>Make the header self-consistent.<commit_after>/**
* $Id$
*
* Copyright (C)
* 2015 - $Date$
* Martin Wolf <ndhist@martin-wolf.org>
*
* This file is distributed under the BSD 2-Clause Open Source License
* (See LICENSE file).
*
*/
#ifndef NDHIST_DETAIL_BIN_VALUE_HPP_INCLUDED
#define NDHIST_DETAIL_BIN_VALUE_HPP_INCLUDED
#include <boost/python.hpp>
namespace ndhist {
namespace detail {
template <typename WeightValueType>
struct bin_value
{
uintptr_t * noe_;
WeightValueType * sow_;
WeightValueType * sows_;
};
template <>
struct bin_value<boost::python::object>
{
uintptr_t * noe_;
uintptr_t * sow_obj_ptr_;
boost::python::object sow_obj_;
boost::python::object * sow_;
uintptr_t * sows_obj_ptr_;
boost::python::object sows_obj_;
boost::python::object * sows_;
};
}//namespace detail
}//namespace ndhist
#endif // !NDHIST_DETAIL_BIN_VALUE_HPP_INCLUDED
<|endoftext|>
|
<commit_before>#ifndef PARSERLIB__PARSE_CONTEXT__HPP
#define PARSERLIB__PARSE_CONTEXT__HPP
#include <utility>
#include <string>
#include <string_view>
#include <vector>
#include <ostream>
#include <map>
namespace parserlib
{
/**
Struct with data required for parsing.
@param Input input type.
*/
template <typename Input = std::string>
class parse_context
{
public:
///input type.
typedef Input input_type;
///match.
struct match
{
///begin of match input.
typename Input::const_iterator begin;
///end of match input.
typename Input::const_iterator end;
///tag.
std::string_view tag;
///automatic conversion to string.
operator std::basic_string<typename Input::value_type> () const
{
return { begin, end };
}
/**
Operator used for match output to a stream.
@param stream output stream.
@param m match.
@return the output stream.
*/
template <typename Char, typename Traits>
friend std::basic_ostream<Char, Traits>& operator << (std::basic_ostream<Char, Traits>& stream, const match &m)
{
for (auto it = m.begin; it != m.end; ++it)
{
stream << *it;
}
return stream;
}
};
///state
struct state
{
///current position over the input.
typename Input::const_iterator position;
///matches container size.
size_t matches_size;
};
///current position over the input.
typename Input::const_iterator position;
///input begin.
const typename Input::const_iterator begin;
///input end.
const typename Input::const_iterator end;
///parse positions.
std::map<const void*, std::vector<typename Input::const_iterator>> parse_positions;
///matches.
std::vector<match> matches;
/**
Constructor.
@param container container to create a parse context out of.
@return the parse context for parsing the input contained in the given container.
*/
parse_context(const Input& container)
: position(container.begin())
, begin(container.begin())
, end(container.end())
{
}
/**
Checks if position has reached end.
@return true if position has not reached end, false otherwise.
*/
bool valid() const
{
return position < end;
}
/**
Returns the current state.
@return state.
*/
struct state state() const
{
return { position, matches.size() };
}
/**
Sets the current state.
@param s state.
*/
void set_state(const struct state& s)
{
position = s.position;
matches.resize(s.matches_size);
}
/**
Returns the remaining input.
@return the remaining input.
*/
Input remaining_input() const
{
return Input(position, end);
}
/**
Helper function for adding a match.
@param begin start of matched input.
@param end end of matched input.
@param tag input tag.
*/
void add_match(
const typename Input::const_iterator begin,
const typename Input::const_iterator end,
const std::string_view& tag)
{
matches.push_back(match{ begin, end, tag });
}
/**
Helper function for adding a parse position.
@param obj object to add a parse position for.
@return true if the two last positions are the same (useful in recognizing left recursion), false otherwise.
*/
bool add_position(const void* obj)
{
auto& pos = parse_positions[obj];
pos.push_back(position);
return pos.size() >= 2 && pos.back() == *(pos.end() - 2);
}
/**
Removes the last parse position.
@param obj obj to remove the last parse position of.
*/
void remove_position(const void* obj)
{
parse_positions[rule].pop_back();
}
};
} //namespace parserlib
#endif //PARSERLIB__PARSE_CONTEXT__HPP
<commit_msg>Fixed the function.<commit_after>#ifndef PARSERLIB__PARSE_CONTEXT__HPP
#define PARSERLIB__PARSE_CONTEXT__HPP
#include <utility>
#include <string>
#include <string_view>
#include <vector>
#include <ostream>
#include <map>
namespace parserlib
{
/**
Struct with data required for parsing.
@param Input input type.
*/
template <typename Input = std::string>
class parse_context
{
public:
///input type.
typedef Input input_type;
///match.
struct match
{
///begin of match input.
typename Input::const_iterator begin;
///end of match input.
typename Input::const_iterator end;
///tag.
std::string_view tag;
///automatic conversion to string.
operator std::basic_string<typename Input::value_type> () const
{
return { begin, end };
}
/**
Operator used for match output to a stream.
@param stream output stream.
@param m match.
@return the output stream.
*/
template <typename Char, typename Traits>
friend std::basic_ostream<Char, Traits>& operator << (std::basic_ostream<Char, Traits>& stream, const match &m)
{
for (auto it = m.begin; it != m.end; ++it)
{
stream << *it;
}
return stream;
}
};
///state
struct state
{
///current position over the input.
typename Input::const_iterator position;
///matches container size.
size_t matches_size;
};
///current position over the input.
typename Input::const_iterator position;
///input begin.
const typename Input::const_iterator begin;
///input end.
const typename Input::const_iterator end;
///parse positions.
std::map<const void*, std::vector<typename Input::const_iterator>> parse_positions;
///matches.
std::vector<match> matches;
size_t recursion_count = 0;
/**
Constructor.
@param container container to create a parse context out of.
@return the parse context for parsing the input contained in the given container.
*/
parse_context(const Input& container)
: position(container.begin())
, begin(container.begin())
, end(container.end())
{
}
/**
Checks if position has reached end.
@return true if position has not reached end, false otherwise.
*/
bool valid() const
{
return position < end;
}
/**
Returns the current state.
@return state.
*/
struct state state() const
{
return { position, matches.size() };
}
/**
Sets the current state.
@param s state.
*/
void set_state(const struct state& s)
{
position = s.position;
matches.resize(s.matches_size);
}
/**
Returns the remaining input.
@return the remaining input.
*/
Input remaining_input() const
{
return Input(position, end);
}
/**
Helper function for adding a match.
@param begin start of matched input.
@param end end of matched input.
@param tag input tag.
*/
void add_match(
const typename Input::const_iterator begin,
const typename Input::const_iterator end,
const std::string_view& tag)
{
matches.push_back(match{ begin, end, tag });
}
/**
Helper function for adding a parse position.
@param obj object to add a parse position for.
@return true if the two last positions are the same (useful in recognizing left recursion), false otherwise.
*/
bool add_position(const void* obj)
{
auto& pos = parse_positions[obj];
pos.push_back(position);
return pos.size() >= 2 && pos.back() == *(pos.end() - 2);
}
/**
Removes the last parse position.
@param obj obj to remove the last parse position of.
*/
void remove_position(const void* obj)
{
parse_positions[obj].pop_back();
}
};
} //namespace parserlib
#endif //PARSERLIB__PARSE_CONTEXT__HPP
<|endoftext|>
|
<commit_before>/*******************************************************************************
* include/queries/bin_rank_popcnt.hpp
*
* Copyright (C) 2018 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
/* Based on
* @inproceedings{Zhou2013RankSelect,
* author = {Dong Zhou and David G. Andersen and Michael Kaminsky},
* title = {Space-Efficient, High-Performance Rank and Select Structures
* on Uncompressed Bit Sequences},
* booktitle = {12th International Symposium on Experimental Algorithms
* ({SEA})},
* series = {LNCS},
* volume = {7933},
* pages = {151--163},
* publisher = {Springer},
* year = {2013},
* }
*/
#pragma once
#include <limits>
class bin_rank_popcnt {
public:
bin_rank_popcnt(uint64_t const * data, const size_t size)
: l0_(size / upper_block_cover_, 0ULL), l12_(size / l12_block_cover_, 0ULL),
data_(data), size_(size) {
auto cur_pos = data;
const auto end_pos = data + size;
size_t l0_pos = 0;
size_t l12_pos = 0;
uint32_t l1_entry = 0UL;
while (cur_pos != end_pos) {
l12_[l12_pos] = set_l1_entry(l12_[l12_pos], l1_entry);
for (size_t i = 0; i < 3; ++i) {
uint32_t l2_entry = 0UL;
for (size_t j = 0; j < basic_block_cover_; ++j) {
l2_entry += __builtin_popcountll(*(cur_pos++));
}
l1_entry += l2_entry;
l12_[l12_pos] = set_l2_entry(l12_[l12_pos], l2_entry, i);
}
for (size_t j = 0; j < basic_block_cover_; ++j) {
l1_entry += __builtin_popcountll(*(cur_pos++));
}
++l12_pos;
if (l12_pos % upper_block_cover_ == 0) {
if (l0_pos > 0) { l0_[l0_pos] += l0_[l0_pos - 1]; }
l0_[l0_pos++] += l1_entry;
l1_entry = 0UL;
}
}
}
inline size_t rank1(const size_t index) const {
size_t result = 0;
size_t remaining_bits = index;
// Find L0 block
size_t l0_pos = remaining_bits / upper_block_bit_size_;
remaining_bits -= (l0_pos * upper_block_bit_size_);
if (l0_pos > 0) { result += l0_[l0_pos - 1]; }
// Find L1/L2 block
size_t l1_pos = remaining_bits / l12_block_bit_size_;
remaining_bits -= (l1_pos * l12_block_bit_size_);
const uint64_t l12_block = l12_[l1_pos];
result += get_l1_entry(l12_block);
size_t l2_pos = remaining_bits / basic_block_bit_size_;
remaining_bits -= (l2_pos * basic_block_bit_size_);
for (size_t i = 0; i < l2_pos; ++i) {
result += get_l2_entry(l12_block, i);
}
uint64_t const * remaining_data = data_ + (l1_pos * l12_block_cover_) +
(l2_pos * basic_block_cover_);
while (remaining_bits >= 64) {
result += __builtin_popcountll(*(remaining_data++));
remaining_bits -= 64;
}
if (remaining_bits > 0) {
result += __builtin_popcountll(*remaining_data >> (64 - remaining_bits));
}
return result;
}
inline size_t rank0(size_t index) const {
return index - rank1(index);
}
private:
// Note that we can only set the value once. If we want to set the value
// multiple times, we first have to set the first 32 bits to 0.
inline uint64_t set_l1_entry(const uint64_t word,
const uint32_t l1_entry) const {
uint64_t l1_entry_cast = static_cast<uint64_t>(l1_entry);
return word | (l1_entry_cast << 32);
}
inline uint32_t get_l1_entry(const uint64_t word) const {
return word >> 32;
}
// Note that we can only set each value once. If we want to set any value
// multiple times, we firts ahve to the the corresponding bits to 0.
inline uint64_t set_l2_entry(uint64_t word, const uint32_t l2_entry,
const size_t entry_pos) const {
uint64_t l2_entry_cast = static_cast<uint64_t>(l2_entry);
return word | (l2_entry_cast << (22 - (entry_pos * 10)));
}
inline uint32_t get_l2_entry(const uint64_t word,
const size_t entry_pos) const {
return (word & ((~0ULL) >> (32 + (entry_pos * 10)))) >>
(22 - (entry_pos * 10));
}
private:
static constexpr size_t bits_per_word_ = sizeof(uint64_t) * 8;
static constexpr size_t basic_block_bit_size_ = 512;
static constexpr size_t l12_block_bit_size_ = 4 * basic_block_bit_size_;
static constexpr size_t upper_block_bit_size_ =
std::numeric_limits<uint32_t>::max();
static constexpr size_t basic_block_cover_ =
basic_block_bit_size_ / bits_per_word_;
static constexpr size_t l12_block_cover_ =
l12_block_bit_size_ / bits_per_word_;
static constexpr size_t upper_block_cover_ =
upper_block_bit_size_ / bits_per_word_;
std::vector<uint64_t> l0_;
std::vector<uint64_t> l12_;
uint64_t const * const data_;
const size_t size_;
}; // class bin_rank_popcnt
/******************************************************************************/
<commit_msg>Disable copying operations in rank support<commit_after>/*******************************************************************************
* include/queries/bin_rank_popcnt.hpp
*
* Copyright (C) 2018 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
/* Based on
* @inproceedings{Zhou2013RankSelect,
* author = {Dong Zhou and David G. Andersen and Michael Kaminsky},
* title = {Space-Efficient, High-Performance Rank and Select Structures
* on Uncompressed Bit Sequences},
* booktitle = {12th International Symposium on Experimental Algorithms
* ({SEA})},
* series = {LNCS},
* volume = {7933},
* pages = {151--163},
* publisher = {Springer},
* year = {2013},
* }
*/
#pragma once
#include <limits>
#include <vector>
class bin_rank_popcnt {
public:
bin_rank_popcnt(uint64_t const * data, const size_t size)
: l0_(size / upper_block_cover_, 0ULL), l12_(size / l12_block_cover_, 0ULL),
data_(data), size_(size) {
auto cur_pos = data;
const auto end_pos = data + size;
size_t l0_pos = 0;
size_t l12_pos = 0;
uint32_t l1_entry = 0UL;
while (cur_pos != end_pos) {
l12_[l12_pos] = set_l1_entry(l12_[l12_pos], l1_entry);
for (size_t i = 0; i < 3; ++i) {
uint32_t l2_entry = 0UL;
for (size_t j = 0; j < basic_block_cover_; ++j) {
l2_entry += __builtin_popcountll(*(cur_pos++));
}
l1_entry += l2_entry;
l12_[l12_pos] = set_l2_entry(l12_[l12_pos], l2_entry, i);
}
for (size_t j = 0; j < basic_block_cover_; ++j) {
l1_entry += __builtin_popcountll(*(cur_pos++));
}
++l12_pos;
if (l12_pos % upper_block_cover_ == 0) {
if (l0_pos > 0) { l0_[l0_pos] += l0_[l0_pos - 1]; }
l0_[l0_pos++] += l1_entry;
l1_entry = 0UL;
}
}
}
bin_rank_popcnt(bin_rank_popcnt const&) = delete;
bin_rank_popcnt& operator =(bin_rank_popcnt const&) = delete;
bin_rank_popcnt(bin_rank_popcnt&&) = default;
bin_rank_popcnt& operator =(bin_rank_popcnt&&) = default;
inline size_t rank1(const size_t index) const {
size_t result = 0;
size_t remaining_bits = index;
// Find L0 block
size_t l0_pos = remaining_bits / upper_block_bit_size_;
remaining_bits -= (l0_pos * upper_block_bit_size_);
if (l0_pos > 0) { result += l0_[l0_pos - 1]; }
// Find L1/L2 block
size_t l1_pos = remaining_bits / l12_block_bit_size_;
remaining_bits -= (l1_pos * l12_block_bit_size_);
const uint64_t l12_block = l12_[l1_pos];
result += get_l1_entry(l12_block);
size_t l2_pos = remaining_bits / basic_block_bit_size_;
remaining_bits -= (l2_pos * basic_block_bit_size_);
for (size_t i = 0; i < l2_pos; ++i) {
result += get_l2_entry(l12_block, i);
}
uint64_t const * remaining_data = data_ + (l1_pos * l12_block_cover_) +
(l2_pos * basic_block_cover_);
while (remaining_bits >= 64) {
result += __builtin_popcountll(*(remaining_data++));
remaining_bits -= 64;
}
if (remaining_bits > 0) {
result += __builtin_popcountll(*remaining_data >> (64 - remaining_bits));
}
return result;
}
inline size_t rank0(size_t index) const {
return index - rank1(index);
}
private:
// Note that we can only set the value once. If we want to set the value
// multiple times, we first have to set the first 32 bits to 0.
inline uint64_t set_l1_entry(const uint64_t word,
const uint32_t l1_entry) const {
uint64_t l1_entry_cast = static_cast<uint64_t>(l1_entry);
return word | (l1_entry_cast << 32);
}
inline uint32_t get_l1_entry(const uint64_t word) const {
return word >> 32;
}
// Note that we can only set each value once. If we want to set any value
// multiple times, we firts ahve to the the corresponding bits to 0.
inline uint64_t set_l2_entry(uint64_t word, const uint32_t l2_entry,
const size_t entry_pos) const {
uint64_t l2_entry_cast = static_cast<uint64_t>(l2_entry);
return word | (l2_entry_cast << (22 - (entry_pos * 10)));
}
inline uint32_t get_l2_entry(const uint64_t word,
const size_t entry_pos) const {
return (word & ((~0ULL) >> (32 + (entry_pos * 10)))) >>
(22 - (entry_pos * 10));
}
private:
static constexpr size_t bits_per_word_ = sizeof(uint64_t) * 8;
static constexpr size_t basic_block_bit_size_ = 512;
static constexpr size_t l12_block_bit_size_ = 4 * basic_block_bit_size_;
static constexpr size_t upper_block_bit_size_ =
std::numeric_limits<uint32_t>::max();
static constexpr size_t basic_block_cover_ =
basic_block_bit_size_ / bits_per_word_;
static constexpr size_t l12_block_cover_ =
l12_block_bit_size_ / bits_per_word_;
static constexpr size_t upper_block_cover_ =
upper_block_bit_size_ / bits_per_word_;
std::vector<uint64_t> l0_;
std::vector<uint64_t> l12_;
uint64_t const * const data_;
const size_t size_;
}; // class bin_rank_popcnt
/******************************************************************************/
<|endoftext|>
|
<commit_before>// Copyright 2017 Nest Labs, 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.
#ifndef DETECTORGRAPH_INCLUDE_TIMEOUTPUBLISHERSERVICE_HPP_
#define DETECTORGRAPH_INCLUDE_TIMEOUTPUBLISHERSERVICE_HPP_
#include "graph.hpp"
#include "topicstate.hpp"
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
// LITE_BEGIN
#include "detectorgraphliteconfig.hpp"
#include "statictypedallocator-lite.hpp"
// LITE_END
#else
// FULL_BEGIN
#include <vector>
// FULL_END
#endif
namespace DetectorGraph
{
typedef int TimeoutPublisherHandle;
enum { kInvalidTimeoutPublisherHandle = -1 };
typedef uint64_t TimeOffset;
/**
* @brief A service that provides Timer function to DetectorGraph Detectors
*
* TimeoutPublisherService is used/shared among many TimeoutPublishers
* (Detectors) to add the notion of timed publications to DetectorGraph.
*/
class TimeoutPublisherService
{
// Types and classes used internally
/**
* @brief Internal DispatcherInterface for dispatching any scheduled
TopicState to Graph::PushData<T>
*/
struct DispatcherInterface
{
virtual void Dispatch(Graph& aGraph) = 0;
virtual ~DispatcherInterface() {}
};
/**
* @brief Internal Dispatcher for dispatching a particular scheduled
TopicState to Graph::PushData<T>
*/
template<class T>
struct Dispatcher : public DispatcherInterface
{
Dispatcher() : mData() {}
Dispatcher(const T& aData) : mData(aData) {}
virtual void Dispatch(Graph& aGraph)
{
aGraph.PushData<T>(mData);
}
const T mData;
};
/**
* @brief Internal Dispatcher for periodically dispatching TopicState to Graph::PushData<T>
*
* This internal data structure holds a periodically-triggered dispatcher. It is also used to track
* the time between triggers, so that different dispatchers can use the same synchronized metronome timer.
*/
struct PeriodicPublishingSeries
{
const TimeOffset mPublishingPeriodMsec;
TimeOffset mMetronomeCounter;
DispatcherInterface* mpDispatcher;
PeriodicPublishingSeries(const TimeOffset aPublishingPeriodMsec,
DispatcherInterface* aDispatcher)
: mPublishingPeriodMsec(aPublishingPeriodMsec)
, mMetronomeCounter(0)
, mpDispatcher(aDispatcher) {}
};
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
typedef SequenceContainer<DispatcherInterface*,
DetectorGraphConfig::kMaxNumberOfTimeouts> TimeoutDispatchersContainer;
typedef SequenceContainer<PeriodicPublishingSeries,
DetectorGraphConfig::kMaxNumberOfPeriodicTimers> PeriodicPublishingSeriesContainer;
struct TimeoutCtxt {};
typedef StaticTypedAllocator<DispatcherInterface, TimeoutCtxt> TimeoutDispatchersAllocator;
struct PeriodicCtxt {};
typedef StaticTypedAllocator<DispatcherInterface, PeriodicCtxt> PeriodicDispatchersAllocator;
#else
typedef std::vector<DispatcherInterface*> TimeoutDispatchersContainer;
typedef std::vector<PeriodicPublishingSeries> PeriodicPublishingSeriesContainer;
#endif
public:
/**
* @brief Constructor that initializes the service connected to a graph
*
* @param[in] graph The graph to which timed out TopicStates will be posted
*/
TimeoutPublisherService(Graph& graph);
/**
* @brief Destructor
*
* Deletes all dynamically allocated pending TopicStates
*/
virtual ~TimeoutPublisherService();
/**
* @brief Starts a Metronome to publish scheduled TopicStates
*
* Calling this method starts a metronome(periodic timer).
* TimeoutPublisherService will start publishing scheduled TopicStates periodically to graph.
*/
void StartPeriodicPublishing();
/**
* @brief Returns a unique id/handle for a new timer
*
* Different TimeoutPublishers will call this to 'acquire' a timer. The
* handle is then used throughout the API to refer to any individual timer.
* Note that this will never return kInvalidTimeoutPublisherHandle.
*/
TimeoutPublisherHandle GetUniqueTimerHandle();
/**
* @brief Schedules a TopicState for publishing periodically
*
* This is called by different Detectors with a TopicState and a publishing period.
* This method updates the metronome period based on the GCD of the requested publishing period.
* Calling 'StartPeriodicPublishing' will start publishing `T` to the graph periodically
* with interval @param aPeriodInMilliseconds .
*
* @param aPeriodInMilliseconds The regular period at which T should be published.
*/
template<class T>
void SchedulePeriodicPublishing(const TimeOffset aPeriodInMilliseconds)
{
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
SchedulePeriodicPublishingDispatcher(mPeriodicDispatchersAllocator.New(Dispatcher<T>()), aPeriodInMilliseconds);
#else
SchedulePeriodicPublishingDispatcher(new Dispatcher<T>(), aPeriodInMilliseconds);
#endif
}
/**
* @brief Schedules a TopicState for Publishing after a timeout
*
* This is called internally by TimeoutPublishers. It starts a timer set to
* expire at a given deadline. When the deadline is reached @param aData is
* Published to the graph.
* Calling this method on an pending @param aTimerHandle resets it
* (canceling any previous timeouts)
*
* @param aData The TopicState to be published when the deadline expires.
* @param aMillisecondsFromNow The deadline relative to now.
* @param aTimerHandle A unique handle for this timer.
*/
template<class T>
void ScheduleTimeout(const T& aData, const TimeOffset aMillisecondsFromNow, const TimeoutPublisherHandle aTimerHandle)
{
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
ScheduleTimeoutDispatcher(mTimeoutDispatchersAllocator.New(Dispatcher<T>(aData)), aMillisecondsFromNow, aTimerHandle);
#else
ScheduleTimeoutDispatcher(new Dispatcher<T>(aData), aMillisecondsFromNow, aTimerHandle);
#endif
}
/**
* @brief Cancels a timeout and deletes the stored TopicState
*
* This is called by different TimeoutPublishers when a timeout must be
* canceled.
*/
void CancelPublishOnTimeout(const TimeoutPublisherHandle aTimerHandle);
/**
* @brief Returns weather the timeout for a given handle has expired/fired
already.
*
* This will also return true if the referred timer never existed.
*/
bool HasTimeoutExpired(const TimeoutPublisherHandle aTimerHandle) const;
/**
* @brief Should return the time offset to Epoch
*
* This must be implemented by subclasses. Different detectors may call
* this to acquire a timestamp - usually used to "stamp" a TopicState.
* This clock may jump back & forth due to time sync.
*/
virtual TimeOffset GetTime() const = 0;
/**
* @brief Should return monotonic time since some unspecified starting point.
*
* This must be implemented by subclasses.
* Returns the time offset to an unspecified point back in time that should
* not change for the duration of this instance.
* Different detectors may call this to acquire a consistent, strictly
* increasing, time offset valid for the duration of this object's instance.
*/
virtual TimeOffset GetMonotonicTime() const = 0;
protected:
/**
* @brief Fires/Dispatches a TopicState that was pending on a timeout
*
* This method should be called by a particular subclasses of
* TimeoutPublisherService to notify the service that the actual
* internal timers have expired/fired.
*/
void TimeoutExpired(const TimeoutPublisherHandle aTimerHandle);
/**
* @brief Should setup a timeout for the given handle.
*
* This must be implemented by subclasses. This should initialize a unique
* timer for that handle (if it doesn't already exist) and set it's timeout
* accordingly.
*/
virtual void SetTimeout(const TimeOffset aMillisecondsFromNow, const TimeoutPublisherHandle) = 0;
/**
* @brief Should start a timer for the given handle.
*
* This must be implemented by subclasses. This should start the timer.
*/
virtual void Start(const TimeoutPublisherHandle) = 0;
/**
* @brief Should cancel the timer the given handle.
*
* This must be implemented by subclasses. This should cancel the timer.
*/
virtual void Cancel(const TimeoutPublisherHandle) = 0;
/**
* @brief Update metronome counters and Fires/Dispatches TopicStates that was pending on scheduled period.
*
* This method should be called by a particular subclasses of
* TimeoutPublisherService to notify the service that the actual
* internal period timer has fired.
*/
void MetronomeFired();
/**
* @brief Should start the metronome (periodic timer) for the given period.
*
* This must be implemented by subclasses. This should start the periodic timer.
*/
virtual void StartMetronome(const TimeOffset aPeriodInMilliseconds) = 0;
/**
* @brief Should stop the metronome.
*
* This must be implemented by subclasses. This should stop the periodic timer.
*/
virtual void CancelMetronome() = 0;
private:
/**
* @brief Internal type-agnostic method to schedule timeouts
*/
void ScheduleTimeoutDispatcher(DispatcherInterface* aDispatcher, const TimeOffset aMillisecondsFromNow, const TimeoutPublisherHandle aTimerHandle);
/**
* @brief Internal type-agnostic method to schedule periodic timers
*/
void SchedulePeriodicPublishingDispatcher(DispatcherInterface* aDispatcher, const TimeOffset aPeriodInMilliseconds);
/**
* @brief Euclidean algorithm to compute great common divisor(GCD)
*/
TimeOffset gcd(TimeOffset lhs, TimeOffset rhs);
/**
* @brief Reference to the graph to which timed out TopicStates will be
pushed/posted.
*/
Graph& mrGraph;
/**
* @brief Metronome period which used for periodic Topicstates publishing
*/
TimeOffset mMetronomePeriodMsec;
/**
* @brief Map of pending TopicStates per Handle
*/
TimeoutDispatchersContainer mTimeoutDispatchers;
/**
* @brief List of scheduled periodic TopicStates dispatcher
*/
PeriodicPublishingSeriesContainer mPeriodicSeries;
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
TimeoutDispatchersAllocator mTimeoutDispatchersAllocator;
PeriodicDispatchersAllocator mPeriodicDispatchersAllocator;
#endif
};
} // namespace DetectorGraph
#endif // DETECTORGRAPH_INCLUDE_TIMEOUTPUBLISHERSERVICE_HPP_
<commit_msg>Removed const limitation from mPublishingPeriodMsec as it's now assignable (in the vector).<commit_after>// Copyright 2017 Nest Labs, 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.
#ifndef DETECTORGRAPH_INCLUDE_TIMEOUTPUBLISHERSERVICE_HPP_
#define DETECTORGRAPH_INCLUDE_TIMEOUTPUBLISHERSERVICE_HPP_
#include "graph.hpp"
#include "topicstate.hpp"
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
// LITE_BEGIN
#include "detectorgraphliteconfig.hpp"
#include "statictypedallocator-lite.hpp"
// LITE_END
#else
// FULL_BEGIN
#include <vector>
// FULL_END
#endif
namespace DetectorGraph
{
typedef int TimeoutPublisherHandle;
enum { kInvalidTimeoutPublisherHandle = -1 };
typedef uint64_t TimeOffset;
/**
* @brief A service that provides Timer function to DetectorGraph Detectors
*
* TimeoutPublisherService is used/shared among many TimeoutPublishers
* (Detectors) to add the notion of timed publications to DetectorGraph.
*/
class TimeoutPublisherService
{
// Types and classes used internally
/**
* @brief Internal DispatcherInterface for dispatching any scheduled
TopicState to Graph::PushData<T>
*/
struct DispatcherInterface
{
virtual void Dispatch(Graph& aGraph) = 0;
virtual ~DispatcherInterface() {}
};
/**
* @brief Internal Dispatcher for dispatching a particular scheduled
TopicState to Graph::PushData<T>
*/
template<class T>
struct Dispatcher : public DispatcherInterface
{
Dispatcher() : mData() {}
Dispatcher(const T& aData) : mData(aData) {}
virtual void Dispatch(Graph& aGraph)
{
aGraph.PushData<T>(mData);
}
const T mData;
};
/**
* @brief Internal Dispatcher for periodically dispatching TopicState to Graph::PushData<T>
*
* This internal data structure holds a periodically-triggered dispatcher. It is also used to track
* the time between triggers, so that different dispatchers can use the same synchronized metronome timer.
*/
struct PeriodicPublishingSeries
{
TimeOffset mPublishingPeriodMsec;
TimeOffset mMetronomeCounter;
DispatcherInterface* mpDispatcher;
PeriodicPublishingSeries(TimeOffset aPublishingPeriodMsec,
DispatcherInterface* aDispatcher)
: mPublishingPeriodMsec(aPublishingPeriodMsec)
, mMetronomeCounter(0)
, mpDispatcher(aDispatcher) {}
};
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
typedef SequenceContainer<DispatcherInterface*,
DetectorGraphConfig::kMaxNumberOfTimeouts> TimeoutDispatchersContainer;
typedef SequenceContainer<PeriodicPublishingSeries,
DetectorGraphConfig::kMaxNumberOfPeriodicTimers> PeriodicPublishingSeriesContainer;
struct TimeoutCtxt {};
typedef StaticTypedAllocator<DispatcherInterface, TimeoutCtxt> TimeoutDispatchersAllocator;
struct PeriodicCtxt {};
typedef StaticTypedAllocator<DispatcherInterface, PeriodicCtxt> PeriodicDispatchersAllocator;
#else
typedef std::vector<DispatcherInterface*> TimeoutDispatchersContainer;
typedef std::vector<PeriodicPublishingSeries> PeriodicPublishingSeriesContainer;
#endif
public:
/**
* @brief Constructor that initializes the service connected to a graph
*
* @param[in] graph The graph to which timed out TopicStates will be posted
*/
TimeoutPublisherService(Graph& graph);
/**
* @brief Destructor
*
* Deletes all dynamically allocated pending TopicStates
*/
virtual ~TimeoutPublisherService();
/**
* @brief Starts a Metronome to publish scheduled TopicStates
*
* Calling this method starts a metronome(periodic timer).
* TimeoutPublisherService will start publishing scheduled TopicStates periodically to graph.
*/
void StartPeriodicPublishing();
/**
* @brief Returns a unique id/handle for a new timer
*
* Different TimeoutPublishers will call this to 'acquire' a timer. The
* handle is then used throughout the API to refer to any individual timer.
* Note that this will never return kInvalidTimeoutPublisherHandle.
*/
TimeoutPublisherHandle GetUniqueTimerHandle();
/**
* @brief Schedules a TopicState for publishing periodically
*
* This is called by different Detectors with a TopicState and a publishing period.
* This method updates the metronome period based on the GCD of the requested publishing period.
* Calling 'StartPeriodicPublishing' will start publishing `T` to the graph periodically
* with interval @param aPeriodInMilliseconds .
*
* @param aPeriodInMilliseconds The regular period at which T should be published.
*/
template<class T>
void SchedulePeriodicPublishing(const TimeOffset aPeriodInMilliseconds)
{
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
SchedulePeriodicPublishingDispatcher(mPeriodicDispatchersAllocator.New(Dispatcher<T>()), aPeriodInMilliseconds);
#else
SchedulePeriodicPublishingDispatcher(new Dispatcher<T>(), aPeriodInMilliseconds);
#endif
}
/**
* @brief Schedules a TopicState for Publishing after a timeout
*
* This is called internally by TimeoutPublishers. It starts a timer set to
* expire at a given deadline. When the deadline is reached @param aData is
* Published to the graph.
* Calling this method on an pending @param aTimerHandle resets it
* (canceling any previous timeouts)
*
* @param aData The TopicState to be published when the deadline expires.
* @param aMillisecondsFromNow The deadline relative to now.
* @param aTimerHandle A unique handle for this timer.
*/
template<class T>
void ScheduleTimeout(const T& aData, const TimeOffset aMillisecondsFromNow, const TimeoutPublisherHandle aTimerHandle)
{
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
ScheduleTimeoutDispatcher(mTimeoutDispatchersAllocator.New(Dispatcher<T>(aData)), aMillisecondsFromNow, aTimerHandle);
#else
ScheduleTimeoutDispatcher(new Dispatcher<T>(aData), aMillisecondsFromNow, aTimerHandle);
#endif
}
/**
* @brief Cancels a timeout and deletes the stored TopicState
*
* This is called by different TimeoutPublishers when a timeout must be
* canceled.
*/
void CancelPublishOnTimeout(const TimeoutPublisherHandle aTimerHandle);
/**
* @brief Returns weather the timeout for a given handle has expired/fired
already.
*
* This will also return true if the referred timer never existed.
*/
bool HasTimeoutExpired(const TimeoutPublisherHandle aTimerHandle) const;
/**
* @brief Should return the time offset to Epoch
*
* This must be implemented by subclasses. Different detectors may call
* this to acquire a timestamp - usually used to "stamp" a TopicState.
* This clock may jump back & forth due to time sync.
*/
virtual TimeOffset GetTime() const = 0;
/**
* @brief Should return monotonic time since some unspecified starting point.
*
* This must be implemented by subclasses.
* Returns the time offset to an unspecified point back in time that should
* not change for the duration of this instance.
* Different detectors may call this to acquire a consistent, strictly
* increasing, time offset valid for the duration of this object's instance.
*/
virtual TimeOffset GetMonotonicTime() const = 0;
protected:
/**
* @brief Fires/Dispatches a TopicState that was pending on a timeout
*
* This method should be called by a particular subclasses of
* TimeoutPublisherService to notify the service that the actual
* internal timers have expired/fired.
*/
void TimeoutExpired(const TimeoutPublisherHandle aTimerHandle);
/**
* @brief Should setup a timeout for the given handle.
*
* This must be implemented by subclasses. This should initialize a unique
* timer for that handle (if it doesn't already exist) and set it's timeout
* accordingly.
*/
virtual void SetTimeout(const TimeOffset aMillisecondsFromNow, const TimeoutPublisherHandle) = 0;
/**
* @brief Should start a timer for the given handle.
*
* This must be implemented by subclasses. This should start the timer.
*/
virtual void Start(const TimeoutPublisherHandle) = 0;
/**
* @brief Should cancel the timer the given handle.
*
* This must be implemented by subclasses. This should cancel the timer.
*/
virtual void Cancel(const TimeoutPublisherHandle) = 0;
/**
* @brief Update metronome counters and Fires/Dispatches TopicStates that was pending on scheduled period.
*
* This method should be called by a particular subclasses of
* TimeoutPublisherService to notify the service that the actual
* internal period timer has fired.
*/
void MetronomeFired();
/**
* @brief Should start the metronome (periodic timer) for the given period.
*
* This must be implemented by subclasses. This should start the periodic timer.
*/
virtual void StartMetronome(const TimeOffset aPeriodInMilliseconds) = 0;
/**
* @brief Should stop the metronome.
*
* This must be implemented by subclasses. This should stop the periodic timer.
*/
virtual void CancelMetronome() = 0;
private:
/**
* @brief Internal type-agnostic method to schedule timeouts
*/
void ScheduleTimeoutDispatcher(DispatcherInterface* aDispatcher, const TimeOffset aMillisecondsFromNow, const TimeoutPublisherHandle aTimerHandle);
/**
* @brief Internal type-agnostic method to schedule periodic timers
*/
void SchedulePeriodicPublishingDispatcher(DispatcherInterface* aDispatcher, const TimeOffset aPeriodInMilliseconds);
/**
* @brief Euclidean algorithm to compute great common divisor(GCD)
*/
TimeOffset gcd(TimeOffset lhs, TimeOffset rhs);
/**
* @brief Reference to the graph to which timed out TopicStates will be
pushed/posted.
*/
Graph& mrGraph;
/**
* @brief Metronome period which used for periodic Topicstates publishing
*/
TimeOffset mMetronomePeriodMsec;
/**
* @brief Map of pending TopicStates per Handle
*/
TimeoutDispatchersContainer mTimeoutDispatchers;
/**
* @brief List of scheduled periodic TopicStates dispatcher
*/
PeriodicPublishingSeriesContainer mPeriodicSeries;
#if defined(BUILD_FEATURE_DETECTORGRAPH_CONFIG_LITE)
TimeoutDispatchersAllocator mTimeoutDispatchersAllocator;
PeriodicDispatchersAllocator mPeriodicDispatchersAllocator;
#endif
};
} // namespace DetectorGraph
#endif // DETECTORGRAPH_INCLUDE_TIMEOUTPUBLISHERSERVICE_HPP_
<|endoftext|>
|
<commit_before>#include "swift/extractor/remapping/SwiftOutputRewrite.h"
#include <llvm/ADT/SmallString.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>
#include <swift/Basic/OutputFileMap.h>
#include <swift/Basic/Platform.h>
#include <unistd.h>
#include <unordered_set>
#include <optional>
#include <iostream>
// Creates a copy of the output file map and updates remapping table in place
// It does not change the original map file as it is depended upon by the original compiler
// Returns path to the newly created output file map on success, or None in a case of failure
static std::optional<std::string> rewriteOutputFileMap(
const std::string& scratchDir,
const std::string& outputFileMapPath,
const std::vector<std::string>& inputs,
std::unordered_map<std::string, std::string>& remapping) {
auto newMapPath = scratchDir + '/' + outputFileMapPath;
// TODO: do not assume absolute path for the second parameter
auto outputMapOrError = swift::OutputFileMap::loadFromPath(outputFileMapPath, "");
if (!outputMapOrError) {
std::cerr << "Cannot load output map: '" << outputFileMapPath << "'\n";
return std::nullopt;
}
auto oldOutputMap = outputMapOrError.get();
swift::OutputFileMap newOutputMap;
std::vector<llvm::StringRef> keys;
for (auto& key : inputs) {
auto oldMap = oldOutputMap.getOutputMapForInput(key);
if (!oldMap) {
continue;
}
keys.push_back(key);
auto& newMap = newOutputMap.getOrCreateOutputMapForInput(key);
newMap.copyFrom(*oldMap);
for (auto& entry : newMap) {
auto oldPath = entry.getSecond();
auto newPath = scratchDir + '/' + oldPath;
entry.getSecond() = newPath;
remapping[oldPath] = newPath;
}
}
std::error_code ec;
llvm::SmallString<PATH_MAX> filepath(newMapPath);
llvm::StringRef parent = llvm::sys::path::parent_path(filepath);
if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {
std::cerr << "Cannot create relocated output map dir: '" << parent.str()
<< "': " << ec.message() << "\n";
return std::nullopt;
}
llvm::raw_fd_ostream fd(newMapPath, ec, llvm::sys::fs::OF_None);
newOutputMap.write(fd, keys);
return newMapPath;
}
namespace codeql {
std::unordered_map<std::string, std::string> rewriteOutputsInPlace(
const std::string& scratchDir,
std::vector<std::string>& CLIArgs) {
std::unordered_map<std::string, std::string> remapping;
// TODO: handle filelists?
const std::unordered_set<std::string> pathRewriteOptions({
"-emit-dependencies-path",
"-emit-module-path",
"-emit-module-doc-path",
"-emit-module-source-info-path",
"-emit-objc-header-path",
"-emit-reference-dependencies-path",
"-index-store-path",
"-module-cache-path",
"-o",
"-pch-output-dir",
"-serialize-diagnostics-path",
});
std::unordered_set<std::string> outputFileMaps(
{"-supplementary-output-file-map", "-output-file-map"});
std::vector<size_t> outputFileMapIndexes;
std::vector<std::string> maybeInput;
std::string targetTriple;
std::vector<std::string> newLocations;
for (size_t i = 0; i < CLIArgs.size(); i++) {
if (pathRewriteOptions.count(CLIArgs[i])) {
auto oldPath = CLIArgs[i + 1];
auto newPath = scratchDir + '/' + oldPath;
CLIArgs[++i] = newPath;
newLocations.push_back(newPath);
remapping[oldPath] = newPath;
} else if (outputFileMaps.count(CLIArgs[i])) {
// collect output map indexes for further rewriting and skip the following argument
// We don't patch the map in place as we need to collect all the input files first
outputFileMapIndexes.push_back(++i);
} else if (CLIArgs[i] == "-target") {
targetTriple = CLIArgs[++i];
} else if (CLIArgs[i][0] != '-') {
// TODO: add support for input file lists?
// We need to collect input file names to later use them to extract information from the
// output file maps.
maybeInput.push_back(CLIArgs[i]);
}
}
for (auto index : outputFileMapIndexes) {
auto oldPath = CLIArgs[index];
auto maybeNewPath = rewriteOutputFileMap(scratchDir, oldPath, maybeInput, remapping);
if (maybeNewPath) {
auto newPath = maybeNewPath.value();
CLIArgs[index] = newPath;
remapping[oldPath] = newPath;
}
}
return remapping;
}
void ensureDirectoriesForNewPathsExist(
const std::unordered_map<std::string, std::string>& remapping) {
for (auto& [_, newPath] : remapping) {
llvm::SmallString<PATH_MAX> filepath(newPath);
llvm::StringRef parent = llvm::sys::path::parent_path(filepath);
if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {
std::cerr << "Cannot create redirected directory: " << ec.message() << "\n";
}
}
}
} // namespace codeql
<commit_msg>Swift: redirect more artfacts<commit_after>#include "swift/extractor/remapping/SwiftOutputRewrite.h"
#include <llvm/ADT/SmallString.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>
#include <swift/Basic/OutputFileMap.h>
#include <swift/Basic/Platform.h>
#include <unistd.h>
#include <unordered_set>
#include <optional>
#include <iostream>
// Creates a copy of the output file map and updates remapping table in place
// It does not change the original map file as it is depended upon by the original compiler
// Returns path to the newly created output file map on success, or None in a case of failure
static std::optional<std::string> rewriteOutputFileMap(
const std::string& scratchDir,
const std::string& outputFileMapPath,
const std::vector<std::string>& inputs,
std::unordered_map<std::string, std::string>& remapping) {
auto newMapPath = scratchDir + '/' + outputFileMapPath;
// TODO: do not assume absolute path for the second parameter
auto outputMapOrError = swift::OutputFileMap::loadFromPath(outputFileMapPath, "");
if (!outputMapOrError) {
std::cerr << "Cannot load output map: '" << outputFileMapPath << "'\n";
return std::nullopt;
}
auto oldOutputMap = outputMapOrError.get();
swift::OutputFileMap newOutputMap;
std::vector<llvm::StringRef> keys;
for (auto& key : inputs) {
auto oldMap = oldOutputMap.getOutputMapForInput(key);
if (!oldMap) {
continue;
}
keys.push_back(key);
auto& newMap = newOutputMap.getOrCreateOutputMapForInput(key);
newMap.copyFrom(*oldMap);
for (auto& entry : newMap) {
auto oldPath = entry.getSecond();
auto newPath = scratchDir + '/' + oldPath;
entry.getSecond() = newPath;
remapping[oldPath] = newPath;
}
}
std::error_code ec;
llvm::SmallString<PATH_MAX> filepath(newMapPath);
llvm::StringRef parent = llvm::sys::path::parent_path(filepath);
if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {
std::cerr << "Cannot create relocated output map dir: '" << parent.str()
<< "': " << ec.message() << "\n";
return std::nullopt;
}
llvm::raw_fd_ostream fd(newMapPath, ec, llvm::sys::fs::OF_None);
newOutputMap.write(fd, keys);
return newMapPath;
}
namespace codeql {
std::unordered_map<std::string, std::string> rewriteOutputsInPlace(
const std::string& scratchDir,
std::vector<std::string>& CLIArgs) {
std::unordered_map<std::string, std::string> remapping;
// TODO: handle filelists?
const std::unordered_set<std::string> pathRewriteOptions({
"-emit-abi-descriptor-path",
"-emit-dependencies-path",
"-emit-module-path",
"-emit-module-doc-path",
"-emit-module-source-info-path",
"-emit-objc-header-path",
"-emit-reference-dependencies-path",
"-index-store-path",
"-index-unit-output-path",
"-module-cache-path",
"-o",
"-pch-output-dir",
"-serialize-diagnostics-path",
});
std::unordered_set<std::string> outputFileMaps(
{"-supplementary-output-file-map", "-output-file-map"});
std::vector<size_t> outputFileMapIndexes;
std::vector<std::string> maybeInput;
std::string targetTriple;
std::vector<std::string> newLocations;
for (size_t i = 0; i < CLIArgs.size(); i++) {
if (pathRewriteOptions.count(CLIArgs[i])) {
auto oldPath = CLIArgs[i + 1];
auto newPath = scratchDir + '/' + oldPath;
CLIArgs[++i] = newPath;
newLocations.push_back(newPath);
remapping[oldPath] = newPath;
} else if (outputFileMaps.count(CLIArgs[i])) {
// collect output map indexes for further rewriting and skip the following argument
// We don't patch the map in place as we need to collect all the input files first
outputFileMapIndexes.push_back(++i);
} else if (CLIArgs[i] == "-target") {
targetTriple = CLIArgs[++i];
} else if (CLIArgs[i][0] != '-') {
// TODO: add support for input file lists?
// We need to collect input file names to later use them to extract information from the
// output file maps.
maybeInput.push_back(CLIArgs[i]);
}
}
for (auto index : outputFileMapIndexes) {
auto oldPath = CLIArgs[index];
auto maybeNewPath = rewriteOutputFileMap(scratchDir, oldPath, maybeInput, remapping);
if (maybeNewPath) {
auto newPath = maybeNewPath.value();
CLIArgs[index] = newPath;
remapping[oldPath] = newPath;
}
}
return remapping;
}
void ensureDirectoriesForNewPathsExist(
const std::unordered_map<std::string, std::string>& remapping) {
for (auto& [_, newPath] : remapping) {
llvm::SmallString<PATH_MAX> filepath(newPath);
llvm::StringRef parent = llvm::sys::path::parent_path(filepath);
if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {
std::cerr << "Cannot create redirected directory: " << ec.message() << "\n";
}
}
}
} // namespace codeql
<|endoftext|>
|
<commit_before>/*
* einit-gui-gtk.c++
* einit
*
* Created by Magnus Deininger on 01/08/2007.
* Copyright 2006, 2007 Magnus Deininger. All rights reserved.
*
*/
/*
Copyright (c) 2007, Magnus Deininger
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the project nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <gtkmm.h>
#include <einit/einit++.h>
int main(int argc, char *argv[])
{
Gtk::Main kit(argc, argv);
Gtk::Window window;
Einit einit;
Gtk::Main::run(window);
return 0;
}
<commit_msg>the gtk client can now show a listing with all the services... yay<commit_after>/*
* einit-gui-gtk.c++
* einit
*
* Created by Magnus Deininger on 01/08/2007.
* Copyright 2006, 2007 Magnus Deininger. All rights reserved.
*
*/
/*
Copyright (c) 2007, Magnus Deininger
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the project nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <einit/einit++.h>
#include <gtkmm.h>
#include <iostream>
class EinitGTK : public Gtk::Window {
public:
EinitGTK();
virtual ~EinitGTK();
Einit einit;
protected:
virtual void updateInformation();
//Signal handlers:
virtual void on_button_quit();
virtual void on_button_buffer1();
//Child widgets:
Gtk::VBox m_VBox;
Gtk::ScrolledWindow m_ScrolledWindow;
Gtk::TextView m_TextView;
Glib::RefPtr<Gtk::TextBuffer> m_refTextBuffer1;
Gtk::HButtonBox m_ButtonBox;
Gtk::Button m_Button_Quit, m_Button_Buffer1;
};
EinitGTK::EinitGTK(): m_Button_Quit(Gtk::Stock::QUIT), m_Button_Buffer1("Update"), einit() {
set_title("eINIT GTK GUI");
set_border_width(5);
set_default_size(400, 200);
add(m_VBox);
//Add the TreeView, inside a ScrolledWindow, with the button underneath:
m_ScrolledWindow.add(m_TextView);
//Only show the scrollbars when they are necessary:
m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
m_VBox.pack_start(m_ScrolledWindow);
//Add buttons:
m_VBox.pack_start(m_ButtonBox, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Buffer1, Gtk::PACK_SHRINK);
m_ButtonBox.pack_start(m_Button_Quit, Gtk::PACK_SHRINK);
m_ButtonBox.set_border_width(5);
m_ButtonBox.set_spacing(5);
m_ButtonBox.set_layout(Gtk::BUTTONBOX_END);
//Connect signals:
m_Button_Quit.signal_clicked().connect(sigc::mem_fun(*this,
&EinitGTK::on_button_quit) );
m_Button_Buffer1.signal_clicked().connect(sigc::mem_fun(*this,
&EinitGTK::on_button_buffer1) );
m_refTextBuffer1 = Gtk::TextBuffer::create();
updateInformation();
show_all_children();
}
void EinitGTK::updateInformation() {
this->einit.update();
einit_connect();
char *services = einit_ipc ("list services");
if (services) {
m_refTextBuffer1->set_text(services);
} else {
m_refTextBuffer1->set_text("Connection Failed");
}
m_TextView.set_buffer(m_refTextBuffer1);
}
EinitGTK::~EinitGTK() {
}
void EinitGTK::on_button_quit() {
hide();
}
void EinitGTK::on_button_buffer1() {
this->updateInformation();
}
int main (int argc, char *argv[]) {
Gtk::Main kit(argc, argv);
EinitGTK helloworld;
Gtk::Main::run(helloworld);
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef ORG_EEROS_CONTROL_MAFILTER_HPP_
#define ORG_EEROS_CONTROL_MAFILTER_HPP_
#include <eeros/control/Block1i1o.hpp>
#include <ostream>
namespace eeros {
namespace control {
/**
* A moving average filter (MAFilter) block is used to filter an input signal.
* The output signal value depends linearly on the current and various past
* input signal values.
* This is achieved by multiplying the current and the past values with
* the specified coefficients. The results are accumulated and yield to the
* output signal. The following terms represents the operation performed in
* this block.
*
* y[t] = c[0]*x[t-N] + c[1]*x[t-N-1] + ... + c[N]*x[t]
* Outp = c[0]*Inp[0] + c[1]*Inp[1] + ... + c[N]*Inp[N]
*
* MAFilter is a Class Template with two type and one non-type template arguments.
* The two type template arguments specify the types which are used for the
* values and the coefficients when the class template is instanciated.
* The non-type template argument specifies the number of coefficients and the
* number of concidered past values respectively.
*
* @tparam N - number of coefficients
* @tparam Tval - value type (double - default type)
* @tparam Tcoeff - coefficients type (Tval - default value)
*
* @since v0.6
*/
template <size_t N, typename Tval = double, typename Tcoeff = Tval>
class MAFilter : public Block1i1o<Tval> {
public:
/**
* Constructs a MAFilter instance with the coefficients coeff.\n
* @param coeff - coefficients
*/
explicit MAFilter(Tcoeff (& coeff)[N]) : coefficients{coeff} {}
/**
* Runs the filter algorithm.
*
* Performs the calculation of the filtered output signal value.
* Multiplies the current and past input signal values with the coefficients.
* The coefficients weight the current and past input signal values. Finally,
* the resulting values are accumulated and yield to the output signal value
* if the filter instance is enabled. Otherwise, the output signal value is
* set to the actual input signal value.
*
* The timestamp value will not be altered.
*
* @see enable()
* @see disable()
*/
virtual void run() {
Tval result{};
for(size_t i = 0; i < N; i++){
if(i < N-1) {
previousValues[i] = previousValues[i+1];
} else {
previousValues[i] = this->in.getSignal().getValue();
}
result += coefficients[i] * previousValues[i];
}
if(enabled) {
this->out.getSignal().setValue(result);
} else {
this->out.getSignal().setValue(this->in.getSignal().getValue());
}
this->out.getSignal().setTimestamp(this->in.getSignal().getTimestamp());
}
/**
* Enables the filter.
*
* If enabled, run() will set the output signal value to the accumulated values
* which result from the current and the past values weighted by the coefficients.
*
* @see run()
*/
virtual void enable() {
enabled = true;
}
/**
* Disables the filter.
*
* If disabled, run() will set the output signal to the input signal.
*
* @see run()
*/
virtual void disable() {
enabled = false;
}
/*
* Friend operator overload to give the operator overload outside
* the class access to the private fields.
*/
template <size_t No, typename ValT, typename CoeffT>
friend std::ostream& operator<<(std::ostream& os, MAFilter<No,ValT,CoeffT>& filter);
protected:
Tcoeff * coefficients;
Tval previousValues[N]{};
bool enabled{true};
};
/**
* Operator overload (<<) to enable an easy way to print the state of a
* MAFilter instance to an output stream.
* Does not print a newline control character.
*/
template <size_t N, typename Tval, typename Tcoeff>
std::ostream& operator<<(std::ostream& os, MAFilter<N,Tval,Tcoeff>& filter) {
os << "Block MAFilter: '" << filter.getName() << "' is enabled=";
os << filter.enabled << ", ";
os << "coefficients:[" << filter.coefficients[0];
for(size_t i = 1; i < N; i++){
os << "," << filter.coefficients[i];
}
os << "], ";
os << "previousValues:[" << filter.previousValues[0];
for(size_t i = 1; i < N; i++){
os << "," << filter.previousValues[i];
}
os << "]";
}
};
};
#endif /* ORG_EEROS_CONTROL_MAFILTER_HPP_ */
<commit_msg>fix(MAFilter) fix comment. fix syntax.<commit_after>#ifndef ORG_EEROS_CONTROL_MAFILTER_HPP_
#define ORG_EEROS_CONTROL_MAFILTER_HPP_
#include <eeros/control/Block1i1o.hpp>
#include <ostream>
namespace eeros {
namespace control {
/**
* A moving average filter (MAFilter) block is used to filter an input signal.
* The output signal value depends linearly on the current and various past
* input signal values.
* This is achieved by multiplying the current and the past values with
* the specified coefficients. The results are accumulated and yield to the
* output signal. The following terms represents the operation performed in
* this block.
*
* y[t] = c[0]*x[t-N] + c[1]*x[t-N+1] + ... + c[N]*x[t]
*
* Outp = c[0]*prev[0] + c[1]*prev[1] + ... + c[N]*Inp
*
* MAFilter is a Class Template with two type and one non-type template arguments.
* The two type template arguments specify the types which are used for the
* values and the coefficients when the class template is instanciated.
* The non-type template argument specifies the number of coefficients and the
* number of concidered past values respectively.
*
* @tparam N - number of coefficients
* @tparam Tval - value type (double - default type)
* @tparam Tcoeff - coefficients type (Tval - default value)
*
* @since v0.6
*/
template <size_t N, typename Tval = double, typename Tcoeff = Tval>
class MAFilter : public Block1i1o<Tval> {
public:
/**
* Constructs a MAFilter instance with the coefficients coeff.\n
* @param coeff - coefficients
*/
explicit MAFilter(Tcoeff (& coeff)[N]) : coefficients{coeff} {}
/**
* Runs the filter algorithm.
*
* Performs the calculation of the filtered output signal value.
* Multiplies the current and past input signal values with the coefficients.
* The coefficients weight the current and past input signal values. Finally,
* the resulting values are accumulated and yield to the output signal value
* if the filter instance is enabled. Otherwise, the output signal value is
* set to the actual input signal value.
*
* The timestamp value will not be altered.
*
* @see enable()
* @see disable()
*/
virtual void run() {
Tval result{};
for(size_t i = 0; i < N; i++) {
if(i < N-1) {
previousValues[i] = previousValues[i+1];
} else {
previousValues[i] = this->in.getSignal().getValue();
}
result += coefficients[i] * previousValues[i];
}
if(enabled) {
this->out.getSignal().setValue(result);
} else {
this->out.getSignal().setValue(this->in.getSignal().getValue());
}
this->out.getSignal().setTimestamp(this->in.getSignal().getTimestamp());
}
/**
* Enables the filter.
*
* If enabled, run() will set the output signal value to the accumulated values
* which result from the current and the past values weighted by the coefficients.
*
* @see run()
*/
virtual void enable() {
enabled = true;
}
/**
* Disables the filter.
*
* If disabled, run() will set the output signal to the input signal.
*
* @see run()
*/
virtual void disable() {
enabled = false;
}
/*
* Friend operator overload to give the operator overload outside
* the class access to the private fields.
*/
template <size_t No, typename ValT, typename CoeffT>
friend std::ostream& operator<<(std::ostream& os, MAFilter<No,ValT,CoeffT>& filter);
protected:
Tcoeff * coefficients;
Tval previousValues[N]{};
bool enabled{true};
};
/**
* Operator overload (<<) to enable an easy way to print the state of a
* MAFilter instance to an output stream.
* Does not print a newline control character.
*/
template <size_t N, typename Tval, typename Tcoeff>
std::ostream& operator<<(std::ostream& os, MAFilter<N,Tval,Tcoeff>& filter) {
os << "Block MAFilter: '" << filter.getName() << "' is enabled=";
os << filter.enabled << ", ";
os << "coefficients:[" << filter.coefficients[0];
for(size_t i = 1; i < N; i++){
os << "," << filter.coefficients[i];
}
os << "], ";
os << "previousValues:[" << filter.previousValues[0];
for(size_t i = 1; i < N; i++){
os << "," << filter.previousValues[i];
}
os << "]";
}
};
};
#endif /* ORG_EEROS_CONTROL_MAFILTER_HPP_ */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xcreator.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:40:35 $
*
* 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 __XCREATOR_HXX_
#define __XCREATOR_HXX_
#ifndef _COM_SUN_STAR_EMBED_XEMBEDOBJECTCREATOR_HPP_
#include <com/sun/star/embed/XEmbedObjectCreator.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XEMBEDOBJECTFACTORY_HPP_
#include <com/sun/star/embed/XEmbedObjectFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XLINKCREATOR_HPP_
#include <com/sun/star/embed/XLinkCreator.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XLINKFACTORY_HPP_
#include <com/sun/star/embed/XLinkFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#include "confighelper.hxx"
class UNOEmbeddedObjectCreator : public ::cppu::WeakImplHelper5<
::com::sun::star::embed::XEmbedObjectCreator,
::com::sun::star::embed::XEmbedObjectFactory,
::com::sun::star::embed::XLinkCreator,
::com::sun::star::embed::XLinkFactory,
::com::sun::star::lang::XServiceInfo >
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;
ConfigurationHelper m_aConfigHelper;
public:
UNOEmbeddedObjectCreator(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory )
: m_xFactory( xFactory )
, m_aConfigHelper( xFactory )
{
OSL_ENSURE( xFactory.is(), "No service manager is provided!\n" );
}
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL impl_staticGetSupportedServiceNames();
static ::rtl::OUString SAL_CALL impl_staticGetImplementationName();
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
impl_staticCreateSelfInstance(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
// XEmbedObjectCreator
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitNew( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const ::rtl::OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitFromEntry( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMedDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitFromMediaDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XEmbedObjectFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceUserInit( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const ::rtl::OUString& sClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, sal_Int32 nEntryConnectionMode, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aObjectArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XLinkCreator
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceLink( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XLinkFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceLinkUserInit( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aClassID, const ::rtl::OUString& sClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntryName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aObjectArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS oj14 (1.8.24); FILE MERGED 2006/03/20 08:42:07 oj 1.8.24.1: use mimeconfighelper<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xcreator.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2007-07-06 10:10:15 $
*
* 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 __XCREATOR_HXX_
#define __XCREATOR_HXX_
#ifndef _COM_SUN_STAR_EMBED_XEMBEDOBJECTCREATOR_HPP_
#include <com/sun/star/embed/XEmbedObjectCreator.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XEMBEDOBJECTFACTORY_HPP_
#include <com/sun/star/embed/XEmbedObjectFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XLINKCREATOR_HPP_
#include <com/sun/star/embed/XLinkCreator.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XLINKFACTORY_HPP_
#include <com/sun/star/embed/XLinkFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
#ifndef _COMPHELPER_MIMECONFIGHELPER_HXX_
#include <comphelper/mimeconfighelper.hxx>
#endif
class UNOEmbeddedObjectCreator : public ::cppu::WeakImplHelper5<
::com::sun::star::embed::XEmbedObjectCreator,
::com::sun::star::embed::XEmbedObjectFactory,
::com::sun::star::embed::XLinkCreator,
::com::sun::star::embed::XLinkFactory,
::com::sun::star::lang::XServiceInfo >
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;
::comphelper::MimeConfigurationHelper m_aConfigHelper;
public:
UNOEmbeddedObjectCreator(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory )
: m_xFactory( xFactory )
, m_aConfigHelper( xFactory )
{
OSL_ENSURE( xFactory.is(), "No service manager is provided!\n" );
}
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL impl_staticGetSupportedServiceNames();
static ::rtl::OUString SAL_CALL impl_staticGetImplementationName();
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
impl_staticCreateSelfInstance(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
// XEmbedObjectCreator
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitNew( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const ::rtl::OUString& aClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitFromEntry( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMedDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceInitFromMediaDescriptor( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XEmbedObjectFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceUserInit( const ::com::sun::star::uno::Sequence< sal_Int8 >& aClassID, const ::rtl::OUString& sClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, sal_Int32 nEntryConnectionMode, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aObjectArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XLinkCreator
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceLink( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aMediaDescr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lObjArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XLinkFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceLinkUserInit( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aClassID, const ::rtl::OUString& sClassName, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage, const ::rtl::OUString& sEntryName, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aObjectArgs ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>
|
<commit_before>//!
//! @author @Yue Wang @shbling
//!
//! Exercise 10.24:
//! Use bind and check_size to find the first element in a vector of ints that
//! has a value greater than the length of a specified string value.
//!
// Discussion over this exercise on StackOverflow
// http://stackoverflow.com/questions/20539406/what-type-does-stdfind-if-not-return
//!
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
using namespace std::placeholders;
bool check_size(const string &s, string::size_type sz)
{
return s.size()<sz;
}
vector<int>::const_iterator find_first_bigger(const vector<int> &v, const string &s)
{
return find_if(v.cbegin(), v.cend(), bind(check_size, s, _1));
}
int main()
{
vector<int> v{3,2,5,0,6,5,3,9,5};
string s("test");
cout<<*find_first_bigger(v, s)<<endl;
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
using namespace std::placeholders;
bool check_size(const string &s, int i)
{
return s.size()<i;
}
int main()
{
vector<int> v{3,2,5,0,3,5,3,9,5};
cout<<*find_if(v.cbegin(), v.cend(), bind(check_size, "test", _1))<<endl;
}
<commit_msg>Update ex10_24.cpp<commit_after>//!
//! @author @Yue Wang @shbling
//!
//! Exercise 10.24:
//! Use bind and check_size to find the first element in a vector of ints that
//! has a value greater than the length of a specified string value.
//!
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
using namespace std::placeholders;
bool check_size(const string &s, string::size_type sz)
{
return s.size()<sz;
}
vector<int>::const_iterator find_first_bigger(const vector<int> &v, const string &s)
{
return find_if(v.cbegin(), v.cend(), bind(check_size, s, _1));
}
int main()
{
vector<int> v{3,2,5,0,6,5,3,9,5};
string s("test");
cout<<*find_first_bigger(v, s)<<endl;
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
using namespace std::placeholders;
bool check_size(const string &s, int i)
{
return s.size()<i;
}
int main()
{
vector<int> v{3,2,5,0,3,5,3,9,5};
cout<<*find_if(v.cbegin(), v.cend(), bind(check_size, "test", _1))<<endl;
}
<|endoftext|>
|
<commit_before>//
// ex13_26.cpp
// Exercise 13.26
//
// Created by pezy on 1/19/15.
// Copyright (c) 2014 pezy. All rights reserved.
//
// Write your own version of the StrBlob class described in the previous
// exercise.
//
// @See ex12_22 and ex13_25
#include "ex13_26.h"
ConstStrBlobPtr StrBlob::begin() const // should add const
{
return ConstStrBlobPtr(*this);
}
ConstStrBlobPtr StrBlob::end() const // should add const
{
return ConstStrBlobPtr(*this, data->size());
}
StrBlob& StrBlob::operator=(const StrBlob& sb)
{
data = std::make_shared<vector<string>>(*sb.data);
return *this;
}
<commit_msg>Update ex13_26.cpp<commit_after>//
// ex13_26.cpp
// Exercise 13.26
//
// @See ex12_22 and ex13_25
//
#include "ex12_26.h"
StrBlob &StrBlob::operator=(const StrBlob &sb)
{
data=make_shared<vector<string>>(*sb.data);
return *this;
}
ConstStrBlobPtr StrBlob::begin() const // should add const
{
return ConstStrBlobPtr(*this);
}
ConstStrBlobPtr StrBlob::end() const // should add const
{
return ConstStrBlobPtr(*this, data->size());
}
<|endoftext|>
|
<commit_before>//
// ex13_28.cpp
// Exercise 13.28
//
// Created by pezy on 1/20/15.
//
// Given the following classes, implement a default constructor and the necessary copy-control members.
#include "ex13_28.h"
TreeNode& TreeNode::operator=(const TreeNode &rhs)
{
++*rhs.count;
if (--*count == 0) {
if (left) {
delete left;
}
if (right) {
delete right;
}
delete count;
}
value = rhs.value;
left = rhs.left;
right = rhs.right;
count = rhs.count;
return *this;
}
BinStrTree& BinStrTree::operator=(const BinStrTree &bst)
{
TreeNode *new_root = new TreeNode(*bst.root);
delete root;
root = new_root;
return *this;
}
int main()
{
return 0;
}
<commit_msg>Update ex13_28.cpp<commit_after>//
// ex13_28.cpp
// Exercise 13.28
//
// Created by pezy on 1/20/15.
//
// Given the following classes, implement a default constructor and the necessary copy-control members.
#include "ex13_28.h"
TreeNode& TreeNode::operator=(const TreeNode &rhs)
{
++*rhs.count;
if (--*count == 0) {
delete left;
delete right;
delete count;
}
value = rhs.value;
left = rhs.left;
right = rhs.right;
count = rhs.count;
return *this;
}
BinStrTree& BinStrTree::operator=(const BinStrTree &bst)
{
TreeNode *new_root = new TreeNode(*bst.root);
delete root;
root = new_root;
return *this;
}
int main()
{
return 0;
}
<|endoftext|>
|
<commit_before>#include "common-header.hpp"
template <class T>
struct double_first_half {
};
static_assert(
mpl::equal<
double_first_half< mpl::vector_c<int, 1, 2, 3, 4> >::type,
mpl::vector_c<int, 2, 4, 3, 4>
>::type::value,
"equal");
<commit_msg>stuck by 5-1<commit_after>#include "common-header.hpp"
//template <class First, class Last>
//struct concat {
//
//};
//
//template <class T>
//struct double_first_half {
//
//};
//
//static_assert(
// mpl::equal<
// double_first_half< mpl::vector_c<int, 1, 2, 3, 4> >::type,
// mpl::vector_c<int, 2, 4, 3, 4>
// >::type::value,
// "equal");
/**
* fold test
*/
template <class first, class last, class init, class bo>
struct fold
:mpl::if_<
std::is_same<first, last>,
init,
fold<
typename mpl::next<first>::type,
last,
typename mpl::apply<
bo,
init,
typename mpl::deref<first>::type
>::type,
bo
>
>
{ };
typedef mpl::vector_c<int, 1> vec0;
typedef mpl::int_<1> answer0;
typedef fold<
mpl::begin<vec0>::type,
mpl::end<vec0>::type,
mpl::int_<0>,
mpl::plus<_1, _2>
>::type fold_res0;
static_assert(std::is_same<answer0, fold_res0>::value, "fold one element");
typedef mpl::vector_c<int, 1, 2, 3, 4> vec_c;
typedef mpl::int_<10> answer;
typedef fold<
mpl::begin<vec_c>::type,
mpl::end<vec_c>::type,
mpl::int_<0>,
mpl::plus<_1, _2>
>::type fold_res;
static_assert( std::is_same<answer, fold_res>::value, "fold more elements");
/*
* push_back test
*/
typedef mpl::vector<short, unsigned, short> vec;
typedef mpl::vector<short, unsigned, short, long> vec1;
static_assert(
mpl::equal<
vec1,
mpl::push_back<vec, long >::type
>::type::value,
"push_back");
<|endoftext|>
|
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/contrib/lite/testing/tflite_driver.h"
#include <iostream>
#include "tensorflow/contrib/lite/testing/split.h"
namespace tflite {
namespace testing {
namespace {
// Returns the value in the given position in a tensor.
template <typename T>
T Value(const TfLitePtrUnion& data, int index);
template <>
float Value(const TfLitePtrUnion& data, int index) {
return data.f[index];
}
template <>
int32_t Value(const TfLitePtrUnion& data, int index) {
return data.i32[index];
}
template <>
int64_t Value(const TfLitePtrUnion& data, int index) {
return data.i64[index];
}
template <>
uint8_t Value(const TfLitePtrUnion& data, int index) {
return data.uint8[index];
}
template <typename T>
void SetTensorData(const std::vector<T>& values, TfLitePtrUnion* data) {
T* input_ptr = reinterpret_cast<T*>(data->raw);
for (const T& v : values) {
*input_ptr = v;
++input_ptr;
}
}
} // namespace
class TfLiteDriver::Expectation {
public:
Expectation() { data_.raw = nullptr; }
~Expectation() { delete[] data_.raw; }
template <typename T>
void SetData(const string& csv_values) {
const auto& values = testing::Split<T>(csv_values, ",");
data_.raw = new char[values.size() * sizeof(T)];
SetTensorData(values, &data_);
}
bool Check(bool verbose, const TfLiteTensor& tensor) {
switch (tensor.type) {
case kTfLiteFloat32:
return TypedCheck<float>(verbose, tensor);
case kTfLiteInt32:
return TypedCheck<int32_t>(verbose, tensor);
case kTfLiteInt64:
return TypedCheck<int64_t>(verbose, tensor);
case kTfLiteUInt8:
return TypedCheck<uint8_t>(verbose, tensor);
default:
fprintf(stderr, "Unsupported type %d in Check\n", tensor.type);
return false;
}
}
private:
template <typename T>
bool TypedCheck(bool verbose, const TfLiteTensor& tensor) {
// TODO(ahentz): must find a way to configure the tolerance.
constexpr double kRelativeThreshold = 1e-2f;
constexpr double kAbsoluteThreshold = 1e-4f;
int tensor_size = tensor.bytes / sizeof(T);
bool good_output = true;
for (int i = 0; i < tensor_size; ++i) {
float computed = Value<T>(tensor.data, i);
float reference = Value<T>(data_, i);
float diff = std::abs(computed - reference);
bool error_is_large = false;
// For very small numbers, try absolute error, otherwise go with
// relative.
if (std::abs(reference) < kRelativeThreshold) {
error_is_large = (diff > kAbsoluteThreshold);
} else {
error_is_large = (diff > kRelativeThreshold * std::abs(reference));
}
if (error_is_large) {
good_output = false;
if (verbose) {
std::cerr << " index " << i << ": got " << computed
<< ", but expected " << reference << std::endl;
}
}
}
return good_output;
}
TfLitePtrUnion data_;
};
TfLiteDriver::TfLiteDriver(bool use_nnapi) : use_nnapi_(use_nnapi) {}
TfLiteDriver::~TfLiteDriver() {}
void TfLiteDriver::AllocateTensors() {
if (must_allocate_tensors_) {
if (interpreter_->AllocateTensors() != kTfLiteOk) {
Invalidate("Failed to allocate tensors");
return;
}
must_allocate_tensors_ = false;
}
}
void TfLiteDriver::LoadModel(const string& bin_file_path) {
if (!IsValid()) return;
std::cout << std::endl << "Loading model: " << bin_file_path << std::endl;
model_ = FlatBufferModel::BuildFromFile(GetFullPath(bin_file_path).c_str());
if (!model_) {
Invalidate("Failed to mmap model " + bin_file_path);
return;
}
ops::builtin::BuiltinOpResolver builtins;
InterpreterBuilder(*model_, builtins)(&interpreter_);
if (!interpreter_) {
Invalidate("Failed build interpreter");
return;
}
must_allocate_tensors_ = true;
}
void TfLiteDriver::ResetTensor(int id) {
if (!IsValid()) return;
auto* tensor = interpreter_->tensor(id);
memset(tensor->data.raw, 0, tensor->bytes);
}
void TfLiteDriver::ReshapeTensor(int id, const string& csv_values) {
if (!IsValid()) return;
if (interpreter_->ResizeInputTensor(
id, testing::Split<int>(csv_values, ",")) != kTfLiteOk) {
Invalidate("Failed to resize input tensor " + std::to_string(id));
return;
}
must_allocate_tensors_ = true;
}
void TfLiteDriver::SetInput(int id, const string& csv_values) {
if (!IsValid()) return;
auto* tensor = interpreter_->tensor(id);
switch (tensor->type) {
case kTfLiteFloat32: {
const auto& values = testing::Split<float>(csv_values, ",");
if (!CheckSizes<float>(tensor->bytes, values.size())) return;
SetTensorData(values, &tensor->data);
break;
}
case kTfLiteInt32: {
const auto& values = testing::Split<int32_t>(csv_values, ",");
if (!CheckSizes<int32_t>(tensor->bytes, values.size())) return;
SetTensorData(values, &tensor->data);
break;
}
case kTfLiteInt64: {
const auto& values = testing::Split<int64_t>(csv_values, ",");
if (!CheckSizes<int64_t>(tensor->bytes, values.size())) return;
SetTensorData(values, &tensor->data);
break;
}
case kTfLiteUInt8: {
const auto& values = testing::Split<uint8_t>(csv_values, ",");
if (!CheckSizes<uint8_t>(tensor->bytes, values.size())) return;
SetTensorData(values, &tensor->data);
break;
}
default:
fprintf(stderr, "Unsupported type %d in SetInput\n", tensor->type);
Invalidate("Unsupported tensor data type");
return;
}
}
void TfLiteDriver::SetExpectation(int id, const string& csv_values) {
if (!IsValid()) return;
auto* tensor = interpreter_->tensor(id);
if (expected_output_.count(id) != 0) {
fprintf(stderr, "Overriden expectation for tensor %d\n", id);
Invalidate("Overriden expectation");
}
expected_output_[id].reset(new Expectation);
switch (tensor->type) {
case kTfLiteFloat32:
expected_output_[id]->SetData<float>(csv_values);
break;
case kTfLiteInt32:
expected_output_[id]->SetData<int32_t>(csv_values);
break;
case kTfLiteInt64:
expected_output_[id]->SetData<int64_t>(csv_values);
break;
case kTfLiteUInt8:
expected_output_[id]->SetData<uint8_t>(csv_values);
break;
default:
fprintf(stderr, "Unsupported type %d in SetExpectation\n", tensor->type);
Invalidate("Unsupported tensor data type");
return;
}
}
void TfLiteDriver::Invoke() {
if (!IsValid()) return;
if (interpreter_->Invoke() != kTfLiteOk) {
Invalidate("Failed to invoke interpreter");
}
}
bool TfLiteDriver::CheckResults() {
if (!IsValid()) return false;
bool success = true;
for (const auto& p : expected_output_) {
int id = p.first;
auto* tensor = interpreter_->tensor(id);
if (!p.second->Check(/*verbose=*/false, *tensor)) {
// Do not invalidate anything here. Instead, simply output the
// differences and return false. Invalidating would prevent all
// subsequent invocations from running..
std::cerr << "There were errors in invocation '" << GetInvocationId()
<< "', output tensor '" << id << "':" << std::endl;
p.second->Check(/*verbose=*/true, *tensor);
success = false;
SetOverallSuccess(false);
}
}
expected_output_.clear();
return success;
}
} // namespace testing
} // namespace tflite
<commit_msg>Make sure tensor size match before inspecting their content.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/contrib/lite/testing/tflite_driver.h"
#include <iostream>
#include "tensorflow/contrib/lite/testing/split.h"
namespace tflite {
namespace testing {
namespace {
// Returns the value in the given position in a tensor.
template <typename T>
T Value(const TfLitePtrUnion& data, int index);
template <>
float Value(const TfLitePtrUnion& data, int index) {
return data.f[index];
}
template <>
int32_t Value(const TfLitePtrUnion& data, int index) {
return data.i32[index];
}
template <>
int64_t Value(const TfLitePtrUnion& data, int index) {
return data.i64[index];
}
template <>
uint8_t Value(const TfLitePtrUnion& data, int index) {
return data.uint8[index];
}
template <typename T>
void SetTensorData(const std::vector<T>& values, TfLitePtrUnion* data) {
T* input_ptr = reinterpret_cast<T*>(data->raw);
for (const T& v : values) {
*input_ptr = v;
++input_ptr;
}
}
} // namespace
class TfLiteDriver::Expectation {
public:
Expectation() {
data_.raw = nullptr;
num_elements_ = 0;
}
~Expectation() { delete[] data_.raw; }
template <typename T>
void SetData(const string& csv_values) {
const auto& values = testing::Split<T>(csv_values, ",");
num_elements_ = values.size();
data_.raw = new char[num_elements_ * sizeof(T)];
SetTensorData(values, &data_);
}
bool Check(bool verbose, const TfLiteTensor& tensor) {
switch (tensor.type) {
case kTfLiteFloat32:
return TypedCheck<float>(verbose, tensor);
case kTfLiteInt32:
return TypedCheck<int32_t>(verbose, tensor);
case kTfLiteInt64:
return TypedCheck<int64_t>(verbose, tensor);
case kTfLiteUInt8:
return TypedCheck<uint8_t>(verbose, tensor);
default:
fprintf(stderr, "Unsupported type %d in Check\n", tensor.type);
return false;
}
}
private:
template <typename T>
bool TypedCheck(bool verbose, const TfLiteTensor& tensor) {
// TODO(ahentz): must find a way to configure the tolerance.
constexpr double kRelativeThreshold = 1e-2f;
constexpr double kAbsoluteThreshold = 1e-4f;
size_t tensor_size = tensor.bytes / sizeof(T);
if (tensor_size != num_elements_) {
std::cerr << "Expected a tensor with " << num_elements_
<< " elements, got " << tensor_size << std::endl;
return false;
}
bool good_output = true;
for (int i = 0; i < tensor_size; ++i) {
float computed = Value<T>(tensor.data, i);
float reference = Value<T>(data_, i);
float diff = std::abs(computed - reference);
bool error_is_large = false;
// For very small numbers, try absolute error, otherwise go with
// relative.
if (std::abs(reference) < kRelativeThreshold) {
error_is_large = (diff > kAbsoluteThreshold);
} else {
error_is_large = (diff > kRelativeThreshold * std::abs(reference));
}
if (error_is_large) {
good_output = false;
if (verbose) {
std::cerr << " index " << i << ": got " << computed
<< ", but expected " << reference << std::endl;
}
}
}
return good_output;
}
TfLitePtrUnion data_;
size_t num_elements_;
};
TfLiteDriver::TfLiteDriver(bool use_nnapi) : use_nnapi_(use_nnapi) {}
TfLiteDriver::~TfLiteDriver() {}
void TfLiteDriver::AllocateTensors() {
if (must_allocate_tensors_) {
if (interpreter_->AllocateTensors() != kTfLiteOk) {
Invalidate("Failed to allocate tensors");
return;
}
must_allocate_tensors_ = false;
}
}
void TfLiteDriver::LoadModel(const string& bin_file_path) {
if (!IsValid()) return;
std::cout << std::endl << "Loading model: " << bin_file_path << std::endl;
model_ = FlatBufferModel::BuildFromFile(GetFullPath(bin_file_path).c_str());
if (!model_) {
Invalidate("Failed to mmap model " + bin_file_path);
return;
}
ops::builtin::BuiltinOpResolver builtins;
InterpreterBuilder(*model_, builtins)(&interpreter_);
if (!interpreter_) {
Invalidate("Failed build interpreter");
return;
}
must_allocate_tensors_ = true;
}
void TfLiteDriver::ResetTensor(int id) {
if (!IsValid()) return;
auto* tensor = interpreter_->tensor(id);
memset(tensor->data.raw, 0, tensor->bytes);
}
void TfLiteDriver::ReshapeTensor(int id, const string& csv_values) {
if (!IsValid()) return;
if (interpreter_->ResizeInputTensor(
id, testing::Split<int>(csv_values, ",")) != kTfLiteOk) {
Invalidate("Failed to resize input tensor " + std::to_string(id));
return;
}
must_allocate_tensors_ = true;
}
void TfLiteDriver::SetInput(int id, const string& csv_values) {
if (!IsValid()) return;
auto* tensor = interpreter_->tensor(id);
switch (tensor->type) {
case kTfLiteFloat32: {
const auto& values = testing::Split<float>(csv_values, ",");
if (!CheckSizes<float>(tensor->bytes, values.size())) return;
SetTensorData(values, &tensor->data);
break;
}
case kTfLiteInt32: {
const auto& values = testing::Split<int32_t>(csv_values, ",");
if (!CheckSizes<int32_t>(tensor->bytes, values.size())) return;
SetTensorData(values, &tensor->data);
break;
}
case kTfLiteInt64: {
const auto& values = testing::Split<int64_t>(csv_values, ",");
if (!CheckSizes<int64_t>(tensor->bytes, values.size())) return;
SetTensorData(values, &tensor->data);
break;
}
case kTfLiteUInt8: {
const auto& values = testing::Split<uint8_t>(csv_values, ",");
if (!CheckSizes<uint8_t>(tensor->bytes, values.size())) return;
SetTensorData(values, &tensor->data);
break;
}
default:
fprintf(stderr, "Unsupported type %d in SetInput\n", tensor->type);
Invalidate("Unsupported tensor data type");
return;
}
}
void TfLiteDriver::SetExpectation(int id, const string& csv_values) {
if (!IsValid()) return;
auto* tensor = interpreter_->tensor(id);
if (expected_output_.count(id) != 0) {
fprintf(stderr, "Overriden expectation for tensor %d\n", id);
Invalidate("Overriden expectation");
}
expected_output_[id].reset(new Expectation);
switch (tensor->type) {
case kTfLiteFloat32:
expected_output_[id]->SetData<float>(csv_values);
break;
case kTfLiteInt32:
expected_output_[id]->SetData<int32_t>(csv_values);
break;
case kTfLiteInt64:
expected_output_[id]->SetData<int64_t>(csv_values);
break;
case kTfLiteUInt8:
expected_output_[id]->SetData<uint8_t>(csv_values);
break;
default:
fprintf(stderr, "Unsupported type %d in SetExpectation\n", tensor->type);
Invalidate("Unsupported tensor data type");
return;
}
}
void TfLiteDriver::Invoke() {
if (!IsValid()) return;
if (interpreter_->Invoke() != kTfLiteOk) {
Invalidate("Failed to invoke interpreter");
}
}
bool TfLiteDriver::CheckResults() {
if (!IsValid()) return false;
bool success = true;
for (const auto& p : expected_output_) {
int id = p.first;
auto* tensor = interpreter_->tensor(id);
if (!p.second->Check(/*verbose=*/false, *tensor)) {
// Do not invalidate anything here. Instead, simply output the
// differences and return false. Invalidating would prevent all
// subsequent invocations from running..
std::cerr << "There were errors in invocation '" << GetInvocationId()
<< "', output tensor '" << id << "':" << std::endl;
p.second->Check(/*verbose=*/true, *tensor);
success = false;
SetOverallSuccess(false);
}
}
expected_output_.clear();
return success;
}
} // namespace testing
} // namespace tflite
<|endoftext|>
|
<commit_before>#include "PlanarAccelerationModule.h"
#include "OrientationSensorsWrapper.h"
#include "DualEncoderDriver.h"
#include "MotorDriver.h"
#include "constants.h"
void PlanarAcceleration::calibrate()
{
acc_offset_x = 0;
acc_offset_y = 0;
int samples_count = 0;
uint32_t start_micros = micros();
uint32_t last_micros = start_micros - MICROS_PER_SECOND;
float last_left_speed = 0;
float last_right_speed = 0;
setMotors(MOTORS_CALIBRATE_SPEED);
while(true)
{
uint32_t current_micros = micros();
if(current_micros - start_micros > MICROS_PER_SECOND / 3)
return;
if(current_micros - last_micros < MICROS_PER_SECOND / CALIBRATION_FREQUENCY)
continue;
float left_speed = leftEncoder.getSpeed();
float right_speed = rightEncoder.getSpeed();
float acceleration = (left_speed + right_speed - last_left_speed - last_right_speed) / 2;
acc_offset_x += position.getAccX();
acc_offset_y += position.getAccY() - acceleration;
++samples_count;
last_left_speed = left_speed;
last_right_speed = right_speed;
}
acc_offset_x /= samples_count;
acc_offset_y /= samples_count;
Serial.print("Planar: ");
Serial.print(acc_offset_x); Serial.print(" ");
Serial.print(acc_offset_y); Serial.println("");
setMotors(0, 0);
}
PlanarAcceleration plannarAcceleration;
<commit_msg>Bug fix module<commit_after>#include "PlanarAccelerationModule.h"
#include "OrientationSensorsWrapper.h"
#include "DualEncoderDriver.h"
#include "MotorDriver.h"
#include "constants.h"
void PlanarAcceleration::calibrate()
{
acc_offset_x = 0;
acc_offset_y = 0;
int samples_count = 0;
uint32_t start_micros = micros();
uint32_t last_micros = start_micros - MICROS_PER_SECOND;
float last_left_speed = 0;
float last_right_speed = 0;
setMotors(MOTORS_CALIBRATE_SPEED);
while(true)
{
uint32_t current_micros = micros();
if(current_micros - start_micros > MICROS_PER_SECOND / 3)
break;
if(current_micros - last_micros < MICROS_PER_SECOND / CALIBRATION_FREQUENCY)
continue;
float left_speed = leftEncoder.getSpeed();
float right_speed = rightEncoder.getSpeed();
float acceleration = (left_speed + right_speed - last_left_speed - last_right_speed) / 2;
acc_offset_x += position.getAccX();
acc_offset_y += position.getAccY() - acceleration;
++samples_count;
last_left_speed = left_speed;
last_right_speed = right_speed;
last_micros = current_micros;
}
acc_offset_x /= samples_count;
acc_offset_y /= samples_count;
setMotors(0, 0);
}
PlanarAcceleration plannarAcceleration;
<|endoftext|>
|
<commit_before>/*
* @author Howard Roatti
* @date 07/2015
* @contact howardcruzroatti@gmail.com
*/
#include "Utils.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <getopt.h>
#include "IDF.h"
#include "ICF.h"
#include "RF.h"
#include "ICFBASED.h"
#include "RFXIDF.h"
#include "QUIQUAD.h"
using namespace std;
char *optarg;
int c, opc = 1, tipo = 0;
long norm = 0, reducto = 0;
float limite;
int main(int argc, char* argv[]) {
while ((c = getopt(argc, argv, "p:v:m:c:n:")) != -1) {
switch (c) {
case 'p' :
opc = ENUM(optarg);
printf("Ponderacao: %s\n", vet[opc]);
//if(opc == 0) exit;//TF
break;
case 'v' :
tipo = 0;
mDensa = optarg;
entrada = fopen(mDensa, "r");
if(entrada == NULL){
printf("Erro ao tentar abrir o arquivo %s\n", mDensa);
fclose(entrada);
exit(1);
};
printf("Matriz Densa: %s\n", mDensa);
break;
case 'm' :
tipo = 1;
mMarket = optarg;
entrada = fopen(mMarket, "r");
if(entrada == NULL){
printf("Erro ao tentar abrir o arquivo %s\n", mMarket);
fclose(entrada);
exit(2);
};
fgets(lixo, MAX, entrada);//Remove o texto que expressa o tipo de documento
printf("Matrix Market: %s\n", mMarket);
break;
case 'c' :
lClasses = optarg;
if(opc > 1){//Se precisa das classes para calcular
arqClasses = fopen(lClasses, "r");
if(arqClasses == NULL){
printf("Erro ao tentar abrir o arquivo %s\n", lClasses);
fclose(arqClasses);
exit(3);
};
}
printf("Classes: %s\n", lClasses);
break;
case 'n' :
if(strcmp(optarg, "tf") == 0){
norm = 0;
}else if(strcmp(optarg, "log") == 0){
norm = 1;
}
printf("Normalizar: %s\n", optarg);
break;
case 'r':
if(strcmp(optarg, "quiquad") == 0 ){
reducto = 1;
}else if(strcmp(optarg, "docs") == 0 ){
reducto = 2;
}
printf("Reducao de dimensionalidade: %s\n", optarg);
break;
case 'a':
limite = atof(optarg);
break;
default:
printf("Parâmetro não existe.\n -p -> Tipo de Ponderacao\n -v -> Matriz Densa\n -m -> Matrix Market\n -c -> Lista de Classes\n -v (tf|log)\n");
return 0;
}
}
fscanf(entrada, "%s", sLin);
fscanf(entrada, "%s", sCol);
fscanf(entrada, "%s", sEnt);
lin = atoi(sLin);
col = atoi(sCol);
ent = atoi(sEnt);
int linha = lin, coluna = col;
printf("Termos(%d):Documentos(%d)\n", coluna, linha);//Para fins de ilustração, imprime as dimensões da matriz
//Ler o arquivo de vetores
if(tipo == 1){//mtx
while(!feof(entrada)){
fscanf(entrada, "%s", sLin);
fscanf(entrada, "%s", sCol);
fscanf(entrada, "%s", sEnt);
lin = atoi(sLin);
col = atoi(sCol);
ent = atof(sEnt);
//printf("lin(%d) col(%d) ent(%g)\n", lin, col, ent);
if(lin <= linha)
dataSet[lin-1][col-1] = ent;
}
}else{//denso
for(int i = 0; i < linha; i++){
for(int j = 0; j < coluna; j++){
fscanf(entrada, "%s", sEnt);
ent = atof(sEnt);
if(ent > 0)
dataSet[i][j] = ent;
}
}
}
fclose(entrada);
//Ler o arquivo de classes
if(opc > 1 || reducto == 1){
for(i = 0; i < linha; i++){
fscanf(arqClasses, "%s", tmpLabel);
labels.push_back(tmpLabel);
labelsAccountability[tmpLabel]++;
classes[tmpLabel].push_back(i);
}
fclose(arqClasses);
}
/*Reducao de dimensionalidade*/
if(reducto == 1){
reductionPerQuiquad(linha, coluna, limite);
}else if(reducto == 2){
reductionPerDocs(linha, coluna, limite);
}
/*Ponderador*/
if(opc == 1){
weightsIDF(linha, coluna, norm);
}else if(opc == 2){
weightsICF(linha, coluna, norm);
}else if(opc == 3){
weightsRF(linha, coluna, norm);
}else if(opc == 4){
weightsICFBASED(linha, coluna, norm);
}else if(opc == 5){
weightsRFxIDF(linha, coluna, norm);
}else if(opc == 6){
weightsQUIQUAD(linha, coluna, norm);
}else if(opc == 0){
weightsTF(linha, coluna);
}else{
printf("Em desenvolvimento\n");
}
printf("Concluido!\n");
return 0;
}
<commit_msg>Adicionado novas opcoes de parametros.<commit_after>/*
* @author Howard Roatti
* @date 07/2015
* @contact howardcruzroatti@gmail.com
*/
#include "Utils.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <getopt.h>
#include "IDF.h"
#include "ICF.h"
#include "RF.h"
#include "ICFBASED.h"
#include "RFXIDF.h"
#include "QUIQUAD.h"
using namespace std;
char *optarg;
int c, opc = 1, tipo = 0;
long norm = 0, reducto = 0;
float limite;
int main(int argc, char* argv[]) {
while ((c = getopt(argc, argv, "p:v:m:c:n:r:a:")) != -1) {
switch (c) {
case 'p' :
opc = ENUM(optarg);
printf("Ponderacao: %s\n", vet[opc]);
//if(opc == 0) exit;//TF
break;
case 'v' :
tipo = 0;
mDensa = optarg;
entrada = fopen(mDensa, "r");
if(entrada == NULL){
printf("Erro ao tentar abrir o arquivo %s\n", mDensa);
fclose(entrada);
exit(1);
};
printf("Matriz Densa: %s\n", mDensa);
break;
case 'm' :
tipo = 1;
mMarket = optarg;
entrada = fopen(mMarket, "r");
if(entrada == NULL){
printf("Erro ao tentar abrir o arquivo %s\n", mMarket);
fclose(entrada);
exit(2);
};
fgets(lixo, MAX, entrada);//Remove o texto que expressa o tipo de documento
printf("Matrix Market: %s\n", mMarket);
break;
case 'c' :
lClasses = optarg;
// if(opc > 1){//Se precisa das classes para calcular
arqClasses = fopen(lClasses, "r");
if(arqClasses == NULL){
printf("Erro ao tentar abrir o arquivo %s\n", lClasses);
fclose(arqClasses);
exit(3);
}
// }
printf("Classes: %s\n", lClasses);
break;
case 'n' :
if(strcmp(optarg, "tf") == 0){
norm = 0;
}else if(strcmp(optarg, "log") == 0){
norm = 1;
}
printf("Normalizar: %s\n", optarg);
break;
case 'r':
if(strcmp(optarg, "quiquad") == 0 ){
reducto = 1;
}else if(strcmp(optarg, "docs") == 0 ){
reducto = 2;
}
printf("Reducao de dimensionalidade: %s\n", optarg);
break;
case 'a':
limite = atof(optarg);
break;
default:
printf("Parâmetro não existe.\n -p -> Tipo de Ponderacao\n -v -> Matriz Densa\n -m -> Matrix Market\n -c -> Lista de Classes\n -v (tf|log)\n");
return 0;
}
}
fscanf(entrada, "%s", sLin);
fscanf(entrada, "%s", sCol);
fscanf(entrada, "%s", sEnt);
lin = atoi(sLin);
col = atoi(sCol);
ent = atoi(sEnt);
int linha = lin, coluna = col;
printf("Termos(%d):Documentos(%d)\n", coluna, linha);//Para fins de ilustração, imprime as dimensões da matriz
//Ler o arquivo de vetores
if(tipo == 1){//mtx
while(!feof(entrada)){
fscanf(entrada, "%s", sLin);
fscanf(entrada, "%s", sCol);
fscanf(entrada, "%s", sEnt);
lin = atoi(sLin);
col = atoi(sCol);
ent = atof(sEnt);
//printf("lin(%d) col(%d) ent(%g)\n", lin, col, ent);
if(lin <= linha)
dataSet[lin-1][col-1] = ent;
}
}else{//denso
for(int i = 0; i < linha; i++){
for(int j = 0; j < coluna; j++){
fscanf(entrada, "%s", sEnt);
ent = atof(sEnt);
if(ent > 0)
dataSet[i][j] = ent;
}
}
}
fclose(entrada);
//Ler o arquivo de classes
if(opc > 1 || reducto == 1){
for(i = 0; i < linha; i++){
fscanf(arqClasses, "%s", tmpLabel);
labels.push_back(tmpLabel);
labelsAccountability[tmpLabel]++;
classes[tmpLabel].push_back(i);
}
fclose(arqClasses);
}
/*Reducao de dimensionalidade*/
if(reducto == 1){
reductionPerQuiquad(linha, coluna, limite);
}else if(reducto == 2){
reductionPerDocs(linha, coluna, limite);
}
/*Ponderador*/
if(opc == 1){
weightsIDF(linha, coluna, norm);
}else if(opc == 2){
weightsICF(linha, coluna, norm);
}else if(opc == 3){
weightsRF(linha, coluna, norm);
}else if(opc == 4){
weightsICFBASED(linha, coluna, norm);
}else if(opc == 5){
weightsRFxIDF(linha, coluna, norm);
}else if(opc == 6){
weightsQUIQUAD(linha, coluna, norm);
}else if(opc == 0){
weightsTF(linha, coluna);
}else{
printf("Em desenvolvimento\n");
}
printf("Concluido!\n");
return 0;
}
<|endoftext|>
|
<commit_before>#include "tests.h"
// Work efficient prefix sum
template <typename F, typename std::enable_if<std::is_floating_point<F>::value>::type* = nullptr>
bool check_sum(cl::sycl::buffer<F, 1>& data) {
using namespace cl::sycl;
auto d = data.get_access<access::read, access::host_buffer>();
F sum = 0;
for(size_t i = 0; i < data.get_count(); ++i) {
sum += (F)1;
auto diff = std::abs(sum - d[i]);
if(diff > 0.01) {
debug() << "wrong sum, should be" << sum << "- is" << d[i];
return false;
}
}
return true;
}
template <typename I, typename std::enable_if<std::is_integral<I>::value>::type* = nullptr>
bool check_sum(cl::sycl::buffer<I, 1>& data) {
using namespace cl::sycl;
auto d = data.get_access<access::read, access::host_buffer>();
I sum = 0;
for(size_t i = 0; i < data.get_count(); ++i) {
sum += (I)i;
if(d[i] != sum) {
debug() << "wrong sum, should be" << sum << "- is" << d[i];
return false;
}
}
return true;
}
template <typename T>
struct prefix_sum_kernel {
protected:
using mode = cl::sycl::access::mode;
using target = cl::sycl::access::target;
using buffer = cl::sycl::buffer<T>;
// Constants
size_t global_size;
// Global memory
cl::sycl::accessor<T> input;
cl::sycl::accessor<T, 1, mode::write> higher_level;
// Local memory
cl::sycl::accessor<T, 1, mode::read_write, target::local> localBlock;
public:
prefix_sum_kernel(cl::sycl::handler& cgh, buffer& data, buffer& higher_level, size_t global_size, size_t local_size)
: input(data.get_access<mode::read_write>(cgh)),
higher_level(higher_level.get_access<mode::write>(cgh)),
localBlock(local_size),
global_size(global_size) {}
void operator()(cl::sycl::nd_item<1> index) {
using namespace cl::sycl;
uint1 GID = 2 * index.get_global(0);
uint1 LID = 2 * index.get_local(0);
SYCL_IF(GID < global_size)
SYCL_BEGIN {
localBlock[LID] = input[GID];
localBlock[LID + 1] = input[GID + 1];
}
SYCL_END
index.barrier(access::fence_space::local);
uint1 local_size = 2 * index.get_local_range()[0];
uint1 first;
uint1 second;
LID /= 2;
// Up-sweep
uint1 offset = 1;
SYCL_WHILE(offset < local_size)
SYCL_BEGIN {
SYCL_IF(LID % offset == 0)
SYCL_BEGIN {
first = 2 * LID + offset - 1;
second = first + offset;
localBlock[second] = localBlock[first] + localBlock[second];
}
SYCL_END
index.barrier(access::fence_space::local);
offset *= 2;
}
SYCL_END
SYCL_IF(LID == 0)
SYCL_THEN({
localBlock[local_size - 1] = 0;
})
index.barrier(access::fence_space::local);
vec<T, 1> tmp;
// Down-sweep
offset = local_size;
SYCL_WHILE(offset > 0)
SYCL_BEGIN {
SYCL_IF(LID % offset == 0)
SYCL_BEGIN {
first = 2 * LID + offset - 1;
second = first + offset;
tmp = localBlock[second];
localBlock[second] = localBlock[first] + tmp;
localBlock[first] = tmp;
}
SYCL_END
index.barrier(access::fence_space::local);
offset /= 2;
}
SYCL_END
uint1 last_sum_id = GID + local_size - 1;
SYCL_IF(LID == 0 && last_sum_id < global_size)
SYCL_BEGIN {
// Write last sum into auxiliary array
higher_level[GID / local_size] = localBlock[local_size - 1] + input[last_sum_id];
}
SYCL_END
LID *= 2;
SYCL_IF(GID < global_size)
SYCL_BEGIN {
input[GID] += localBlock[LID];
input[GID + 1] += localBlock[LID + 1];
}
SYCL_END
}
};
template <typename T>
struct prefix_sum_join_kernel {
protected:
using mode = cl::sycl::access::mode;
using target = cl::sycl::access::target;
using buffer = cl::sycl::buffer<T>;
// Global memory
cl::sycl::accessor<T> data;
cl::sycl::accessor<T, 1, mode::read> higher_level;
public:
prefix_sum_join_kernel(cl::sycl::handler& cgh, buffer& data, buffer& higher_level)
: data(data.get_access<mode::read_write>(cgh)),
higher_level(higher_level.get_access<mode::read>(cgh)) {}
void operator()(cl::sycl::nd_item<1> index) {
using namespace cl::sycl;
int1 GID = index.get_global(0);
int1 local_size = 2 * index.get_local_range()[0];
SYCL_IF(GID >= local_size)
SYCL_THEN({
data[GID] += higher_level[GID / local_size - 1];
})
}
};
template <typename type>
void prefix_sum_recursion(
cl::sycl::queue& myQueue,
cl::sycl::vector_class<cl::sycl::buffer<type>>& data,
cl::sycl::vector_class<size_t>& sizes,
size_t level,
size_t group_size
) {
using namespace cl::sycl;
myQueue.submit([&](handler& cgh) {
cgh.parallel_for(
nd_range<1>(sizes[level] / 2, group_size),
prefix_sum_kernel<type>(cgh, data[level], data[level + 1], sizes[level], 2 * group_size)
);
});
if(sizes[level + 1] <= group_size) {
return;
}
prefix_sum_recursion(myQueue, data, sizes, level + 1, group_size);
// TODO: Extend for large arrays
}
bool test9() {
using namespace cl::sycl;
{
queue myQueue;
const auto group_size = myQueue.get_device().get_info<info::device::max_work_group_size>();
const auto size = group_size * 2;
size_t N = size;
using type = double;
// Calculate required number of buffer levels
N = size;
size_t number_levels = 1;
while(N > 0) {
N /= 2 * group_size;
++number_levels;
}
// Create buffers
vector_class<buffer<type>> data;
vector_class<size_t> sizes;
data.reserve(number_levels);
sizes.reserve(number_levels);
N = size;
for(size_t i = 0; i < number_levels; ++i) {
sizes.push_back(N);
data.emplace_back(N);
N = std::max(N / (2 * group_size), group_size);
N += N % 2; // Needs to be divisible by 2
}
// Init
myQueue.submit([&](handler& cgh) {
auto d = data[0].get_access<access::write>(cgh);
cgh.parallel_for<class init>(range<1>(size), [=](id<1> index) {
d[index] = 1;
});
});
prefix_sum_recursion(myQueue, data, sizes, 0, group_size);
debug() << "Done, checking results";
return check_sum(data[0]);
}
return true;
}
<commit_msg>Code for joining prefix sums.<commit_after>#include "tests.h"
// Work efficient prefix sum
template <typename F, typename std::enable_if<std::is_floating_point<F>::value>::type* = nullptr>
bool check_sum(cl::sycl::buffer<F, 1>& data) {
using namespace cl::sycl;
auto d = data.get_access<access::read, access::host_buffer>();
F sum = 0;
for(size_t i = 0; i < data.get_count(); ++i) {
sum += (F)1;
auto diff = std::abs(sum - d[i]);
if(diff > 0.01) {
debug() << "wrong sum, should be" << sum << "- is" << d[i];
return false;
}
}
return true;
}
template <typename I, typename std::enable_if<std::is_integral<I>::value>::type* = nullptr>
bool check_sum(cl::sycl::buffer<I, 1>& data) {
using namespace cl::sycl;
auto d = data.get_access<access::read, access::host_buffer>();
I sum = 0;
for(size_t i = 0; i < data.get_count(); ++i) {
sum += (I)i;
if(d[i] != sum) {
debug() << "wrong sum, should be" << sum << "- is" << d[i];
return false;
}
}
return true;
}
template <typename T>
struct prefix_sum_kernel {
protected:
using mode = cl::sycl::access::mode;
using target = cl::sycl::access::target;
using buffer = cl::sycl::buffer<T>;
// Constants
size_t global_size;
// Global memory
cl::sycl::accessor<T> input;
cl::sycl::accessor<T, 1, mode::write> higher_level;
// Local memory
cl::sycl::accessor<T, 1, mode::read_write, target::local> localBlock;
public:
prefix_sum_kernel(cl::sycl::handler& cgh, buffer& data, buffer& higher_level, size_t global_size, size_t local_size)
: input(data.get_access<mode::read_write>(cgh)),
higher_level(higher_level.get_access<mode::write>(cgh)),
localBlock(local_size),
global_size(global_size) {}
void operator()(cl::sycl::nd_item<1> index) {
using namespace cl::sycl;
uint1 GID = 2 * index.get_global(0);
uint1 LID = 2 * index.get_local(0);
SYCL_IF(GID < global_size)
SYCL_BEGIN {
localBlock[LID] = input[GID];
localBlock[LID + 1] = input[GID + 1];
}
SYCL_END
index.barrier(access::fence_space::local);
uint1 local_size = 2 * index.get_local_range()[0];
uint1 first;
uint1 second;
LID /= 2;
// Up-sweep
uint1 offset = 1;
SYCL_WHILE(offset < local_size)
SYCL_BEGIN {
SYCL_IF(LID % offset == 0)
SYCL_BEGIN {
first = 2 * LID + offset - 1;
second = first + offset;
localBlock[second] = localBlock[first] + localBlock[second];
}
SYCL_END
index.barrier(access::fence_space::local);
offset *= 2;
}
SYCL_END
SYCL_IF(LID == 0)
SYCL_THEN({
localBlock[local_size - 1] = 0;
})
index.barrier(access::fence_space::local);
vec<T, 1> tmp;
// Down-sweep
offset = local_size;
SYCL_WHILE(offset > 0)
SYCL_BEGIN {
SYCL_IF(LID % offset == 0)
SYCL_BEGIN {
first = 2 * LID + offset - 1;
second = first + offset;
tmp = localBlock[second];
localBlock[second] = localBlock[first] + tmp;
localBlock[first] = tmp;
}
SYCL_END
index.barrier(access::fence_space::local);
offset /= 2;
}
SYCL_END
uint1 last_sum_id = GID + local_size - 1;
SYCL_IF(LID == 0 && last_sum_id < global_size)
SYCL_BEGIN {
// Write last sum into auxiliary array
higher_level[GID / local_size] = localBlock[local_size - 1] + input[last_sum_id];
}
SYCL_END
index.barrier(access::fence_space::local);
LID *= 2;
SYCL_IF(GID < global_size)
SYCL_BEGIN {
input[GID] += localBlock[LID];
input[GID + 1] += localBlock[LID + 1];
}
SYCL_END
}
};
template <typename T>
struct prefix_sum_join_kernel {
protected:
using mode = cl::sycl::access::mode;
using target = cl::sycl::access::target;
using buffer = cl::sycl::buffer<T>;
// Global memory
cl::sycl::accessor<T> data;
cl::sycl::accessor<T, 1, mode::read> higher_level;
public:
prefix_sum_join_kernel(cl::sycl::handler& cgh, buffer& data, buffer& higher_level)
: data(data.get_access<mode::read_write>(cgh)),
higher_level(higher_level.get_access<mode::read>(cgh)) {}
void operator()(cl::sycl::nd_item<1> index) {
using namespace cl::sycl;
int1 GID = index.get_global(0);
int1 local_size = 2 * index.get_local_range()[0];
SYCL_IF(GID >= local_size)
SYCL_THEN({
data[GID] += higher_level[GID / local_size - 1];
})
}
};
template <typename type>
template <typename type>
void prefix_sum_recursion(
cl::sycl::queue& myQueue,
cl::sycl::vector_class<cl::sycl::buffer<type>>& data,
cl::sycl::vector_class<size_t>& sizes,
size_t level,
size_t number_levels,
size_t group_size
) {
using namespace cl::sycl;
myQueue.submit([&](handler& cgh) {
cgh.parallel_for(
nd_range<1>(sizes[level] / 2, group_size),
prefix_sum_kernel<type>(cgh, data[level], data[level + 1], sizes[level], 2 * group_size)
);
});
if(level + 2 >= number_levels) {
return;
}
prefix_sum_recursion(myQueue, data, sizes, level + 1, number_levels, group_size);
myQueue.submit([&](handler& cgh) {
cgh.parallel_for(
nd_range<1>(sizes[level] / 2, group_size),
prefix_sum_join_kernel<type>(cgh, data[level], data[level + 1])
);
});
}
bool test9() {
using namespace cl::sycl;
{
queue myQueue;
const auto group_size = myQueue.get_device().get_info<info::device::max_work_group_size>();
const auto size = group_size * 2;
size_t N = size;
using type = double;
// Calculate required number of buffer levels
N = size;
size_t number_levels = 1;
while(N > 1) {
N /= 2 * group_size;
++number_levels;
}
// Create buffers
vector_class<buffer<type>> data;
vector_class<size_t> sizes;
data.reserve(number_levels);
sizes.reserve(number_levels);
N = size;
for(size_t i = 0; i < number_levels; ++i) {
sizes.push_back(N);
data.emplace_back(N);
N = std::max((size_t)1, N / (2 * group_size));
N += N % 2; // Needs to be divisible by 2
}
// Init
myQueue.submit([&](handler& cgh) {
auto d = data[0].get_access<access::write>(cgh);
cgh.parallel_for<class init>(range<1>(size), [=](id<1> index) {
d[index] = 1;
});
});
prefix_sum_recursion(myQueue, data, sizes, 0, number_levels, group_size);
debug() << "Done, checking results";
return check_sum(data[0]);
}
return true;
}
<|endoftext|>
|
<commit_before>/*
* File: Renderer.h
* Author: morgan
*
* Created on February 15, 2014, 2:37 PM
*/
#ifndef MO_RENDERER_H
#define MO_RENDERER_H
#include <ogli/ogli.h>
#include <glm/glm.hpp>
#include <iostream>
#include <map>
#include <tuple>
#include "vertex.hpp"
#include "texture2d.hpp"
#include "model.hpp"
#include "particles.hpp"
#include "particle.hpp"
#include "light.hpp"
#include "render_target.hpp"
namespace mo {
struct ParticleProgramData{
unsigned int program;
int mvp;
int mv;
};
struct VertexProgramData {
unsigned int program;
int mvp;
int mv;
int normal_matrix;
int texture;
int lightmap;
int normalmap;
int material_ambient_color;
int material_diffuse_color;
int material_specular_color;
int material_specular_exponent;
int opacity;
int light_position;
int light_diffuse_color;
int light_specular_color;
int has_texture;
int has_lightmap;
int has_normalmap;
int selected;
int time;
};
/*!
* The class that talks to OpenGL, and renders Model objects.
*/
class Renderer {
public:
typedef std::pair<unsigned int, ogli::ArrayBuffer> ArrayPair;
typedef std::pair<unsigned int, ogli::ElementArrayBuffer> ElementPair;
typedef std::pair<unsigned int, ogli::TextureBuffer> TexturePair;
typedef std::pair<unsigned int, ogli::FrameBuffer> FrameBufferPair;
typedef std::pair<std::string, VertexProgramData> VertexProgramPair;
typedef std::pair<std::string, ParticleProgramData> ParticleProgramPair;
Renderer();
virtual ~Renderer();
void add_program(const std::string name);
void add_vertex_program(const std::string path,
const std::string vertex_shader_source,
const std::string fragment_shader_source);
void add_particle_program(const std::string name,
const std::string vs_source,
const std::string fs_source);
/**
* Renders a Model object.
*
* @param model.
* @param Additional transform matrix.
* @param View matrix of the camera
* @param Projection matrix of the camera
* @param Custom opacity of the object.
* @param Program_name, either "text" or "standard"
* @param Position of one ortho light.
*/
void update(const Model & model,
const glm::mat4 transform,
const glm::mat4 view,
const glm::mat4 projection,
const float opacity = 1.0f,
const std::string program_name = "standard",
const Light & light = Light(),
const float time = 0.0f);
/*
void render(const Model & model,
const glm::mat4 view,
const glm::mat4 projection,
const float opacity = 1.0f,
const std::string program_name = "standard"){
render(model, glm::mat4(1.0f), view, projection, opacity, program_name);
}
* */
template<class It>
void update(It begin, It end, const glm::mat4 transform, const glm::mat4 view,
const glm::mat4 projection, const float opacity = 1.0f,
const std::string program_name = "standard",
const Light & light = Light(), const float time = 0.0f){
for (auto it = begin; it != end; ++it){
update(*it, transform, view, projection, opacity, program_name, light, time);
}
}
/**
* Renders particles.
*
* @param Particles object.
* @param View matrix.
* @param Projection matrix.
* @param Custom opacity of the object.
*/
void update(Particles & particles,
const glm::mat4 view,
const glm::mat4 projection);
/**
* Clears the screen and the depth buffer.
* @param color
*/
void clear(const glm::vec3 color);
void clear_buffers(){
for (auto & texture : textures_) {
glDeleteTextures(1, &texture.second);
}
textures_.clear();
for (auto & ab : array_buffers_) {
glDeleteBuffers(1, &ab.second.id);
}
array_buffers_.clear();
for (auto & eab : element_array_buffers_){
glDeleteBuffers(1, &eab.second.id);
}
element_array_buffers_.clear();
}
void render_target_reset(unsigned int width, unsigned int height){
glBindFramebuffer(GL_READ_FRAMEBUFFER, readFBO);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFBO);
glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
GLuint readFBO;
GLuint drawFBO;
void render_target(RenderTarget target){
if (frame_buffers_.find(target.id()) == frame_buffers_.end()) {
glGenFramebuffers(1, &readFBO);
glBindFramebuffer(GL_FRAMEBUFFER, readFBO);
GLuint renderedTexture;
glGenTextures(1, &renderedTexture);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, renderedTexture);
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_SRGB8_ALPHA8, target.texture->width(), target.texture->height(), GL_TRUE);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, renderedTexture, 0);
GLuint depthrenderbuffer;
glGenRenderbuffers(1, &depthrenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH24_STENCIL8, target.texture->width(), target.texture->height());
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer);
GLuint screenTexture;
glGenTextures(1, &screenTexture);
glBindTexture(GL_TEXTURE_2D, screenTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8, target.texture->width(), target.texture->height(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
glGenFramebuffers(1, &drawFBO);
glBindFramebuffer(GL_FRAMEBUFFER, drawFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, screenTexture, 0);
// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE){
throw std::runtime_error("Framebuffer incomplete.");
}
//textures_.insert(TexturePair(target.texture->id(), ogli::TextureBuffer{renderedTexture}));
textures_.insert({target.texture->id(), screenTexture});
frame_buffers_.insert(FrameBufferPair(target.id(), ogli::FrameBuffer{readFBO}));
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
auto fb = frame_buffers_.at(target.id());
//std::cout << fb.id << std::endl;
glBindFramebuffer(GL_FRAMEBUFFER, fb.id);
//std::cout << target.texture->width() << " " << target.texture->height() << std::endl;
//glViewport(0,0,target.texture->width(), target.texture->height());
}
private:
unsigned int create_shader(const std::string source, const unsigned int type);
bool check_shader(const unsigned int shader);
bool check_program(const unsigned int program);
unsigned int create_texture(std::shared_ptr<mo::Texture2D> texture);
std::map<std::string, VertexProgramData> vertex_programs_;
std::map<std::string, ParticleProgramData> particle_programs_;
std::map<unsigned int, ogli::ArrayBuffer> array_buffers_;
std::map<unsigned int, ogli::ElementArrayBuffer> element_array_buffers_;
std::map<unsigned int, ogli::FrameBuffer> frame_buffers_;
std::map<unsigned int, unsigned int> textures_;
std::map<unsigned int, unsigned int> array_buffers2_;
std::map<unsigned int, unsigned int> element_array_buffers2_;
std::map<unsigned int, unsigned int> vertex_arrays_;
std::map<unsigned int, unsigned int> textures2_;
std::map<unsigned int, unsigned int> frame_buffers2_;
};
}
#endif /* MO_RENDERER_H */
<commit_msg>Framebuffer no ogli.<commit_after>/*
* File: Renderer.h
* Author: morgan
*
* Created on February 15, 2014, 2:37 PM
*/
#ifndef MO_RENDERER_H
#define MO_RENDERER_H
#include <ogli/ogli.h>
#include <glm/glm.hpp>
#include <iostream>
#include <map>
#include <tuple>
#include "vertex.hpp"
#include "texture2d.hpp"
#include "model.hpp"
#include "particles.hpp"
#include "particle.hpp"
#include "light.hpp"
#include "render_target.hpp"
namespace mo {
struct ParticleProgramData{
unsigned int program;
int mvp;
int mv;
};
struct VertexProgramData {
unsigned int program;
int mvp;
int mv;
int normal_matrix;
int texture;
int lightmap;
int normalmap;
int material_ambient_color;
int material_diffuse_color;
int material_specular_color;
int material_specular_exponent;
int opacity;
int light_position;
int light_diffuse_color;
int light_specular_color;
int has_texture;
int has_lightmap;
int has_normalmap;
int selected;
int time;
};
/*!
* The class that talks to OpenGL, and renders Model objects.
*/
class Renderer {
public:
typedef std::pair<unsigned int, ogli::ArrayBuffer> ArrayPair;
typedef std::pair<unsigned int, ogli::ElementArrayBuffer> ElementPair;
typedef std::pair<unsigned int, ogli::TextureBuffer> TexturePair;
typedef std::pair<unsigned int, ogli::FrameBuffer> FrameBufferPair;
typedef std::pair<std::string, VertexProgramData> VertexProgramPair;
typedef std::pair<std::string, ParticleProgramData> ParticleProgramPair;
Renderer();
virtual ~Renderer();
void add_program(const std::string name);
void add_vertex_program(const std::string path,
const std::string vertex_shader_source,
const std::string fragment_shader_source);
void add_particle_program(const std::string name,
const std::string vs_source,
const std::string fs_source);
/**
* Renders a Model object.
*
* @param model.
* @param Additional transform matrix.
* @param View matrix of the camera
* @param Projection matrix of the camera
* @param Custom opacity of the object.
* @param Program_name, either "text" or "standard"
* @param Position of one ortho light.
*/
void update(const Model & model,
const glm::mat4 transform,
const glm::mat4 view,
const glm::mat4 projection,
const float opacity = 1.0f,
const std::string program_name = "standard",
const Light & light = Light(),
const float time = 0.0f);
/*
void render(const Model & model,
const glm::mat4 view,
const glm::mat4 projection,
const float opacity = 1.0f,
const std::string program_name = "standard"){
render(model, glm::mat4(1.0f), view, projection, opacity, program_name);
}
* */
template<class It>
void update(It begin, It end, const glm::mat4 transform, const glm::mat4 view,
const glm::mat4 projection, const float opacity = 1.0f,
const std::string program_name = "standard",
const Light & light = Light(), const float time = 0.0f){
for (auto it = begin; it != end; ++it){
update(*it, transform, view, projection, opacity, program_name, light, time);
}
}
/**
* Renders particles.
*
* @param Particles object.
* @param View matrix.
* @param Projection matrix.
* @param Custom opacity of the object.
*/
void update(Particles & particles,
const glm::mat4 view,
const glm::mat4 projection);
/**
* Clears the screen and the depth buffer.
* @param color
*/
void clear(const glm::vec3 color);
void clear_buffers(){
for (auto & texture : textures_) {
glDeleteTextures(1, &texture.second);
}
textures_.clear();
for (auto & ab : array_buffers_) {
glDeleteBuffers(1, &ab.second.id);
}
array_buffers_.clear();
for (auto & eab : element_array_buffers_){
glDeleteBuffers(1, &eab.second.id);
}
element_array_buffers_.clear();
}
void render_target_reset(unsigned int width, unsigned int height){
glBindFramebuffer(GL_READ_FRAMEBUFFER, readFBO);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, drawFBO);
glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
GLuint readFBO;
GLuint drawFBO;
void render_target(RenderTarget target){
if (frame_buffers_.find(target.id()) == frame_buffers_.end()) {
glGenFramebuffers(1, &readFBO);
glBindFramebuffer(GL_FRAMEBUFFER, readFBO);
GLuint renderedTexture;
glGenTextures(1, &renderedTexture);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, renderedTexture);
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_SRGB8_ALPHA8, target.texture->width(), target.texture->height(), GL_TRUE);
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, renderedTexture, 0);
GLuint depthrenderbuffer;
glGenRenderbuffers(1, &depthrenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer);
glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_DEPTH24_STENCIL8, target.texture->width(), target.texture->height());
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer);
GLuint screenTexture;
glGenTextures(1, &screenTexture);
glBindTexture(GL_TEXTURE_2D, screenTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8, target.texture->width(), target.texture->height(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
glGenFramebuffers(1, &drawFBO);
glBindFramebuffer(GL_FRAMEBUFFER, drawFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, screenTexture, 0);
// Always check that our framebuffer is ok
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE){
throw std::runtime_error("Framebuffer incomplete.");
}
//textures_.insert(TexturePair(target.texture->id(), ogli::TextureBuffer{renderedTexture}));
textures_.insert({target.texture->id(), screenTexture});
frame_buffers_.insert({target.id(), readFBO});
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
auto fb = frame_buffers_[target.id()];
//std::cout << fb.id << std::endl;
glBindFramebuffer(GL_FRAMEBUFFER, fb);
//std::cout << target.texture->width() << " " << target.texture->height() << std::endl;
//glViewport(0,0,target.texture->width(), target.texture->height());
}
private:
unsigned int create_shader(const std::string source, const unsigned int type);
bool check_shader(const unsigned int shader);
bool check_program(const unsigned int program);
unsigned int create_texture(std::shared_ptr<mo::Texture2D> texture);
std::map<std::string, VertexProgramData> vertex_programs_;
std::map<std::string, ParticleProgramData> particle_programs_;
std::map<unsigned int, ogli::ArrayBuffer> array_buffers_;
std::map<unsigned int, ogli::ElementArrayBuffer> element_array_buffers_;
std::map<unsigned int, unsigned int> frame_buffers_;
std::map<unsigned int, unsigned int> textures_;
std::map<unsigned int, unsigned int> array_buffers2_;
std::map<unsigned int, unsigned int> element_array_buffers2_;
std::map<unsigned int, unsigned int> vertex_arrays_;
std::map<unsigned int, unsigned int> textures2_;
std::map<unsigned int, unsigned int> frame_buffers2_;
};
}
#endif /* MO_RENDERER_H */
<|endoftext|>
|
<commit_before>/*
[auto_generated]
boost/numeric/odeint/config.hpp
[begin_description]
Sets configurations for odeint and used libraries. Should be included before any other odeint library
[end_description]
Copyright 2009-2011 Karsten Ahnert
Copyright 2009-2011 Mario Mulansky
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or
copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef OMPLEXT_BOOST_NUMERIC_ODEINT_CONFIG_HPP_INCLUDED
#define OMPLEXT_BOOST_NUMERIC_ODEINT_CONFIG_HPP_INCLUDED
#define FUSION_MAX_VECTOR_SIZE 16
#define BOOST_FUSION_UNFUSED_MAX_ARITY 16
#define BOOST_FUSION_UNFUSED_TYPE_MAX_ARITY 16
#define BOOST_FUSION_INVOKE_MAX_ARITY 16
#define BOOST_FUSION_INVOKE_PROCEDURE_MAX_ARITY 16
#define BOOST_FUSION_INVOKE_FUNCTION_OBJECT_MAX_ARITY 16
#include <boost/config.hpp>
#endif // BOOST_NUMERIC_ODEINT_CONFIG_HPP_INCLUDED
<commit_msg>Remove macros for Boost.Fusion in odeint. Fusion is not used in this version of odeint.<commit_after>/*
[auto_generated]
boost/numeric/odeint/config.hpp
[begin_description]
Sets configurations for odeint and used libraries. Should be included before any other odeint library
[end_description]
Copyright 2009-2011 Karsten Ahnert
Copyright 2009-2011 Mario Mulansky
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or
copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef OMPLEXT_BOOST_NUMERIC_ODEINT_CONFIG_HPP_INCLUDED
#define OMPLEXT_BOOST_NUMERIC_ODEINT_CONFIG_HPP_INCLUDED
//#define FUSION_MAX_VECTOR_SIZE 16
//#define BOOST_FUSION_UNFUSED_MAX_ARITY 16
//#define BOOST_FUSION_UNFUSED_TYPE_MAX_ARITY 16
//#define BOOST_FUSION_INVOKE_MAX_ARITY 16
//#define BOOST_FUSION_INVOKE_PROCEDURE_MAX_ARITY 16
//#define BOOST_FUSION_INVOKE_FUNCTION_OBJECT_MAX_ARITY 16
#include <boost/config.hpp>
#endif // BOOST_NUMERIC_ODEINT_CONFIG_HPP_INCLUDED
<|endoftext|>
|
<commit_before>#include "StorageFlattening.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Scope.h"
#include <sstream>
namespace Halide {
namespace Internal {
using std::ostringstream;
using std::string;
using std::vector;
using std::map;
class FlattenDimensions : public IRMutator {
public:
FlattenDimensions(const map<string, Function> &e) : env(e) {}
Scope<int> scope;
private:
const map<string, Function> &env;
Expr flatten_args(const string &name, const vector<Expr> &args) {
Expr idx = 0;
vector<Expr> mins(args.size()), strides(args.size());
for (size_t i = 0; i < args.size(); i++) {
string dim = int_to_string(i);
string stride_name = name + ".stride." + dim;
string min_name = name + ".min." + dim;
string stride_name_constrained = stride_name + ".constrained";
string min_name_constrained = min_name + ".constrained";
if (scope.contains(stride_name_constrained)) {
stride_name = stride_name_constrained;
}
if (scope.contains(min_name_constrained)) {
min_name = min_name_constrained;
}
strides[i] = Variable::make(Int(32), stride_name);
mins[i] = Variable::make(Int(32), min_name);
}
if (env.find(name) != env.end()) {
// f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This
// strategy makes sense when we expect x to cancel with
// something in xmin. We use this for internal allocations
for (size_t i = 0; i < args.size(); i++) {
idx += (args[i] - mins[i]) * strides[i];
}
} else {
// f(x, y) -> f[x*stride + y*ystride - (xstride*xmin +
// ystride*ymin)]. The idea here is that the last term
// will be pulled outside the inner loop. We use this for
// external buffers, where the mins and strides are likely
// to be symbolic
Expr base = 0;
for (size_t i = 0; i < args.size(); i++) {
idx += args[i] * strides[i];
base += mins[i] * strides[i];
}
idx -= base;
}
return idx;
}
using IRMutator::visit;
void visit(const Realize *realize) {
Stmt body = mutate(realize->body);
// Compute the size
Expr size = 1;
for (size_t i = 0; i < realize->bounds.size(); i++) {
size *= realize->bounds[i].extent;
}
vector<int> storage_permutation;
{
map<string, Function>::const_iterator iter = env.find(realize->name);
assert(iter != env.end() && "Realize node refers to function not in environment");
const vector<string> &storage_dims = iter->second.schedule().storage_dims;
const vector<string> &args = iter->second.args();
for (size_t i = 0; i < storage_dims.size(); i++) {
for (size_t j = 0; j < args.size(); j++) {
if (args[j] == storage_dims[i]) {
storage_permutation.push_back((int)j);
}
}
assert(storage_permutation.size() == i+1);
}
}
assert(storage_permutation.size() == realize->bounds.size());
size = mutate(size);
stmt = body;
for (size_t i = 0; i < realize->types.size(); i++) {
string buffer_name = realize->name;
if (realize->types.size() > 1) {
buffer_name = buffer_name + '.' + int_to_string(i);
}
stmt = Allocate::make(buffer_name, realize->types[i], size, stmt);
}
// Compute the strides
for (int i = (int)realize->bounds.size()-1; i > 0; i--) {
int prev_j = storage_permutation[i-1];
int j = storage_permutation[i];
ostringstream stride_name;
stride_name << realize->name << ".stride." << j;
ostringstream prev_stride_name;
prev_stride_name << realize->name << ".stride." << prev_j;
ostringstream prev_extent_name;
prev_extent_name << realize->name << ".extent." << prev_j;
Expr prev_stride = Variable::make(Int(32), prev_stride_name.str());
Expr prev_extent = Variable::make(Int(32), prev_extent_name.str());
stmt = LetStmt::make(stride_name.str(), prev_stride * prev_extent, stmt);
}
// Innermost stride is one
ostringstream stride_0_name;
if (!storage_permutation.empty()) {
stride_0_name << realize->name << ".stride." << storage_permutation[0];
} else {
stride_0_name << realize->name << ".stride.0";
}
stmt = LetStmt::make(stride_0_name.str(), 1, stmt);
// Assign the mins and extents stored
for (size_t i = realize->bounds.size(); i > 0; i--) {
ostringstream min_name, extent_name;
min_name << realize->name << ".min." << (i-1);
extent_name << realize->name << ".extent." << (i-1);
stmt = LetStmt::make(min_name.str(), realize->bounds[i-1].min, stmt);
stmt = LetStmt::make(extent_name.str(), realize->bounds[i-1].extent, stmt);
}
}
void visit(const Provide *provide) {
Expr idx = mutate(flatten_args(provide->name, provide->args));
Expr val = mutate(provide->values[0]);
string buffer_name = provide->name;
if (provide->values.size() > 1) {
buffer_name = buffer_name + ".0";
}
// TODO: this should be a chain of LetStmts instead to get the
// ordering right in case the vals contain loads from the same
// buffer.
Stmt result = Store::make(buffer_name, val, idx);
for (size_t i = 1; i < provide->values.size(); i++) {
buffer_name = provide->name + '.' + int_to_string(i);
val = mutate(provide->values[i]);
result = Block::make(result, Store::make(buffer_name, val, idx));
}
stmt = result;
}
void visit(const Call *call) {
if (call->call_type == Call::Extern || call->call_type == Call::Intrinsic) {
vector<Expr> args(call->args.size());
bool changed = false;
for (size_t i = 0; i < args.size(); i++) {
args[i] = mutate(call->args[i]);
if (!args[i].same_as(call->args[i])) changed = true;
}
if (!changed) {
expr = call;
} else {
expr = Call::make(call->type, call->name, args, call->call_type);
}
} else {
Expr idx = mutate(flatten_args(call->name, call->args));
string name = call->name;
if (call->call_type == Call::Halide &&
call->func.values().size() > 1) {
name = name + '.' + int_to_string(call->value_index);
}
expr = Load::make(call->type, name, idx, call->image, call->param);
}
}
void visit(const LetStmt *let) {
// Discover constrained versions of things.
bool constrained_version_exists = ends_with(let->name, ".constrained");
if (constrained_version_exists) {
scope.push(let->name, 0);
}
IRMutator::visit(let);
if (constrained_version_exists) {
scope.pop(let->name);
}
}
};
Stmt storage_flattening(Stmt s, const map<string, Function> &env) {
return FlattenDimensions(env).mutate(s);
}
}
}
<commit_msg>Changed storage flattening to evaluate all tuple elements before storing any.<commit_after>#include "StorageFlattening.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Scope.h"
#include <sstream>
namespace Halide {
namespace Internal {
using std::ostringstream;
using std::string;
using std::vector;
using std::map;
class FlattenDimensions : public IRMutator {
public:
FlattenDimensions(const map<string, Function> &e) : env(e) {}
Scope<int> scope;
private:
const map<string, Function> &env;
Expr flatten_args(const string &name, const vector<Expr> &args) {
Expr idx = 0;
vector<Expr> mins(args.size()), strides(args.size());
for (size_t i = 0; i < args.size(); i++) {
string dim = int_to_string(i);
string stride_name = name + ".stride." + dim;
string min_name = name + ".min." + dim;
string stride_name_constrained = stride_name + ".constrained";
string min_name_constrained = min_name + ".constrained";
if (scope.contains(stride_name_constrained)) {
stride_name = stride_name_constrained;
}
if (scope.contains(min_name_constrained)) {
min_name = min_name_constrained;
}
strides[i] = Variable::make(Int(32), stride_name);
mins[i] = Variable::make(Int(32), min_name);
}
if (env.find(name) != env.end()) {
// f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This
// strategy makes sense when we expect x to cancel with
// something in xmin. We use this for internal allocations
for (size_t i = 0; i < args.size(); i++) {
idx += (args[i] - mins[i]) * strides[i];
}
} else {
// f(x, y) -> f[x*stride + y*ystride - (xstride*xmin +
// ystride*ymin)]. The idea here is that the last term
// will be pulled outside the inner loop. We use this for
// external buffers, where the mins and strides are likely
// to be symbolic
Expr base = 0;
for (size_t i = 0; i < args.size(); i++) {
idx += args[i] * strides[i];
base += mins[i] * strides[i];
}
idx -= base;
}
return idx;
}
using IRMutator::visit;
void visit(const Realize *realize) {
Stmt body = mutate(realize->body);
// Compute the size
Expr size = 1;
for (size_t i = 0; i < realize->bounds.size(); i++) {
size *= realize->bounds[i].extent;
}
vector<int> storage_permutation;
{
map<string, Function>::const_iterator iter = env.find(realize->name);
assert(iter != env.end() && "Realize node refers to function not in environment");
const vector<string> &storage_dims = iter->second.schedule().storage_dims;
const vector<string> &args = iter->second.args();
for (size_t i = 0; i < storage_dims.size(); i++) {
for (size_t j = 0; j < args.size(); j++) {
if (args[j] == storage_dims[i]) {
storage_permutation.push_back((int)j);
}
}
assert(storage_permutation.size() == i+1);
}
}
assert(storage_permutation.size() == realize->bounds.size());
size = mutate(size);
stmt = body;
for (size_t i = 0; i < realize->types.size(); i++) {
string buffer_name = realize->name;
if (realize->types.size() > 1) {
buffer_name = buffer_name + '.' + int_to_string(i);
}
stmt = Allocate::make(buffer_name, realize->types[i], size, stmt);
}
// Compute the strides
for (int i = (int)realize->bounds.size()-1; i > 0; i--) {
int prev_j = storage_permutation[i-1];
int j = storage_permutation[i];
ostringstream stride_name;
stride_name << realize->name << ".stride." << j;
ostringstream prev_stride_name;
prev_stride_name << realize->name << ".stride." << prev_j;
ostringstream prev_extent_name;
prev_extent_name << realize->name << ".extent." << prev_j;
Expr prev_stride = Variable::make(Int(32), prev_stride_name.str());
Expr prev_extent = Variable::make(Int(32), prev_extent_name.str());
stmt = LetStmt::make(stride_name.str(), prev_stride * prev_extent, stmt);
}
// Innermost stride is one
ostringstream stride_0_name;
if (!storage_permutation.empty()) {
stride_0_name << realize->name << ".stride." << storage_permutation[0];
} else {
stride_0_name << realize->name << ".stride.0";
}
stmt = LetStmt::make(stride_0_name.str(), 1, stmt);
// Assign the mins and extents stored
for (size_t i = realize->bounds.size(); i > 0; i--) {
ostringstream min_name, extent_name;
min_name << realize->name << ".min." << (i-1);
extent_name << realize->name << ".extent." << (i-1);
stmt = LetStmt::make(min_name.str(), realize->bounds[i-1].min, stmt);
stmt = LetStmt::make(extent_name.str(), realize->bounds[i-1].extent, stmt);
}
}
void visit(const Provide *provide) {
Expr idx = mutate(flatten_args(provide->name, provide->args));
vector<Expr> values(provide->values.size());
for (size_t i = 0; i < values.size(); i++) {
values[i] = mutate(provide->values[i]);
}
if (values.size() == 1) {
stmt = Store::make(provide->name, values[0], idx);
} else {
vector<string> names(provide->values.size());
Stmt result;
// Store the values by name
for (size_t i = 0; i < provide->values.size(); i++) {
string name = provide->name + "." + int_to_string(i);
names[i] = name + ".value";
Expr var = Variable::make(values[i].type(), names[i]);
Stmt store = Store::make(name, var, idx);
if (result.defined()) {
result = Block::make(result, store);
} else {
result = store;
}
}
// Add the let statements that define the values
for (size_t i = provide->values.size(); i > 0; i--) {
result = LetStmt::make(names[i-1], values[i-1], result);
}
stmt = result;
}
}
void visit(const Call *call) {
if (call->call_type == Call::Extern || call->call_type == Call::Intrinsic) {
vector<Expr> args(call->args.size());
bool changed = false;
for (size_t i = 0; i < args.size(); i++) {
args[i] = mutate(call->args[i]);
if (!args[i].same_as(call->args[i])) changed = true;
}
if (!changed) {
expr = call;
} else {
expr = Call::make(call->type, call->name, args, call->call_type);
}
} else {
Expr idx = mutate(flatten_args(call->name, call->args));
string name = call->name;
if (call->call_type == Call::Halide &&
call->func.values().size() > 1) {
name = name + '.' + int_to_string(call->value_index);
}
expr = Load::make(call->type, name, idx, call->image, call->param);
}
}
void visit(const LetStmt *let) {
// Discover constrained versions of things.
bool constrained_version_exists = ends_with(let->name, ".constrained");
if (constrained_version_exists) {
scope.push(let->name, 0);
}
IRMutator::visit(let);
if (constrained_version_exists) {
scope.pop(let->name);
}
}
};
Stmt storage_flattening(Stmt s, const map<string, Function> &env) {
return FlattenDimensions(env).mutate(s);
}
}
}
<|endoftext|>
|
<commit_before>/*
oscarconnection.h - Implementation of an oscar direct connection
Copyright (c) 2002 by Tom Linsky <twl6@po.cwru.edu>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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. *
* *
*************************************************************************
*/
#include <kdebug.h>
#include "oscardirectconnection.h"
#include "oscardebugdialog.h"
#include "oscarsocket.h"
OscarDirectConnection::OscarDirectConnection(const QString &sn, const QString &connName,
char cookie[8], QObject *parent, const char *name)
: OscarConnection(sn, connName, DirectIM, cookie, parent, name)
{
connect(this, SIGNAL(connectionClosed()), this, SLOT(slotConnectionClosed()));
}
OscarDirectConnection::~OscarDirectConnection()
{
}
/** Called when there is data to be read from peer */
void OscarDirectConnection::slotRead(void)
{
ODC2 fl = getODC2();
char *buf = new char[fl.length];
Buffer inbuf;
if (bytesAvailable() < fl.length)
{
while (waitForMore(500) < fl.length)
kdDebug() << "[OSCAR][OnRead()] not enough data read yet... waiting" << endl;
}
int bytesread = readBlock(buf,fl.length);
if (bytesAvailable())
{
emit readyRead(); //there is another packet waiting to be read
}
inbuf.setBuf(buf,bytesread);
//kdDebug() << "[OSCAR] Input: " << endl;
if(hasDebugDialog()){
debugDialog()->addMessageFromServer(inbuf.toString(),connectionName());
}
if (fl.type == 0x000e) // started typing
{
emit gotMiniTypeNotification(fl.sn, 2);
}
else if (fl.type == 0x0002) //finished typing
{
emit gotMiniTypeNotification(fl.sn, 0);
}
else
{
emit gotMiniTypeNotification(fl.sn, 1);
}
if ( (fl.length > 0) && fl.sn) //there is a message here
parseMessage(inbuf);
if ( inbuf.getLength() )
kdDebug() << "[OscarDirectConnection] slotread (" << connectionName() << "): inbuf not empty" << endl;//inbuf.toString() << endl;
if (fl.sn)
delete fl.sn;
if (fl.cookie)
delete fl.cookie;
}
/** Gets an ODC2 header */
ODC2 OscarDirectConnection::getODC2(void)
{
ODC2 odc;
int theword, theword2;
int start;
int chan;
//the ODC2 start byte
if (((start = getch()) == 0x4f) &&
((start = getch()) == 0x44) &&
((start = getch()) == 0x43) &&
((start = getch()) == 0x32))
{
//get the header length
if ((theword = getch()) == -1) {
kdDebug() << "[OSCAR] Error reading length, byte 1: nothing to be read" << endl;
odc.headerLength = 0x00;
} else if((theword2 = getch()) == -1){
kdDebug() << "[OSCAR] Error reading data field length, byte 2: nothing to be read" << endl;
odc.headerLength = 0x00;
} else {
odc.headerLength = (theword << 8) | theword2;
}
//convert header to a buffer
char *buf = new char[odc.headerLength-6]; // the -6 is there because we have already read 6 bytes
readBlock(buf,odc.headerLength-6);
Buffer inbuf;
inbuf.setBuf(buf,odc.headerLength-6);
//inbuf.print();
if(hasDebugDialog()){
debugDialog()->addMessageFromServer(inbuf.toString(),connectionName());
}
//get channel
odc.channel = inbuf.getWord();
//0x0006 is next
if (inbuf.getWord() != 0x0006)
kdDebug() << "[OscarDirectConnection] getODC2: 1: expected a 0x0006, didn't get it" << endl;
//0x0000 is next
if (inbuf.getWord() != 0x0000)
kdDebug() << "[OscarDirectConnection] getODC2: 2: expected a 0x0000, didn't get it" << endl;
//get the 8 byte cookie
odc.cookie = inbuf.getBlock(8);
//for (int i=0;i<8;i++)
// mCookie[i] = odc.cookie[i];
// 10 bytes of 0
if (inbuf.getDWord() != 0x00000000)
kdDebug() << "[OscarDirectConnection] getODC2: 3: expected a 0x00000000, didn't get it" << endl;
if (inbuf.getDWord() != 0x00000000)
kdDebug() << "[OscarDirectConnection] getODC2: 4: expected a 0x00000000, didn't get it" << endl;
//if (inbuf.getWord() != 0x0000)
// kdDebug() << "[OscarDirectConnection] getODC2: 5: expected a 0x0000, didn't get it" << endl;
// message length
odc.length = inbuf.getDWord();
// 6 bytes of 0
if (inbuf.getDWord() != 0x00000000)
kdDebug() << "[OscarDirectConnection] getODC2: 6: expected a 0x00000000, didn't get it" << endl;
if (inbuf.getWord() != 0x0000)
kdDebug() << "[OscarDirectConnection] getODC2: 7: expected a 0x0000, didn't get it" << endl;
// ODC2 type
odc.type = inbuf.getWord();
// 4 bytes of 0
if (inbuf.getDWord() != 0x00000000)
kdDebug() << "[OscarDirectConnection] getODC2: 8: expected a 0x00000000, didn't get it" << endl;
// screen name (not sure how to get length yet, so we'll just take it and the 0's after it)
odc.sn = inbuf.getBlock(inbuf.getLength());
// 25 bytes of 0
//might as well just clear buffer, since there won't be anything after those 25 0x00's
inbuf.clear();
} else {
kdDebug() << "[OSCAR] Error reading ODC2 header... start byte is " << start << endl;
}
kdDebug() << "[OSCAR] Read an ODC2 header! header length: " << odc.headerLength
<< ", channel: " << odc.channel << ", message length: " << odc.length
<< ", type: " << odc.type << ", screen name: " << odc.sn << endl;
return odc;
}
/** Sets the socket to use socket, state() to connected, and emit connected() */
void OscarDirectConnection::setSocket( int socket )
{
QSocket::setSocket(socket);
emit connected();
}
/** Sends the direct IM message to buddy */
void OscarDirectConnection::sendIM(const QString &message, bool /*isAuto*/)
{
sendODC2Block(message, 0x0000); // 0x0000 means message
}
/** Sends a typing notification to the server
@param notifyType Type of notify to send
*/
void OscarDirectConnection::sendTypingNotify(TypingNotify notifyType)
{
switch (notifyType)
{
case TypingBegun:
sendODC2Block(QString::null, 0x000e);
break;
case TypingFinished:
sendODC2Block(QString::null, 0x0002);
break;
case TextTyped: //we will say TextTyped means the user has finished typing, for now
sendODC2Block(QString::null, 0x0002);
break;
}
}
/** Prepares and sends a block with the given message and typing notify flag attached */
void OscarDirectConnection::sendODC2Block(const QString &message, WORD typingnotify)
{
Buffer outbuf;
outbuf.addDWord(0x4f444332); // "ODC2"
outbuf.addWord(0x004c); // not sure if this is always the header length
outbuf.addWord(0x0001); // channel
outbuf.addWord(0x0006); // 0x0006
outbuf.addWord(0x0000); // 0x0000
outbuf.addString(cookie(),8);
outbuf.addDWord(0x00000000);
outbuf.addDWord(0x00000000);
outbuf.addWord(0x0000);
if (typingnotify == 0x0000)
outbuf.addWord(message.length());
else
outbuf.addWord(0x0000);
outbuf.addDWord(0x00000000);
outbuf.addWord(0x0000);
outbuf.addWord(typingnotify);
outbuf.addDWord(0x00000000);
outbuf.addString(getSN().latin1(),getSN().length());
while (outbuf.getLength() < 0x004c)
outbuf.addByte(0x00);
if (typingnotify == 0x0000)
outbuf.addString(message.latin1(), message.length());
kdDebug() << "Sending ODC2 block, message: " << message << "typingnotify: " << typingnotify << endl;
//outbuf.print();
if(hasDebugDialog()){
debugDialog()->addMessageFromClient(outbuf.toString(),connectionName());
}
writeBlock(outbuf.getBuf(),outbuf.getLength());
}
/** Parses the given message */
void OscarDirectConnection::parseMessage(Buffer &inbuf)
{
kdDebug() << "[OscarDirect] buffer length is " << inbuf.getLength() << endl;
// The message will come first, followed by binary files
// so let's parse until we see "<BINARY>"
QString message;
while ( !message.contains("<BINARY>",false) )
{
//kdDebug() << "[OscarDirect] message is: " << message << endl;
// while the message does not contain the string "<BINARY>"
message.append(inbuf.getByte());
if ( !inbuf.getLength() )
{
//if we are at the end of the buffer
kdDebug() << "[OscarDirectConnection] got IM: " << message << endl;
emit gotIM(message, connectionName(), false);
return;
}
}
//now, we have the message, and we need to d/l the binary content
//TODO: implement a FOR loop to handle multiple binary file ID's
//first comes the <DATA> tag
//fields of <DATA ID="n" SIZE="n">(binary file here)
QString datatag;
while ( !datatag.contains(">",false) )
{
datatag.append(inbuf.getByte());
kdDebug() << "[OscarDirect] datatag matching " << datatag << endl;
if ( !inbuf.getLength() )
{
//message ended in the middle of the data tag
kdDebug() << "[OscarDirectConnection] got IM: " << message << endl;
emit gotIM(message.remove("<BINARY>"), connectionName(), false);
}
}
kdDebug() << "[OscarDirectConnection] got IM: " << message << endl;
emit gotIM(message.remove("<BINARY>"), connectionName(), false);
}
#include "oscardirectconnection.moc"
<commit_msg><commit_after>/*
oscarconnection.h - Implementation of an oscar direct connection
Copyright (c) 2002 by Tom Linsky <twl6@po.cwru.edu>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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. *
* *
*************************************************************************
*/
#include <kdebug.h>
#include "oscardirectconnection.h"
#include "oscardebugdialog.h"
#include "oscarsocket.h"
OscarDirectConnection::OscarDirectConnection(const QString &sn, const QString &connName,
char cookie[8], QObject *parent, const char *name)
: OscarConnection(sn, connName, DirectIM, cookie, parent, name)
{
connect(this, SIGNAL(connectionClosed()), this, SLOT(slotConnectionClosed()));
}
OscarDirectConnection::~OscarDirectConnection()
{
}
/** Called when there is data to be read from peer */
void OscarDirectConnection::slotRead(void)
{
ODC2 fl = getODC2();
char *buf = new char[fl.length];
Buffer inbuf;
if (bytesAvailable() < fl.length)
{
while (waitForMore(500) < fl.length)
kdDebug() << "[OSCAR][OnRead()] not enough data read yet... waiting" << endl;
}
int bytesread = readBlock(buf,fl.length);
if (bytesAvailable())
{
emit readyRead(); //there is another packet waiting to be read
}
inbuf.setBuf(buf,bytesread);
//kdDebug() << "[OSCAR] Input: " << endl;
if(hasDebugDialog()){
debugDialog()->addMessageFromServer(inbuf.toString(),connectionName());
}
if (fl.type == 0x000e) // started typing
{
emit gotMiniTypeNotification(fl.sn, 2);
}
else if (fl.type == 0x0002) //finished typing
{
emit gotMiniTypeNotification(fl.sn, 0);
}
else
{
emit gotMiniTypeNotification(fl.sn, 1);
}
if ( (fl.length > 0) && fl.sn) //there is a message here
parseMessage(inbuf);
if ( inbuf.getLength() )
kdDebug() << "[OscarDirectConnection] slotread (" << connectionName() << "): inbuf not empty" << endl;//inbuf.toString() << endl;
if (fl.sn)
delete fl.sn;
if (fl.cookie)
delete fl.cookie;
}
/** Gets an ODC2 header */
ODC2 OscarDirectConnection::getODC2(void)
{
ODC2 odc;
int theword, theword2;
int start;
int chan;
//the ODC2 start byte
if (((start = getch()) == 0x4f) &&
((start = getch()) == 0x44) &&
((start = getch()) == 0x43) &&
((start = getch()) == 0x32))
{
//get the header length
if ((theword = getch()) == -1) {
kdDebug() << "[OSCAR] Error reading length, byte 1: nothing to be read" << endl;
odc.headerLength = 0x00;
} else if((theword2 = getch()) == -1){
kdDebug() << "[OSCAR] Error reading data field length, byte 2: nothing to be read" << endl;
odc.headerLength = 0x00;
} else {
odc.headerLength = (theword << 8) | theword2;
}
//convert header to a buffer
char *buf = new char[odc.headerLength-6]; // the -6 is there because we have already read 6 bytes
readBlock(buf,odc.headerLength-6);
Buffer inbuf;
inbuf.setBuf(buf,odc.headerLength-6);
//inbuf.print();
if(hasDebugDialog()){
debugDialog()->addMessageFromServer(inbuf.toString(),connectionName());
}
//get channel
odc.channel = inbuf.getWord();
//0x0006 is next
if (inbuf.getWord() != 0x0006)
kdDebug() << "[OscarDirectConnection] getODC2: 1: expected a 0x0006, didn't get it" << endl;
//0x0000 is next
if (inbuf.getWord() != 0x0000)
kdDebug() << "[OscarDirectConnection] getODC2: 2: expected a 0x0000, didn't get it" << endl;
//get the 8 byte cookie
odc.cookie = inbuf.getBlock(8);
//for (int i=0;i<8;i++)
// mCookie[i] = odc.cookie[i];
// 10 bytes of 0
if (inbuf.getDWord() != 0x00000000)
kdDebug() << "[OscarDirectConnection] getODC2: 3: expected a 0x00000000, didn't get it" << endl;
if (inbuf.getDWord() != 0x00000000)
kdDebug() << "[OscarDirectConnection] getODC2: 4: expected a 0x00000000, didn't get it" << endl;
//if (inbuf.getWord() != 0x0000)
// kdDebug() << "[OscarDirectConnection] getODC2: 5: expected a 0x0000, didn't get it" << endl;
// message length
odc.length = inbuf.getDWord();
// 6 bytes of 0
if (inbuf.getDWord() != 0x00000000)
kdDebug() << "[OscarDirectConnection] getODC2: 6: expected a 0x00000000, didn't get it" << endl;
if (inbuf.getWord() != 0x0000)
kdDebug() << "[OscarDirectConnection] getODC2: 7: expected a 0x0000, didn't get it" << endl;
// ODC2 type
odc.type = inbuf.getWord();
// 4 bytes of 0
if (inbuf.getDWord() != 0x00000000)
kdDebug() << "[OscarDirectConnection] getODC2: 8: expected a 0x00000000, didn't get it" << endl;
// screen name (not sure how to get length yet, so we'll just take it and the 0's after it)
odc.sn = inbuf.getBlock(inbuf.getLength());
// 25 bytes of 0
//might as well just clear buffer, since there won't be anything after those 25 0x00's
inbuf.clear();
} else {
kdDebug() << "[OSCAR] Error reading ODC2 header... start byte is " << start << endl;
}
kdDebug() << "[OSCAR] Read an ODC2 header! header length: " << odc.headerLength
<< ", channel: " << odc.channel << ", message length: " << odc.length
<< ", type: " << odc.type << ", screen name: " << odc.sn << endl;
return odc;
}
/** Sets the socket to use socket, state() to connected, and emit connected() */
void OscarDirectConnection::setSocket( int socket )
{
QSocket::setSocket(socket);
emit connected();
}
/** Sends the direct IM message to buddy */
void OscarDirectConnection::sendIM(const QString &message, bool /*isAuto*/)
{
sendODC2Block(message, 0x0000); // 0x0000 means message
}
/** Sends a typing notification to the server
@param notifyType Type of notify to send
*/
void OscarDirectConnection::sendTypingNotify(TypingNotify notifyType)
{
switch (notifyType)
{
case TypingBegun:
sendODC2Block(QString::null, 0x000e);
break;
case TypingFinished:
sendODC2Block(QString::null, 0x0002);
break;
case TextTyped: //we will say TextTyped means the user has finished typing, for now
sendODC2Block(QString::null, 0x0002);
break;
}
}
/** Prepares and sends a block with the given message and typing notify flag attached */
void OscarDirectConnection::sendODC2Block(const QString &message, WORD typingnotify)
{
Buffer outbuf;
outbuf.addDWord(0x4f444332); // "ODC2"
outbuf.addWord(0x004c); // not sure if this is always the header length
outbuf.addWord(0x0001); // channel
outbuf.addWord(0x0006); // 0x0006
outbuf.addWord(0x0000); // 0x0000
outbuf.addString(cookie(),8);
outbuf.addDWord(0x00000000);
outbuf.addDWord(0x00000000);
outbuf.addWord(0x0000);
if (typingnotify == 0x0000)
outbuf.addWord(message.length());
else
outbuf.addWord(0x0000);
outbuf.addDWord(0x00000000);
outbuf.addWord(0x0000);
outbuf.addWord(typingnotify);
outbuf.addDWord(0x00000000);
outbuf.addString(getSN().latin1(),getSN().length());
while (outbuf.getLength() < 0x004c)
outbuf.addByte(0x00);
if (typingnotify == 0x0000)
outbuf.addString(message.latin1(), message.length());
kdDebug() << "Sending ODC2 block, message: " << message << "typingnotify: " << typingnotify << endl;
//outbuf.print();
if(hasDebugDialog()){
debugDialog()->addMessageFromClient(outbuf.toString(),connectionName());
}
writeBlock(outbuf.getBuf(),outbuf.getLength());
}
/** Parses the given message */
void OscarDirectConnection::parseMessage(Buffer &inbuf)
{
kdDebug() << "[OscarDirect] buffer length is " << inbuf.getLength() << endl;
// The message will come first, followed by binary files
// so let's parse until we see "<BINARY>"
QString message;
while ( !message.contains("<BINARY>",false) )
{
//kdDebug() << "[OscarDirect] message is: " << message << endl;
// while the message does not contain the string "<BINARY>"
message.append(inbuf.getByte());
if ( !inbuf.getLength() )
{
//if we are at the end of the buffer
kdDebug() << "[OscarDirectConnection] got IM: " << message << endl;
emit gotIM(message, connectionName(), false);
return;
}
}
//now, we have the message, and we need to d/l the binary content
//TODO: implement a FOR loop to handle multiple binary file ID's
//first comes the <DATA> tag
//fields of <DATA ID="n" SIZE="n">(binary file here)
QString datatag;
while ( !datatag.contains(">",false) )
{
datatag.append(inbuf.getByte());
kdDebug() << "[OscarDirect] datatag matching " << datatag << endl;
if ( !inbuf.getLength() )
{
//message ended in the middle of the data tag
kdDebug() << "[OscarDirectConnection] got IM: " << message << endl;
//remove the <BINARY> at the end of the string
emit gotIM(message.remove(message.length()-8, 8), connectionName(), false);
}
}
kdDebug() << "[OscarDirectConnection] got IM: " << message << endl;
emit gotIM(message.remove(message.length()-8, 8), connectionName(), false);
}
#include "oscardirectconnection.moc"
<|endoftext|>
|
<commit_before>
#ifdef _DEBUG
#include "NetworkSample.h"
NetworkSample::NetworkSample()
{
}
NetworkSample::~NetworkSample()
{
}
void NetworkSample::Render()
{
NNScene::Render();
}
void NetworkSample::Update( float dTime )
{
NNScene::Update(dTime);
}
#endif<commit_msg>* NetworkSample Test<commit_after>
#ifdef _DEBUG
#include "NetworkSample.h"
#include "Packet.h"
#include "PacketFunction.h"
#include "NNNetworkSystem.h"
NetworkSample::NetworkSample()
{
//NNNetworkSystem::GetInstance()->Init();
NNNetworkSystem::GetInstance()->SetPacketFunction(PKT_TEST,TestPacketFunction);
}
NetworkSample::~NetworkSample()
{
}
void NetworkSample::Render()
{
NNScene::Render();
}
void NetworkSample::Update( float dTime )
{
NNScene::Update(dTime);
}
#endif<|endoftext|>
|
<commit_before>#ifndef __TRIANGULATION_MACROS_CPP_INCLUDED
#define __TRIANGULATION_MACROS_CPP_INCLUDED
#include "indexing.hpp"
// for bilinear interpolation, southeast-northwest edges, and southwest-northeast edges.
inline GLuint southwest(uint32_t current_vertex_i, uint32_t image_width)
{
return current_vertex_i - image_width - 1;
}
inline GLuint southeast(uint32_t current_vertex_i, uint32_t image_width)
{
return current_vertex_i - image_width;
}
inline GLuint northwest(uint32_t current_vertex_i, uint32_t image_width)
{
return current_vertex_i - 1;
}
inline GLuint northeast(uint32_t current_vertex_i, uint32_t image_width)
{
return current_vertex_i;
}
// for bilinear interpolation.
inline GLuint center(uint32_t current_interpolated_vertex_i)
{
return current_interpolated_vertex_i;
}
// for bilinear interpolation.
#define SOUTHWEST_Y (geometry::get_y(input_vertex_pointer, x - 1, z - 1, image_width))
#define SOUTHEAST_Y (geometry::get_y(input_vertex_pointer, x, z - 1, image_width))
#define NORTHWEST_Y (geometry::get_y(input_vertex_pointer, x - 1, z, image_width))
#define NORTHEAST_Y (geometry::get_y(input_vertex_pointer, x, z, image_width))
#define CENTER_Y ((SOUTHWEST_Y + SOUTHEAST_Y + NORTHWEST_Y + NORTHEAST_Y) / 4)
// for bilinear interpolation.
#define SSW_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, SSW, image_width))
#define WSW_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, WSW, image_width))
#define WNW_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, WNW, image_width))
#define NNW_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, NNW, image_width))
#define NNE_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, NNE, image_width))
#define ENE_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, ENE, image_width))
#define ESE_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, ESE, image_width))
#define SSE_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, SSE, image_width))
// for bilinear interpolation.
#define S_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x - 1, z - 1, ENE, image_width))
#define W_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x - 1, z - 1, NNE, image_width))
#define N_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, WSW, image_width))
#define E_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, SSW, image_width))
// for southeast-northwest edges.
#define SSE_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, SSE_CODE_FOR_SE_NW, image_width))
#define WNW_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, WNW_CODE_FOR_SE_NW, image_width))
#define ESE_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, ESE_CODE_FOR_SE_NW, image_width))
#define NNW_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, NNW_CODE_FOR_SE_NW, image_width))
#define SW_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, SW_CODE_FOR_SE_NW, image_width))
#define NE_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, NE_CODE_FOR_SE_NW, image_width))
#endif
<commit_msg>`inline` functions moved to `namespace geometry`.<commit_after>#ifndef __TRIANGULATION_MACROS_CPP_INCLUDED
#define __TRIANGULATION_MACROS_CPP_INCLUDED
#include "indexing.hpp"
namespace geometry
{
// for bilinear interpolation, southeast-northwest edges, and southwest-northeast edges.
inline GLuint southwest(uint32_t current_vertex_i, uint32_t image_width)
{
return current_vertex_i - image_width - 1;
}
inline GLuint southeast(uint32_t current_vertex_i, uint32_t image_width)
{
return current_vertex_i - image_width;
}
inline GLuint northwest(uint32_t current_vertex_i, uint32_t image_width)
{
return current_vertex_i - 1;
}
inline GLuint northeast(uint32_t current_vertex_i, uint32_t image_width)
{
return current_vertex_i;
}
}
// for bilinear interpolation.
inline GLuint center(uint32_t current_interpolated_vertex_i)
{
return current_interpolated_vertex_i;
}
// for bilinear interpolation.
#define SOUTHWEST_Y (geometry::get_y(input_vertex_pointer, x - 1, z - 1, image_width))
#define SOUTHEAST_Y (geometry::get_y(input_vertex_pointer, x, z - 1, image_width))
#define NORTHWEST_Y (geometry::get_y(input_vertex_pointer, x - 1, z, image_width))
#define NORTHEAST_Y (geometry::get_y(input_vertex_pointer, x, z, image_width))
#define CENTER_Y ((SOUTHWEST_Y + SOUTHEAST_Y + NORTHWEST_Y + NORTHEAST_Y) / 4)
// for bilinear interpolation.
#define SSW_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, SSW, image_width))
#define WSW_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, WSW, image_width))
#define WNW_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, WNW, image_width))
#define NNW_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, NNW, image_width))
#define NNE_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, NNE, image_width))
#define ENE_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, ENE, image_width))
#define ESE_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, ESE, image_width))
#define SSE_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, SSE, image_width))
// for bilinear interpolation.
#define S_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x - 1, z - 1, ENE, image_width))
#define W_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x - 1, z - 1, NNE, image_width))
#define N_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, WSW, image_width))
#define E_FACE_NORMAL (geometry::get_face_normal(face_normal_vector_vec3, x, z, SSW, image_width))
// for southeast-northwest edges.
#define SSE_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, SSE_CODE_FOR_SE_NW, image_width))
#define WNW_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, WNW_CODE_FOR_SE_NW, image_width))
#define ESE_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, ESE_CODE_FOR_SE_NW, image_width))
#define NNW_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, NNW_CODE_FOR_SE_NW, image_width))
#define SW_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, SW_CODE_FOR_SE_NW, image_width))
#define NE_FACE_NORMAL_FOR_SE_NW (geometry::get_face_normal_for_SE_NW(face_normal_vector_vec3, x, z, NE_CODE_FOR_SE_NW, image_width))
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2016 *
* *
* 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 <modules/globebrowsing/meshes/trianglesoup.h>
namespace {
const std::string _loggerCat = "TriangleSoup";
}
namespace openspace
{
TriangleSoup::TriangleSoup(std::vector<unsigned int> elements,
Positions usePositions, TextureCoordinates useTextures, Normals useNormals)
: _vaoID(0)
,_vertexBufferID(0)
,_elementBufferID(0)
,_useVertexPositions(usePositions == Positions::Yes)
,_useTextureCoordinates(useTextures == TextureCoordinates::Yes)
,_useVertexNormals(useNormals == Normals::Yes)
{
setElements(elements);
}
TriangleSoup::~TriangleSoup() {
glDeleteBuffers(1, &_vertexBufferID);
glDeleteBuffers(1, &_elementBufferID);
glDeleteVertexArrays(1, &_vaoID);
}
void TriangleSoup::setVertexPositions(std::vector<glm::vec4> positions) {
_useVertexPositions = true;
_gpuDataNeedUpdate = true;
_vertexData.resize(positions.size());
for (size_t i = 0; i < positions.size(); i++)
{
_vertexData[i].position[0] = static_cast<GLfloat>(positions[i].x);
_vertexData[i].position[1] = static_cast<GLfloat>(positions[i].y);
_vertexData[i].position[2] = static_cast<GLfloat>(positions[i].z);
_vertexData[i].position[3] = static_cast<GLfloat>(positions[i].w);
}
}
void TriangleSoup::setVertexTextureCoordinates(std::vector<glm::vec2> textures) {
_useTextureCoordinates = true;
_gpuDataNeedUpdate = true;
_vertexData.resize(textures.size());
for (size_t i = 0; i < textures.size(); i++)
{
_vertexData[i].texture[0] = static_cast<GLfloat>(textures[i].s);
_vertexData[i].texture[1] = static_cast<GLfloat>(textures[i].t);
}
}
void TriangleSoup::setVertexNormals(std::vector<glm::vec3> normals) {
_useVertexNormals = true;
_gpuDataNeedUpdate = true;
_vertexData.resize(normals.size());
for (size_t i = 0; i < normals.size(); i++)
{
_vertexData[i].normal[0] = static_cast<GLfloat>(normals[i].x);
_vertexData[i].normal[1] = static_cast<GLfloat>(normals[i].y);
_vertexData[i].normal[2] = static_cast<GLfloat>(normals[i].z);
}
}
void TriangleSoup::setElements(std::vector<unsigned int> elements) {
_elementData.resize(elements.size());
_gpuDataNeedUpdate = true;
for (size_t i = 0; i < elements.size(); i++)
{
_elementData[i] = static_cast<GLuint>(elements[i]);
}
}
bool TriangleSoup::updateDataInGPU() {
// Create VAO
if (_vaoID == 0)
glGenVertexArrays(1, &_vaoID);
// Create VBOs
if (_vertexBufferID == 0 && _vertexData.size() > 0) {
glGenBuffers(1, &_vertexBufferID);
if (_vertexBufferID == 0) {
LERROR("Could not create vertex buffer");
return false;
}
}
if (_elementBufferID == 0 && _elementData.size() > 0) {
glGenBuffers(1, &_elementBufferID);
if (_elementBufferID == 0) {
LERROR("Could not create vertex element buffer");
return false;
}
}
// First VAO setup
glBindVertexArray(_vaoID);
// Vertex buffer
glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID);
glBufferData(
GL_ARRAY_BUFFER,
_vertexData.size() * sizeof(Vertex),
&_vertexData[0],
GL_STATIC_DRAW);
// Positions at location 0
if (_useVertexPositions) {
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, position)));
}
// Textures at location 1
if (_useTextureCoordinates) {
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, texture)));
}
// Normals at location 2
if (_useVertexNormals) {
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, normal)));
}
// Element buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _elementBufferID);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
_elementData.size() * sizeof(GLint),
&_elementData[0],
GL_STATIC_DRAW);
glBindVertexArray(0);
return true;
}
void TriangleSoup::drawUsingActiveProgram() {
if (_gpuDataNeedUpdate) {
updateDataInGPU();
}
glBindVertexArray(_vaoID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _elementBufferID);
glDrawElements(GL_TRIANGLES, _elementData.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
} // namespace openspace<commit_msg>Fix bug that caused multiple calls glBufferData(...)<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2016 *
* *
* 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 <modules/globebrowsing/meshes/trianglesoup.h>
namespace {
const std::string _loggerCat = "TriangleSoup";
}
namespace openspace
{
TriangleSoup::TriangleSoup(std::vector<unsigned int> elements,
Positions usePositions, TextureCoordinates useTextures, Normals useNormals)
: _vaoID(0)
,_vertexBufferID(0)
,_elementBufferID(0)
,_useVertexPositions(usePositions == Positions::Yes)
,_useTextureCoordinates(useTextures == TextureCoordinates::Yes)
,_useVertexNormals(useNormals == Normals::Yes)
{
setElements(elements);
}
TriangleSoup::~TriangleSoup() {
glDeleteBuffers(1, &_vertexBufferID);
glDeleteBuffers(1, &_elementBufferID);
glDeleteVertexArrays(1, &_vaoID);
}
void TriangleSoup::setVertexPositions(std::vector<glm::vec4> positions) {
_useVertexPositions = true;
_gpuDataNeedUpdate = true;
_vertexData.resize(positions.size());
for (size_t i = 0; i < positions.size(); i++)
{
_vertexData[i].position[0] = static_cast<GLfloat>(positions[i].x);
_vertexData[i].position[1] = static_cast<GLfloat>(positions[i].y);
_vertexData[i].position[2] = static_cast<GLfloat>(positions[i].z);
_vertexData[i].position[3] = static_cast<GLfloat>(positions[i].w);
}
}
void TriangleSoup::setVertexTextureCoordinates(std::vector<glm::vec2> textures) {
_useTextureCoordinates = true;
_gpuDataNeedUpdate = true;
_vertexData.resize(textures.size());
for (size_t i = 0; i < textures.size(); i++)
{
_vertexData[i].texture[0] = static_cast<GLfloat>(textures[i].s);
_vertexData[i].texture[1] = static_cast<GLfloat>(textures[i].t);
}
}
void TriangleSoup::setVertexNormals(std::vector<glm::vec3> normals) {
_useVertexNormals = true;
_gpuDataNeedUpdate = true;
_vertexData.resize(normals.size());
for (size_t i = 0; i < normals.size(); i++)
{
_vertexData[i].normal[0] = static_cast<GLfloat>(normals[i].x);
_vertexData[i].normal[1] = static_cast<GLfloat>(normals[i].y);
_vertexData[i].normal[2] = static_cast<GLfloat>(normals[i].z);
}
}
void TriangleSoup::setElements(std::vector<unsigned int> elements) {
_elementData.resize(elements.size());
_gpuDataNeedUpdate = true;
for (size_t i = 0; i < elements.size(); i++)
{
_elementData[i] = static_cast<GLuint>(elements[i]);
}
}
bool TriangleSoup::updateDataInGPU() {
// Create VAO
if (_vaoID == 0)
glGenVertexArrays(1, &_vaoID);
// Create VBOs
if (_vertexBufferID == 0 && _vertexData.size() > 0) {
glGenBuffers(1, &_vertexBufferID);
if (_vertexBufferID == 0) {
LERROR("Could not create vertex buffer");
return false;
}
}
if (_elementBufferID == 0 && _elementData.size() > 0) {
glGenBuffers(1, &_elementBufferID);
if (_elementBufferID == 0) {
LERROR("Could not create vertex element buffer");
return false;
}
}
// First VAO setup
glBindVertexArray(_vaoID);
// Vertex buffer
glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID);
glBufferData(
GL_ARRAY_BUFFER,
_vertexData.size() * sizeof(Vertex),
&_vertexData[0],
GL_STATIC_DRAW);
// Positions at location 0
if (_useVertexPositions) {
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, position)));
}
// Textures at location 1
if (_useTextureCoordinates) {
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, texture)));
}
// Normals at location 2
if (_useVertexNormals) {
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
reinterpret_cast<const GLvoid*>(offsetof(Vertex, normal)));
}
// Element buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _elementBufferID);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
_elementData.size() * sizeof(GLint),
&_elementData[0],
GL_STATIC_DRAW);
glBindVertexArray(0);
_gpuDataNeedUpdate = false;
return true;
}
void TriangleSoup::drawUsingActiveProgram() {
if (_gpuDataNeedUpdate) {
updateDataInGPU();
}
glBindVertexArray(_vaoID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _elementBufferID);
glDrawElements(GL_TRIANGLES, _elementData.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
} // namespace openspace<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCActorManager.cpp
// @Author : LvSheng.Huang
// @Date : 2012-12-15
// @Module : NFCActorManager
//
// -------------------------------------------------------------------------
#include "NFCActorManager.h"
#include "NFCPluginManager.h"
#include "NFComm/NFCore/NFCMemory.h"
#include "NFComm/NFCore/NFIComponent.h"
NFCActorManager::NFCActorManager()
{
srand((unsigned)time(NULL));
m_pFramework = new Theron::Framework(NF_ACTOR_THREAD_COUNT);
m_pPluginManager = new NFCPluginManager(this);
}
bool NFCActorManager::Init()
{
m_pMainActor = new NFCActor(*m_pFramework, this);
for (int i= 0; i < NF_ACTOR_THREAD_COUNT*2; ++i)
{
mvActorList.push_back(new NFCActor(*m_pFramework, this));
}
m_pPluginManager->Init();
return true;
}
bool NFCActorManager::AfterInit()
{
m_pPluginManager->AfterInit();
return true;
}
bool NFCActorManager::CheckConfig()
{
m_pPluginManager->CheckConfig();
return true;
}
bool NFCActorManager::BeforeShut()
{
delete m_pMainActor;
m_pMainActor = NULL;
for (int i= 0; i < NF_ACTOR_THREAD_COUNT*2; ++i)
{
NFIActor* pActor = mvActorList[i];
delete pActor;
}
mvActorList.clear();
m_pPluginManager->BeforeShut();
return true;
}
bool NFCActorManager::Shut()
{
delete m_pFramework;
m_pFramework = NULL;
m_pPluginManager->Shut();
return true;
}
bool NFCActorManager::Execute( const float fLasFrametime, const float fStartedTime )
{
m_pPluginManager->Execute(fLasFrametime, fStartedTime);
//m_pFramework->Execute();
return true;
}
int NFCActorManager::OnRequireActor(NFIComponent* pComponent)
{
//actor
if (pComponent)
{
NF_SHARE_PTR<NFIActor> pActor(NF_NEW NFCActor(*m_pFramework, this));
pActor->RegisterActorComponent(pComponent);
mxActorMap.insert(std::make_pair(pActor->GetAddress().AsInteger(), pActor));
return pActor->GetAddress().AsInteger();
}
return 0;
}
NFIActor* NFCActorManager::GetActor(const int nActorIndex)
{
std::map<int, NF_SHARE_PTR<NFIActor>>::iterator it = mxActorMap.find(nActorIndex);
if (it != mxActorMap.end())
{
return it->second.get();
}
int nIndex = rand() % (NF_ACTOR_THREAD_COUNT*2);
if (nIndex > mvActorList.size() || nIndex < 0)
{
return NULL;
}
return mvActorList[nIndex];
}
bool NFCActorManager::SendMsgToActor( const int nActorIndex, const NFIDENTID& objectID, const int nEventID, const std::string& strArg, const NF_SHARE_PTR<NFAsyncEventFunc> xActorEventList)
{
NFIActor* pActor = GetActor(nActorIndex);
if (pActor)
{
NFIActorMessage xMessage;
xMessage.eType = NFIActorMessage::EACTOR_EVENT_MSG;
xMessage.data = strArg;
xMessage.nSubMsgID = nEventID;
xMessage.nFormActor = m_pMainActor->GetAddress().AsInteger();
xMessage.self = objectID;
xMessage.xActorEventFunc = xActorEventList;
return m_pFramework->Send(xMessage, m_pMainActor->GetAddress(), pActor->GetAddress());
}
return false;
}
NFIPluginManager* NFCActorManager::GetPluginManager()
{
return m_pPluginManager;
}<commit_msg>restructure asynchronous actor model<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCActorManager.cpp
// @Author : LvSheng.Huang
// @Date : 2012-12-15
// @Module : NFCActorManager
//
// -------------------------------------------------------------------------
#include "NFCActorManager.h"
#include "NFCPluginManager.h"
#include "NFComm/NFCore/NFCMemory.h"
#include "NFComm/NFCore/NFIComponent.h"
NFCActorManager::NFCActorManager()
{
srand((unsigned)time(NULL));
m_pFramework = NF_NEW Theron::Framework(NF_ACTOR_THREAD_COUNT);
pPluginManager = NF_NEW NFCPluginManager(this);
}
bool NFCActorManager::Init()
{
m_pMainActor = NF_SHARE_PTR<NFIActor>(NF_NEW NFCActor(*m_pFramework, this));
pPluginManager->Init();
return true;
}
bool NFCActorManager::AfterInit()
{
pPluginManager->AfterInit();
return true;
}
bool NFCActorManager::CheckConfig()
{
pPluginManager->CheckConfig();
return true;
}
bool NFCActorManager::BeforeShut()
{
m_pMainActor.reset();
m_pMainActor = nullptr;
pPluginManager->BeforeShut();
return true;
}
bool NFCActorManager::Shut()
{
delete m_pFramework;
m_pFramework = NULL;
pPluginManager->Shut();
return true;
}
bool NFCActorManager::Execute( const float fLasFrametime, const float fStartedTime )
{
pPluginManager->Execute(fLasFrametime, fStartedTime);
return true;
}
int NFCActorManager::RequireActor()
{
//actor
NF_SHARE_PTR<NFIActor> pActor(NF_NEW NFCActor(*m_pFramework, this));
mxActorMap.insert(std::make_pair(pActor->GetAddress().AsInteger(), pActor));
return pActor->GetAddress().AsInteger();
}
NF_SHARE_PTR<NFIActor> NFCActorManager::GetActor(const int nActorIndex)
{
std::map<int, NF_SHARE_PTR<NFIActor> >::iterator it = mxActorMap.find(nActorIndex);
if (it != mxActorMap.end())
{
return it->second;
}
return NF_SHARE_PTR<NFIActor>();
}
bool NFCActorManager::SendMsgToActor( const int nActorIndex, const NFIDENTID& objectID, const int nEventID, const std::string& strArg, const NF_SHARE_PTR<NFAsyncEventFunc> xActorEventList)
{
NF_SHARE_PTR<NFIActor> pActor = GetActor(nActorIndex);
if (nullptr != pActor)
{
NFIActorMessage xMessage;
xMessage.eType = NFIActorMessage::EACTOR_EVENT_MSG;
xMessage.data = strArg;
xMessage.nSubMsgID = nEventID;
xMessage.nFormActor = m_pMainActor->GetAddress().AsInteger();
xMessage.self = objectID;
xMessage.xActorEventFunc = xActorEventList;
return m_pFramework->Send(xMessage, m_pMainActor->GetAddress(), pActor->GetAddress());
}
return false;
}
bool NFCActorManager::AddComponent( const int nActorIndex, NF_SHARE_PTR<NFIComponent> pComponent )
{
NF_SHARE_PTR<NFIActor> pActor = GetActor(nActorIndex);
if (nullptr != pActor)
{
pActor->AddComponent(pComponent);
return true;
}
return false;
}
bool NFCActorManager::ReleaseActor( const int nActorIndex )
{
std::map<int, NF_SHARE_PTR<NFIActor> >::iterator it = mxActorMap.find(nActorIndex);
if (it != mxActorMap.end())
{
mxActorMap.erase(it);
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OgreConversionUtils.h"
#include "OgreParticleAsset.h"
#include "OgreRenderingModule.h"
#include "OgreMaterialUtils.h"
#include "Renderer.h"
#include <Ogre.h>
using namespace OgreRenderer;
void ModifyVectorParameter(Ogre::String& line, std::vector<Ogre::String>& line_vec);
OgreParticleAsset::~OgreParticleAsset()
{
Unload();
}
std::vector<AssetReference> OgreParticleAsset::FindReferences() const
{
return references_;
}
void OgreParticleAsset::Unload()
{
RemoveTemplates();
}
bool OgreParticleAsset::DeserializeFromData(const u8 *data_, size_t numBytes)
{
OgreRenderer::OgreRenderingModule::LogInfo("Begin deserializing particle asset");
RemoveTemplates();
references_.clear();
if (!data_)
{
OgreRenderer::OgreRenderingModule::LogError("Null source asset data pointer");
return false;
}
if (numBytes == 0)
{
OgreRenderer::OgreRenderingModule::LogError("Zero sized particle system asset");
return false;
}
// Detected template names
StringVector new_templates;
std::vector<u8> tempData(data_, data_ + numBytes);
Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&tempData[0], numBytes));
try
{
int brace_level = 0;
bool skip_until_next = false;
int skip_brace_level = 0;
// Parsed/modified script
std::ostringstream output;
while (!data->eof())
{
Ogre::String line = data->getLine();
// Skip empty lines & comments
if ((line.length()) && (line.substr(0, 2) != "//"))
{
// Split line to components
std::vector<Ogre::String> line_vec;
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6
line_vec = Ogre::StringUtil::split(line, "\t ");
#else
Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,"\t ");
int size = vec.size();
line_vec.resize(size);
for (int i = 0; i < size; ++i)
line_vec[i] = vec[i];
#endif
// Check for vector parameters to be modified, so that particle scripts can be authored in typical Ogre coord system
ModifyVectorParameter(line, line_vec);
// Process opening/closing braces
if (!ProcessBraces(line, brace_level))
{
// If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal
if (brace_level == 0)
{
line = SanitateAssetIdForOgre(this->Name().toStdString()) + "_" + boost::lexical_cast<std::string>(new_templates.size());
new_templates.push_back(line);
// New script compilers need this
line = "particle_system " + line;
}
else
{
// Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded
if (line_vec[0] == "affector")
{
if (line_vec.size() >= 2)
{
if (line_vec[1] == "ColourImage")
{
skip_until_next = true;
skip_brace_level = brace_level;
}
}
}
// Check for material definition
else if (line_vec[0] == "material")
{
if (line_vec.size() >= 2)
{
// Tundra: we only support material refs in particle scripts
std::string mat_name = line_vec[1];
references_.push_back(AssetReference(mat_name.c_str()));
line = "material " + SanitateAssetIdForOgre(mat_name);
}
}
}
// Write line to the copy
if (!skip_until_next)
{
std::cout << line << std::endl;
output << line << std::endl;
}
else
OgreRenderer::OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
}
else
{
// Write line to the copy
if (!skip_until_next)
{
std::cout << line << std::endl;
output << line << std::endl;
}
else
OgreRenderer::OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
if (brace_level <= skip_brace_level)
skip_until_next = false;
}
}
}
std::string output_str = output.str();
Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&output_str[0], output_str.size()));
Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
}
catch (Ogre::Exception& e)
{
OgreRenderer::OgreRenderingModule::LogWarning(e.what());
OgreRenderer::OgreRenderingModule::LogWarning("Failed to parse Ogre particle script " + Name().toStdString() + ".");
}
// Check which templates actually succeeded
for (uint i = 0; i < new_templates.size(); ++i)
{
if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i]))
{
templates_.push_back(new_templates[i]);
OgreRenderer::OgreRenderingModule::LogDebug("Ogre particle system template " + new_templates[i] + " created");
}
}
// Give only the name of the first template
internal_name_ = SanitateAssetIdForOgre(Name().toStdString()) + "_0";
// Theoretical success if at least one template was created
return GetNumTemplates() > 0;
}
int OgreParticleAsset::GetNumTemplates() const
{
return templates_.size();
}
QString OgreParticleAsset::GetTemplateName(int index) const
{
if (index >= templates_.size())
return "";
return templates_[index].c_str();
}
void OgreParticleAsset::RemoveTemplates()
{
for (unsigned i = 0; i < templates_.size(); ++i)
{
try
{
Ogre::ParticleSystemManager::getSingleton().removeTemplate(templates_[i]);
} catch (...) {}
}
templates_.clear();
}
void ModifyVectorParameter(Ogre::String& line, std::vector<Ogre::String>& line_vec)
{
static const std::string modify_these[] = {"position", "direction", "force_vector", "common_direction", "common_up_vector", "plane_point", "plane_normal", ""};
// Line should consist of the command & 3 values
if (line_vec.size() != 4)
return;
for (uint i = 0; modify_these[i].length(); ++i)
{
if (line_vec[0] == modify_these[i])
{
try
{
float x = ParseString<float>(line_vec[1]);
float y = ParseString<float>(line_vec[2]);
float z = ParseString<float>(line_vec[3]);
// For compatibility with old rex assets, the Z coord has to be reversed
std::stringstream s;
s << line_vec[0] << " " << x << " " << y << " " << -z;
// Write back the modified string
line = s.str();
}
catch (...)
{
}
return;
}
}
}
<commit_msg>Removed debug prints.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OgreConversionUtils.h"
#include "OgreParticleAsset.h"
#include "OgreRenderingModule.h"
#include "OgreMaterialUtils.h"
#include "Renderer.h"
#include <Ogre.h>
using namespace OgreRenderer;
void ModifyVectorParameter(Ogre::String& line, std::vector<Ogre::String>& line_vec);
OgreParticleAsset::~OgreParticleAsset()
{
Unload();
}
std::vector<AssetReference> OgreParticleAsset::FindReferences() const
{
return references_;
}
void OgreParticleAsset::Unload()
{
RemoveTemplates();
}
bool OgreParticleAsset::DeserializeFromData(const u8 *data_, size_t numBytes)
{
RemoveTemplates();
references_.clear();
if (!data_)
{
OgreRenderer::OgreRenderingModule::LogError("Null source asset data pointer");
return false;
}
if (numBytes == 0)
{
OgreRenderer::OgreRenderingModule::LogError("Zero sized particle system asset");
return false;
}
// Detected template names
StringVector new_templates;
std::vector<u8> tempData(data_, data_ + numBytes);
Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&tempData[0], numBytes));
try
{
int brace_level = 0;
bool skip_until_next = false;
int skip_brace_level = 0;
// Parsed/modified script
std::ostringstream output;
while (!data->eof())
{
Ogre::String line = data->getLine();
// Skip empty lines & comments
if ((line.length()) && (line.substr(0, 2) != "//"))
{
// Split line to components
std::vector<Ogre::String> line_vec;
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6
line_vec = Ogre::StringUtil::split(line, "\t ");
#else
Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,"\t ");
int size = vec.size();
line_vec.resize(size);
for (int i = 0; i < size; ++i)
line_vec[i] = vec[i];
#endif
// Check for vector parameters to be modified, so that particle scripts can be authored in typical Ogre coord system
ModifyVectorParameter(line, line_vec);
// Process opening/closing braces
if (!ProcessBraces(line, brace_level))
{
// If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal
if (brace_level == 0)
{
line = SanitateAssetIdForOgre(this->Name().toStdString()) + "_" + boost::lexical_cast<std::string>(new_templates.size());
new_templates.push_back(line);
// New script compilers need this
line = "particle_system " + line;
}
else
{
// Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded
if (line_vec[0] == "affector")
{
if (line_vec.size() >= 2)
{
if (line_vec[1] == "ColourImage")
{
skip_until_next = true;
skip_brace_level = brace_level;
}
}
}
// Check for material definition
else if (line_vec[0] == "material")
{
if (line_vec.size() >= 2)
{
// Tundra: we only support material refs in particle scripts
std::string mat_name = line_vec[1];
references_.push_back(AssetReference(mat_name.c_str()));
line = "material " + SanitateAssetIdForOgre(mat_name);
}
}
}
// Write line to the copy
if (!skip_until_next)
{
output << line << std::endl;
}
else
OgreRenderer::OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
}
else
{
// Write line to the copy
if (!skip_until_next)
{
output << line << std::endl;
}
else
OgreRenderer::OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
if (brace_level <= skip_brace_level)
skip_until_next = false;
}
}
}
std::string output_str = output.str();
Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&output_str[0], output_str.size()));
Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
}
catch (Ogre::Exception& e)
{
OgreRenderer::OgreRenderingModule::LogWarning(e.what());
OgreRenderer::OgreRenderingModule::LogWarning("Failed to parse Ogre particle script " + Name().toStdString() + ".");
}
// Check which templates actually succeeded
for (uint i = 0; i < new_templates.size(); ++i)
{
if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i]))
{
templates_.push_back(new_templates[i]);
OgreRenderer::OgreRenderingModule::LogDebug("Ogre particle system template " + new_templates[i] + " created");
}
}
// Give only the name of the first template
internal_name_ = SanitateAssetIdForOgre(Name().toStdString()) + "_0";
// Theoretical success if at least one template was created
return GetNumTemplates() > 0;
}
int OgreParticleAsset::GetNumTemplates() const
{
return templates_.size();
}
QString OgreParticleAsset::GetTemplateName(int index) const
{
if (index >= templates_.size())
return "";
return templates_[index].c_str();
}
void OgreParticleAsset::RemoveTemplates()
{
for (unsigned i = 0; i < templates_.size(); ++i)
{
try
{
Ogre::ParticleSystemManager::getSingleton().removeTemplate(templates_[i]);
} catch (...) {}
}
templates_.clear();
}
void ModifyVectorParameter(Ogre::String& line, std::vector<Ogre::String>& line_vec)
{
static const std::string modify_these[] = {"position", "direction", "force_vector", "common_direction", "common_up_vector", "plane_point", "plane_normal", ""};
// Line should consist of the command & 3 values
if (line_vec.size() != 4)
return;
for (uint i = 0; modify_these[i].length(); ++i)
{
if (line_vec[0] == modify_these[i])
{
try
{
float x = ParseString<float>(line_vec[1]);
float y = ParseString<float>(line_vec[2]);
float z = ParseString<float>(line_vec[3]);
// For compatibility with old rex assets, the Z coord has to be reversed
std::stringstream s;
s << line_vec[0] << " " << x << " " << y << " " << -z;
// Write back the modified string
line = s.str();
}
catch (...)
{
}
return;
}
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include "eigen.hh"
#include "eigen.hh"
namespace jcc {
template <int a_rows, int b_rows, int cols>
MatNd<a_rows + b_rows, cols> vstack(const MatNd<a_rows, cols> &a, const MatNd<b_rows, cols> &b) {
MatNd<a_rows + b_rows, cols> ab;
ab << a, b;
return ab;
}
template <int a_cols, int b_cols, int rows>
MatNd<rows, a_cols + b_cols> hstack(const MatNd<rows, a_cols> &a, const MatNd<rows, b_cols> &b) {
MatNd<rows, a_cols + b_cols> ab;
ab.template leftCols<a_cols>() = a;
ab.template rightCols<b_cols>() = b;
return ab;
}
template <int cols>
VecNd<cols + 1> augment(const VecNd<cols> &a, const double val) {
VecNd<cols + 1> v;
v << a, val;
return v;
}
}
<commit_msg>More template jello<commit_after>#pragma once
#include "eigen.hh"
#include "eigen.hh"
namespace jcc {
template <int a_rows, int b_rows, int cols>
MatNd<a_rows + b_rows, cols> vstack(const MatNd<a_rows, cols> &a, const MatNd<b_rows, cols> &b) {
MatNd<a_rows + b_rows, cols> ab;
ab.template topRows<a_rows>() = a;
ab.template bottomRows<b_rows>() = b;
return ab;
}
template <int a_cols, int b_cols, int rows>
MatNd<rows, a_cols + b_cols> hstack(const MatNd<rows, a_cols> &a, const MatNd<rows, b_cols> &b) {
MatNd<rows, a_cols + b_cols> ab;
ab.template leftCols<a_cols>() = a;
ab.template rightCols<b_cols>() = b;
return ab;
}
template <int cols>
VecNd<cols + 1> augment(const VecNd<cols> &a, const double val) {
VecNd<cols + 1> v;
v.template head<cols>() = a;
v[cols] = val;
return v;
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed in accordance with the terms specified in
* the LICENSE file found in the root directory of this source tree.
*/
#include <IOKit/IOMessage.h>
#include <osquery/utils/conversions/darwin/iokit.h>
#include <osquery/events/darwin/iokit.h>
#include <osquery/logger.h>
#include <osquery/registry_factory.h>
#include <osquery/tables.h>
namespace osquery {
REGISTER(IOKitEventPublisher, "event_publisher", "iokit");
struct DeviceTracker : private boost::noncopyable {
public:
explicit DeviceTracker(IOKitEventPublisher* p) : publisher(p) {}
public:
IOKitEventPublisher* publisher{nullptr};
io_object_t notification{0};
};
void IOKitEventPublisher::restart() {
static std::vector<const std::string*> device_classes = {
&kIOUSBDeviceClassName_,
&kIOPCIDeviceClassName_,
&kIOPlatformExpertDeviceClassName_,
&kIOACPIPlatformDeviceClassName_,
&kIOPlatformDeviceClassname_,
};
if (run_loop_ == nullptr) {
return;
}
// Remove any existing stream.
stop();
{
WriteLock lock(mutex_);
port_ = IONotificationPortCreate(kIOMasterPortDefault);
// Get a run loop source from the created IOKit notification port.
auto run_loop_source = IONotificationPortGetRunLoopSource(port_);
CFRunLoopAddSource(run_loop_, run_loop_source, kCFRunLoopDefaultMode);
}
publisher_started_ = false;
for (const auto& class_name : device_classes) {
// Service matching is USB for now, must find a way to get more!
// Can provide a "IOPCIDevice" here too.
auto matches = IOServiceMatching(class_name->c_str());
// Register attach/detaches (could use kIOPublishNotification).
// Notification types are defined in IOKitKeys.
IOReturn result = kIOReturnSuccess + 1;
{
WriteLock lock(mutex_);
result = IOServiceAddMatchingNotification(
port_,
kIOFirstMatchNotification,
matches,
(IOServiceMatchingCallback)deviceAttach,
this,
&iterator_);
}
if (result == kIOReturnSuccess) {
deviceAttach(this, iterator_);
}
}
publisher_started_ = true;
}
void IOKitEventPublisher::newEvent(const io_service_t& device,
IOKitEventContext::Action action) {
auto ec = createEventContext();
ec->action = action;
{
// The IORegistry name is not needed.
io_name_t class_name = {0};
if (IOObjectGetClass(device, class_name) != kIOReturnSuccess) {
return;
}
ec->type = std::string(class_name);
}
// Get the device details
CFMutableDictionaryRef details;
IORegistryEntryCreateCFProperties(
device, &details, kCFAllocatorDefault, kNilOptions);
if (ec->type == kIOUSBDeviceClassName_) {
ec->path = getIOKitProperty(details, "USB Address") + ":";
ec->path += getIOKitProperty(details, "PortNum");
ec->model = getIOKitProperty(details, "USB Product Name");
ec->model_id = getIOKitProperty(details, "idProduct");
ec->vendor = getIOKitProperty(details, "USB Vendor Name");
ec->vendor_id = getIOKitProperty(details, "idVendor");
idToHex(ec->vendor_id);
idToHex(ec->model_id);
ec->serial = getIOKitProperty(details, "USB Serial Number");
if (ec->serial.size() == 0) {
ec->serial = getIOKitProperty(details, "iSerialNumber");
}
ec->version = "";
ec->driver = getIOKitProperty(details, "IOUserClientClass");
} else if (ec->type == kIOPCIDeviceClassName_) {
auto compatible = getIOKitProperty(details, "compatible");
auto properties = IOKitPCIProperties(compatible);
ec->model_id = properties.model_id;
ec->vendor_id = properties.vendor_id;
ec->driver = properties.driver;
if (ec->driver.empty()) {
ec->driver = getIOKitProperty(details, "IOName");
}
ec->path = getIOKitProperty(details, "pcidebug");
ec->version = getIOKitProperty(details, "revision-id");
ec->model = getIOKitProperty(details, "model");
} else {
// Get the name as the model.
io_name_t name = {0};
IORegistryEntryGetName(device, name);
if (name[0] != 0) {
ec->model = std::string(name);
}
}
CFRelease(details);
fire(ec);
}
void IOKitEventPublisher::deviceAttach(void* refcon, io_iterator_t iterator) {
auto self = (IOKitEventPublisher*)refcon;
io_service_t device;
// The iterator may also have become invalid due to a change in the registry.
// It is possible to reiterate devices, but that will cause duplicate events.
while ((device = IOIteratorNext(iterator))) {
// Create a notification tracker.
{
WriteLock lock(self->mutex_);
auto tracker = std::make_shared<struct DeviceTracker>(self);
self->devices_.push_back(tracker);
IOServiceAddInterestNotification(self->port_,
device,
kIOGeneralInterest,
(IOServiceInterestCallback)deviceDetach,
tracker.get(),
&(tracker->notification));
}
if (self->publisher_started_) {
self->newEvent(device, IOKitEventContext::Action::DEVICE_ATTACH);
}
IOObjectRelease(device);
}
}
void IOKitEventPublisher::deviceDetach(void* refcon,
io_service_t device,
natural_t message_type,
void*) {
if (message_type != kIOMessageServiceIsTerminated) {
// This is an unexpected notification.
return;
}
auto* tracker = (struct DeviceTracker*)refcon;
auto* self = tracker->publisher;
// The device tracker allows us to emit using the publisher and release the
// notification created for this device.
self->newEvent(device, IOKitEventContext::Action::DEVICE_DETACH);
IOObjectRelease(device);
{
WriteLock lock(self->mutex_);
// Remove the device tracker.
IOObjectRelease(tracker->notification);
auto it = self->devices_.begin();
while (it != self->devices_.end()) {
if ((*it)->notification == tracker->notification) {
IOObjectRelease((*it)->notification);
self->devices_.erase(it);
break;
}
it++;
}
}
}
Status IOKitEventPublisher::run() {
// The run entrypoint executes in a dedicated thread.
if (run_loop_ == nullptr) {
run_loop_ = CFRunLoopGetCurrent();
// Restart the stream creation.
restart();
}
// Start the run loop, it may be removed with a tearDown.
CFRunLoopRun();
return Status::success();
}
bool IOKitEventPublisher::shouldFire(const IOKitSubscriptionContextRef& sc,
const IOKitEventContextRef& ec) const {
if (!sc->type.empty() && sc->type != ec->type) {
return false;
} else if (!sc->model_id.empty() && sc->model_id != ec->model_id) {
return false;
} else if (!sc->vendor_id.empty() && sc->vendor_id != ec->vendor_id) {
return false;
}
return true;
}
void IOKitEventPublisher::stop() {
if (run_loop_ == nullptr) {
// If there is no run loop then the publisher thread has not started.
return;
}
// Stop the run loop.
WriteLock lock(mutex_);
CFRunLoopStop(run_loop_);
// Stop the run loop before operating on containers.
// Destroy the IOPort.
if (port_ != nullptr) {
auto source = IONotificationPortGetRunLoopSource(port_);
if (CFRunLoopContainsSource(run_loop_, source, kCFRunLoopDefaultMode)) {
CFRunLoopRemoveSource(run_loop_, source, kCFRunLoopDefaultMode);
}
// And destroy the port.
IONotificationPortDestroy(port_);
port_ = nullptr;
}
// Clear all devices and their notifications.
for (const auto& device : devices_) {
IOObjectRelease(device->notification);
}
devices_.clear();
}
void IOKitEventPublisher::tearDown() {
stop();
// Do not keep a reference to the run loop.
run_loop_ = nullptr;
}
}
<commit_msg>iokit: Fix race when accessing port_ (#6380)<commit_after>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed in accordance with the terms specified in
* the LICENSE file found in the root directory of this source tree.
*/
#include <IOKit/IOMessage.h>
#include <osquery/utils/conversions/darwin/iokit.h>
#include <osquery/events/darwin/iokit.h>
#include <osquery/logger.h>
#include <osquery/registry_factory.h>
#include <osquery/tables.h>
namespace osquery {
REGISTER(IOKitEventPublisher, "event_publisher", "iokit");
struct DeviceTracker : private boost::noncopyable {
public:
explicit DeviceTracker(IOKitEventPublisher* p) : publisher(p) {}
public:
IOKitEventPublisher* publisher{nullptr};
io_object_t notification{0};
};
void IOKitEventPublisher::restart() {
static std::vector<const std::string*> device_classes = {
&kIOUSBDeviceClassName_,
&kIOPCIDeviceClassName_,
&kIOPlatformExpertDeviceClassName_,
&kIOACPIPlatformDeviceClassName_,
&kIOPlatformDeviceClassname_,
};
if (run_loop_ == nullptr) {
return;
}
// Remove any existing stream.
stop();
{
WriteLock lock(mutex_);
port_ = IONotificationPortCreate(kIOMasterPortDefault);
// Get a run loop source from the created IOKit notification port.
auto run_loop_source = IONotificationPortGetRunLoopSource(port_);
CFRunLoopAddSource(run_loop_, run_loop_source, kCFRunLoopDefaultMode);
}
publisher_started_ = false;
for (const auto& class_name : device_classes) {
// Service matching is USB for now, must find a way to get more!
// Can provide a "IOPCIDevice" here too.
auto matches = IOServiceMatching(class_name->c_str());
// Register attach/detaches (could use kIOPublishNotification).
// Notification types are defined in IOKitKeys.
IOReturn result = kIOReturnSuccess + 1;
{
WriteLock lock(mutex_);
if (port_ == nullptr) {
return;
}
result = IOServiceAddMatchingNotification(
port_,
kIOFirstMatchNotification,
matches,
(IOServiceMatchingCallback)deviceAttach,
this,
&iterator_);
}
if (result == kIOReturnSuccess) {
deviceAttach(this, iterator_);
}
}
publisher_started_ = true;
}
void IOKitEventPublisher::newEvent(const io_service_t& device,
IOKitEventContext::Action action) {
auto ec = createEventContext();
ec->action = action;
{
// The IORegistry name is not needed.
io_name_t class_name = {0};
if (IOObjectGetClass(device, class_name) != kIOReturnSuccess) {
return;
}
ec->type = std::string(class_name);
}
// Get the device details
CFMutableDictionaryRef details;
IORegistryEntryCreateCFProperties(
device, &details, kCFAllocatorDefault, kNilOptions);
if (ec->type == kIOUSBDeviceClassName_) {
ec->path = getIOKitProperty(details, "USB Address") + ":";
ec->path += getIOKitProperty(details, "PortNum");
ec->model = getIOKitProperty(details, "USB Product Name");
ec->model_id = getIOKitProperty(details, "idProduct");
ec->vendor = getIOKitProperty(details, "USB Vendor Name");
ec->vendor_id = getIOKitProperty(details, "idVendor");
idToHex(ec->vendor_id);
idToHex(ec->model_id);
ec->serial = getIOKitProperty(details, "USB Serial Number");
if (ec->serial.size() == 0) {
ec->serial = getIOKitProperty(details, "iSerialNumber");
}
ec->version = "";
ec->driver = getIOKitProperty(details, "IOUserClientClass");
} else if (ec->type == kIOPCIDeviceClassName_) {
auto compatible = getIOKitProperty(details, "compatible");
auto properties = IOKitPCIProperties(compatible);
ec->model_id = properties.model_id;
ec->vendor_id = properties.vendor_id;
ec->driver = properties.driver;
if (ec->driver.empty()) {
ec->driver = getIOKitProperty(details, "IOName");
}
ec->path = getIOKitProperty(details, "pcidebug");
ec->version = getIOKitProperty(details, "revision-id");
ec->model = getIOKitProperty(details, "model");
} else {
// Get the name as the model.
io_name_t name = {0};
IORegistryEntryGetName(device, name);
if (name[0] != 0) {
ec->model = std::string(name);
}
}
CFRelease(details);
fire(ec);
}
void IOKitEventPublisher::deviceAttach(void* refcon, io_iterator_t iterator) {
auto self = (IOKitEventPublisher*)refcon;
io_service_t device;
// The iterator may also have become invalid due to a change in the registry.
// It is possible to reiterate devices, but that will cause duplicate events.
while ((device = IOIteratorNext(iterator))) {
{
WriteLock lock(self->mutex_);
if (self->port_ == nullptr) {
IOObjectRelease(device);
continue;
}
// Create a notification tracker.
auto tracker = std::make_shared<struct DeviceTracker>(self);
self->devices_.push_back(tracker);
IOServiceAddInterestNotification(self->port_,
device,
kIOGeneralInterest,
(IOServiceInterestCallback)deviceDetach,
tracker.get(),
&(tracker->notification));
}
if (self->publisher_started_) {
self->newEvent(device, IOKitEventContext::Action::DEVICE_ATTACH);
}
IOObjectRelease(device);
}
}
void IOKitEventPublisher::deviceDetach(void* refcon,
io_service_t device,
natural_t message_type,
void*) {
if (message_type != kIOMessageServiceIsTerminated) {
// This is an unexpected notification.
return;
}
auto* tracker = (struct DeviceTracker*)refcon;
auto* self = tracker->publisher;
// The device tracker allows us to emit using the publisher and release the
// notification created for this device.
self->newEvent(device, IOKitEventContext::Action::DEVICE_DETACH);
IOObjectRelease(device);
{
WriteLock lock(self->mutex_);
// Remove the device tracker.
IOObjectRelease(tracker->notification);
auto it = self->devices_.begin();
while (it != self->devices_.end()) {
if ((*it)->notification == tracker->notification) {
IOObjectRelease((*it)->notification);
self->devices_.erase(it);
break;
}
it++;
}
}
}
Status IOKitEventPublisher::run() {
// The run entrypoint executes in a dedicated thread.
if (run_loop_ == nullptr) {
run_loop_ = CFRunLoopGetCurrent();
// Restart the stream creation.
restart();
}
// Start the run loop, it may be removed with a tearDown.
CFRunLoopRun();
return Status::success();
}
bool IOKitEventPublisher::shouldFire(const IOKitSubscriptionContextRef& sc,
const IOKitEventContextRef& ec) const {
if (!sc->type.empty() && sc->type != ec->type) {
return false;
} else if (!sc->model_id.empty() && sc->model_id != ec->model_id) {
return false;
} else if (!sc->vendor_id.empty() && sc->vendor_id != ec->vendor_id) {
return false;
}
return true;
}
void IOKitEventPublisher::stop() {
if (run_loop_ == nullptr) {
// If there is no run loop then the publisher thread has not started.
return;
}
// Stop the run loop.
WriteLock lock(mutex_);
CFRunLoopStop(run_loop_);
// Stop the run loop before operating on containers.
// Destroy the IOPort.
if (port_ != nullptr) {
auto source = IONotificationPortGetRunLoopSource(port_);
if (CFRunLoopContainsSource(run_loop_, source, kCFRunLoopDefaultMode)) {
CFRunLoopRemoveSource(run_loop_, source, kCFRunLoopDefaultMode);
}
// And destroy the port.
IONotificationPortDestroy(port_);
port_ = nullptr;
}
// Clear all devices and their notifications.
for (const auto& device : devices_) {
IOObjectRelease(device->notification);
}
devices_.clear();
}
void IOKitEventPublisher::tearDown() {
stop();
// Do not keep a reference to the run loop.
run_loop_ = nullptr;
}
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680)
#define XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <algorithm>
#include <XalanDOM/XalanDOMString.hpp>
#include <Include/STLHelper.hpp>
#include <XPath/Function.hpp>
#include <XPath/XalanXPathException.hpp>
class Locator;
/**
* Exception class thrown when an unknown function is encountered
*/
class XALAN_XPATH_EXPORT XPathExceptionFunctionNotAvailable : public XalanXPathException
{
public:
XPathExceptionFunctionNotAvailable(int theFunctionNumber);
XPathExceptionFunctionNotAvailable(const XalanDOMString& theFunctionName);
XPathExceptionFunctionNotAvailable(
int theFunctionNumber,
const Locator& theLocator);
XPathExceptionFunctionNotAvailable(
const XalanDOMString& theFunctionName,
const Locator& theLocator);
~XPathExceptionFunctionNotAvailable();
};
/**
* Exception class thrown when an installFunction() is called with a
* function name that is not supported.
*/
class XALAN_XPATH_EXPORT XPathExceptionFunctionNotSupported : public XalanXPathException
{
public:
XPathExceptionFunctionNotSupported(const XalanDOMChar* theFunctionName);
~XPathExceptionFunctionNotSupported();
};
/**
* Class defines a table of functions that can be called in XPath expresions.
*/
class XALAN_XPATH_EXPORT XPathFunctionTable
{
public:
enum { InvalidFunctionNumberID = -1, TableSize = 36 };
typedef size_t SizeType;
typedef XalanDOMString::size_type StringSizeType;
typedef DeleteFunctor<Function> DeleteFunctorType;
/**
* Constructor.
*
* @param fCreateTable If true, the internal table will be created. Otherwise, CreateTable() must be called.
*/
XPathFunctionTable(bool fCreateTable = true);
~XPathFunctionTable();
/**
* Set up the internal table.
*/
void
CreateTable();
/**
* Destroy the internal table.
*/
void
DestroyTable();
/**
* Retrieve the function object for a specified function name.
*
* @param theFunctionName name of function
* @return function named
*/
const Function&
operator[](const XalanDOMString& theFunctionName) const
{
const int theFunctionID =
getFunctionIndex(theFunctionName);
if (theFunctionID != InvalidFunctionNumberID)
{
return *m_functionTable[theFunctionID];
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionName);
}
}
/**
* Retrieve the function object for a specified function ID number.
*
* @param theFunctionID ID number of the function
* @return function named
*/
const Function&
operator[](int theFunctionID) const
{
assert(theFunctionID >= 0 && theFunctionID < TableSize);
assert(m_functionTable[theFunctionID] != 0);
return *m_functionTable[theFunctionID];
}
/**
* Map a function ID to the corresponding name.
*
* @param theFunctionID The ID number of the function
* @return The name of the function, or an empty string if the function doesn't exist.
*/
const XalanDOMString
idToName(int theFunctionID) const
{
XalanDOMString theName;
if (theFunctionID >= 0 && theFunctionID < TableSize)
{
theName.assign(
s_functionNames[theFunctionID].m_name,
s_functionNames[theFunctionID].m_size);
}
return theName;
}
/**
* Map a function name to the corresponding ID number.
*
* @param theName name of function
* @return The ID number of function, or InvalidFunctionNumberID if the function doesn't exist.
*/
int
nameToID(const XalanDOMString& theName) const
{
return getFunctionIndex(theName);
}
/**
* Insert a named function into the function table.
*
* @param theFunctionName name of function
* @param theFunction function object corresponding to name
*/
void
InstallFunction(
const XalanDOMString& theFunctionName,
const Function& theFunction)
{
InstallFunction(theFunctionName.c_str(), theFunction);
}
/**
* Remove a named function from the function table.
*
* @param theFunctionName name of function
* @return true if the function was found and removed.
*/
bool
UninstallFunction(const XalanDOMString& theFunctionName)
{
return UninstallFunction(theFunctionName.c_str());
}
/**
* Insert a named function into the function table.
*
* @param theFunctionName name of function
* @param theFunction function object corresponding to name
*/
void
InstallFunction(
const XalanDOMChar* theFunctionName,
const Function& theFunction);
/**
* Remove a named function from the function table.
*
* @param theFunctionName name of function
* @return true if the function was found and removed.
*/
bool
UninstallFunction(const XalanDOMChar* theFunctionName);
/**
* Whether a named function is in the function table.
*
* @param theFunctionName name of function
* @return true if function is in table
*/
bool
isInstalledFunction(const XalanDOMString& theFunctionName) const
{
return getFunctionIndex(theFunctionName) != InvalidFunctionNumberID ? true : false;
}
#if defined(XALAN_NO_MEMBER_TEMPLATES)
#if defined(XALAN_NO_NAMESPACES)
typedef vector<XalanDOMString> InstalledFunctionNameVectorType;
#else
typedef std::vector<XalanDOMString> InstalledFunctionNameVectorType;
#endif
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theVector vector of function name strings added to
*/
void
getInstalledFunctionNames(InstalledFunctionNameVectorType& theVector) const
{
XalanDOMString theString;
for (int i = 0; i < TableSize; ++i)
{
if (m_functionTable[i] != 0)
{
theString.assign(
s_functionNames[i].m_name,
s_functionNames[i].size);
theVector.push_back(theString);
}
}
}
#else
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theIterator function table iterator to append names to
*/
template<class OutputIteratorType>
void
getInstalledFunctionNames(OutputIteratorType theIterator) const
{
XalanDOMString theString;
for (int i = 0; i < TableSize; ++i)
{
if (m_functionTable[i] != 0)
{
theString.assign(
s_functionNames[i].m_name,
s_functionNames[i].m_size);
*theIterator = theString;
++theIterator;
}
}
}
#endif
struct FunctionNameTableEntry
{
const XalanDOMChar* m_name;
StringSizeType m_size;
};
// These are static strings for the functions supported.
// Note that the XSLT functions are also here, since it's
// just easier to do it this way.
// The string "id"
static const XalanDOMChar s_id[];
// The string "key"
static const XalanDOMChar s_key[];
// The string "not"
static const XalanDOMChar s_not[];
// The string "sum"
static const XalanDOMChar s_sum[];
// The string "lang"
static const XalanDOMChar s_lang[];
// The string "last"
static const XalanDOMChar s_last[];
// The string "name"
static const XalanDOMChar s_name[];
// The string "true"
static const XalanDOMChar s_true[];
// The string "count"
static const XalanDOMChar s_count[];
// The string "false"
static const XalanDOMChar s_false[];
// The string "floor"
static const XalanDOMChar s_floor[];
// The string "round"
static const XalanDOMChar s_round[];
// The string "concat"
static const XalanDOMChar s_concat[];
// The string "number"
static const XalanDOMChar s_number[];
// The string "string"
static const XalanDOMChar s_string[];
// The string "boolean"
static const XalanDOMChar s_boolean[];
// The string "ceiling"
static const XalanDOMChar s_ceiling[];
// The string "current"
static const XalanDOMChar s_current[];
// The string "contains"
static const XalanDOMChar s_contains[];
// The string "document"
static const XalanDOMChar s_document[];
// The string "position"
static const XalanDOMChar s_position[];
// The string "substring"
static const XalanDOMChar s_substring[];
// The string "translate"
static const XalanDOMChar s_translate[];
// The string "local-name"
static const XalanDOMChar s_localName[];
// The string "generate-id"
static const XalanDOMChar s_generateId[];
// The string "starts-with"
static const XalanDOMChar s_startsWith[];
// The string "format-number"
static const XalanDOMChar s_formatNumber[];
// The string "namespace-uri"
static const XalanDOMChar s_namespaceUri[];
// The string "string-length"
static const XalanDOMChar s_stringLength[];
// The string "normalize-space"
static const XalanDOMChar s_normalizeSpace[];
// The string "substring-after"
static const XalanDOMChar s_substringAfter[];
// The string "system-property"
static const XalanDOMChar s_systemProperty[];
// The string "substring-before"
static const XalanDOMChar s_substringBefore[];
// The string "element-available"
static const XalanDOMChar s_elementAvailable[];
// The string "function-available"
static const XalanDOMChar s_functionAvailable[];
// The string "unparsed-entity-uri"
static const XalanDOMChar s_unparsedEntityUri[];
// A table of function names.
static const FunctionNameTableEntry s_functionNames[];
// The size of the table.
static const SizeType s_functionNamesSize;
private:
static int
getFunctionIndex(const XalanDOMString& theName)
{
return getFunctionIndex(
theName.c_str(),
theName.length());
}
static int
getFunctionIndex(const XalanDOMChar* theName)
{
return getFunctionIndex(
theName,
XalanDOMString::length(theName));
}
static int
getFunctionIndex(
const XalanDOMChar* theName,
StringSizeType theNameLength);
const Function* m_functionTable[TableSize];
const Function** const m_functionTableEnd;
// The last one in the table of function names.
static const FunctionNameTableEntry* const s_lastFunctionName;
};
#endif // XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
<commit_msg>Fixed typo.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680)
#define XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <XPath/XPathDefinitions.hpp>
#include <algorithm>
#include <XalanDOM/XalanDOMString.hpp>
#include <Include/STLHelper.hpp>
#include <XPath/Function.hpp>
#include <XPath/XalanXPathException.hpp>
class Locator;
/**
* Exception class thrown when an unknown function is encountered
*/
class XALAN_XPATH_EXPORT XPathExceptionFunctionNotAvailable : public XalanXPathException
{
public:
XPathExceptionFunctionNotAvailable(int theFunctionNumber);
XPathExceptionFunctionNotAvailable(const XalanDOMString& theFunctionName);
XPathExceptionFunctionNotAvailable(
int theFunctionNumber,
const Locator& theLocator);
XPathExceptionFunctionNotAvailable(
const XalanDOMString& theFunctionName,
const Locator& theLocator);
~XPathExceptionFunctionNotAvailable();
};
/**
* Exception class thrown when an installFunction() is called with a
* function name that is not supported.
*/
class XALAN_XPATH_EXPORT XPathExceptionFunctionNotSupported : public XalanXPathException
{
public:
XPathExceptionFunctionNotSupported(const XalanDOMChar* theFunctionName);
~XPathExceptionFunctionNotSupported();
};
/**
* Class defines a table of functions that can be called in XPath expresions.
*/
class XALAN_XPATH_EXPORT XPathFunctionTable
{
public:
enum { InvalidFunctionNumberID = -1, TableSize = 36 };
typedef size_t SizeType;
typedef XalanDOMString::size_type StringSizeType;
typedef DeleteFunctor<Function> DeleteFunctorType;
/**
* Constructor.
*
* @param fCreateTable If true, the internal table will be created. Otherwise, CreateTable() must be called.
*/
XPathFunctionTable(bool fCreateTable = true);
~XPathFunctionTable();
/**
* Set up the internal table.
*/
void
CreateTable();
/**
* Destroy the internal table.
*/
void
DestroyTable();
/**
* Retrieve the function object for a specified function name.
*
* @param theFunctionName name of function
* @return function named
*/
const Function&
operator[](const XalanDOMString& theFunctionName) const
{
const int theFunctionID =
getFunctionIndex(theFunctionName);
if (theFunctionID != InvalidFunctionNumberID)
{
return *m_functionTable[theFunctionID];
}
else
{
throw XPathExceptionFunctionNotAvailable(theFunctionName);
}
}
/**
* Retrieve the function object for a specified function ID number.
*
* @param theFunctionID ID number of the function
* @return function named
*/
const Function&
operator[](int theFunctionID) const
{
assert(theFunctionID >= 0 && theFunctionID < TableSize);
assert(m_functionTable[theFunctionID] != 0);
return *m_functionTable[theFunctionID];
}
/**
* Map a function ID to the corresponding name.
*
* @param theFunctionID The ID number of the function
* @return The name of the function, or an empty string if the function doesn't exist.
*/
const XalanDOMString
idToName(int theFunctionID) const
{
XalanDOMString theName;
if (theFunctionID >= 0 && theFunctionID < TableSize)
{
theName.assign(
s_functionNames[theFunctionID].m_name,
s_functionNames[theFunctionID].m_size);
}
return theName;
}
/**
* Map a function name to the corresponding ID number.
*
* @param theName name of function
* @return The ID number of function, or InvalidFunctionNumberID if the function doesn't exist.
*/
int
nameToID(const XalanDOMString& theName) const
{
return getFunctionIndex(theName);
}
/**
* Insert a named function into the function table.
*
* @param theFunctionName name of function
* @param theFunction function object corresponding to name
*/
void
InstallFunction(
const XalanDOMString& theFunctionName,
const Function& theFunction)
{
InstallFunction(theFunctionName.c_str(), theFunction);
}
/**
* Remove a named function from the function table.
*
* @param theFunctionName name of function
* @return true if the function was found and removed.
*/
bool
UninstallFunction(const XalanDOMString& theFunctionName)
{
return UninstallFunction(theFunctionName.c_str());
}
/**
* Insert a named function into the function table.
*
* @param theFunctionName name of function
* @param theFunction function object corresponding to name
*/
void
InstallFunction(
const XalanDOMChar* theFunctionName,
const Function& theFunction);
/**
* Remove a named function from the function table.
*
* @param theFunctionName name of function
* @return true if the function was found and removed.
*/
bool
UninstallFunction(const XalanDOMChar* theFunctionName);
/**
* Whether a named function is in the function table.
*
* @param theFunctionName name of function
* @return true if function is in table
*/
bool
isInstalledFunction(const XalanDOMString& theFunctionName) const
{
return getFunctionIndex(theFunctionName) != InvalidFunctionNumberID ? true : false;
}
#if defined(XALAN_NO_MEMBER_TEMPLATES)
#if defined(XALAN_NO_NAMESPACES)
typedef vector<XalanDOMString> InstalledFunctionNameVectorType;
#else
typedef std::vector<XalanDOMString> InstalledFunctionNameVectorType;
#endif
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theVector vector of function name strings added to
*/
void
getInstalledFunctionNames(InstalledFunctionNameVectorType& theVector) const
{
XalanDOMString theString;
for (int i = 0; i < TableSize; ++i)
{
if (m_functionTable[i] != 0)
{
theString.assign(
s_functionNames[i].m_name,
s_functionNames[i].m_size);
theVector.push_back(theString);
}
}
}
#else
/**
* Add a list of the names of installed functions to a vector of names.
*
* @param theIterator function table iterator to append names to
*/
template<class OutputIteratorType>
void
getInstalledFunctionNames(OutputIteratorType theIterator) const
{
XalanDOMString theString;
for (int i = 0; i < TableSize; ++i)
{
if (m_functionTable[i] != 0)
{
theString.assign(
s_functionNames[i].m_name,
s_functionNames[i].m_size);
*theIterator = theString;
++theIterator;
}
}
}
#endif
struct FunctionNameTableEntry
{
const XalanDOMChar* m_name;
StringSizeType m_size;
};
// These are static strings for the functions supported.
// Note that the XSLT functions are also here, since it's
// just easier to do it this way.
// The string "id"
static const XalanDOMChar s_id[];
// The string "key"
static const XalanDOMChar s_key[];
// The string "not"
static const XalanDOMChar s_not[];
// The string "sum"
static const XalanDOMChar s_sum[];
// The string "lang"
static const XalanDOMChar s_lang[];
// The string "last"
static const XalanDOMChar s_last[];
// The string "name"
static const XalanDOMChar s_name[];
// The string "true"
static const XalanDOMChar s_true[];
// The string "count"
static const XalanDOMChar s_count[];
// The string "false"
static const XalanDOMChar s_false[];
// The string "floor"
static const XalanDOMChar s_floor[];
// The string "round"
static const XalanDOMChar s_round[];
// The string "concat"
static const XalanDOMChar s_concat[];
// The string "number"
static const XalanDOMChar s_number[];
// The string "string"
static const XalanDOMChar s_string[];
// The string "boolean"
static const XalanDOMChar s_boolean[];
// The string "ceiling"
static const XalanDOMChar s_ceiling[];
// The string "current"
static const XalanDOMChar s_current[];
// The string "contains"
static const XalanDOMChar s_contains[];
// The string "document"
static const XalanDOMChar s_document[];
// The string "position"
static const XalanDOMChar s_position[];
// The string "substring"
static const XalanDOMChar s_substring[];
// The string "translate"
static const XalanDOMChar s_translate[];
// The string "local-name"
static const XalanDOMChar s_localName[];
// The string "generate-id"
static const XalanDOMChar s_generateId[];
// The string "starts-with"
static const XalanDOMChar s_startsWith[];
// The string "format-number"
static const XalanDOMChar s_formatNumber[];
// The string "namespace-uri"
static const XalanDOMChar s_namespaceUri[];
// The string "string-length"
static const XalanDOMChar s_stringLength[];
// The string "normalize-space"
static const XalanDOMChar s_normalizeSpace[];
// The string "substring-after"
static const XalanDOMChar s_substringAfter[];
// The string "system-property"
static const XalanDOMChar s_systemProperty[];
// The string "substring-before"
static const XalanDOMChar s_substringBefore[];
// The string "element-available"
static const XalanDOMChar s_elementAvailable[];
// The string "function-available"
static const XalanDOMChar s_functionAvailable[];
// The string "unparsed-entity-uri"
static const XalanDOMChar s_unparsedEntityUri[];
// A table of function names.
static const FunctionNameTableEntry s_functionNames[];
// The size of the table.
static const SizeType s_functionNamesSize;
private:
static int
getFunctionIndex(const XalanDOMString& theName)
{
return getFunctionIndex(
theName.c_str(),
theName.length());
}
static int
getFunctionIndex(const XalanDOMChar* theName)
{
return getFunctionIndex(
theName,
XalanDOMString::length(theName));
}
static int
getFunctionIndex(
const XalanDOMChar* theName,
StringSizeType theNameLength);
const Function* m_functionTable[TableSize];
const Function** const m_functionTableEnd;
// The last one in the table of function names.
static const FunctionNameTableEntry* const s_lastFunctionName;
};
#endif // XPATHFUNCTIONTABLE_HEADER_GUARD_1357924680
<|endoftext|>
|
<commit_before>#include "all.h"
#include "game/transcendental/entity_handle.h"
#include "game/transcendental/cosmos.h"
#include "game/components/gun_component.h"
#include "augs/graphics/drawers.h"
namespace rendering_scripts {
void draw_crosshair_lines(
std::function<void(vec2, vec2, rgba)> callback,
const interpolation_system& interp,
const const_entity_handle crosshair,
const const_entity_handle character) {
if (crosshair.alive()) {
vec2 line_from[2];
vec2 line_to[2];
rgba cols[2] = { cyan, cyan };
const auto crosshair_pos = crosshair.viewing_transform(interp).pos;
const auto guns = character.guns_wielded();
if (guns.size() >= 1) {
const auto subject_item = guns[0];
const auto& gun = subject_item.get<components::gun>();
const auto rifle_transform = subject_item.viewing_transform(interp);
const auto barrel_center = gun.calculate_barrel_center(rifle_transform);
const auto muzzle = gun.calculate_muzzle_position(rifle_transform);
line_from[0] = muzzle;
const auto proj = crosshair_pos.get_projection_multiplier(barrel_center, muzzle);
if (proj > 1.f) {
line_to[0] = barrel_center + (muzzle - barrel_center) * proj;
callback(line_from[0], line_to[0], cols[0]);
}
}
if (guns.size() >= 2) {
const auto subject_item = guns[1];
const auto& gun = subject_item.get<components::gun>();
const auto rifle_transform = subject_item.viewing_transform(interp);
const auto barrel_center = gun.calculate_barrel_center(rifle_transform);
const auto muzzle = gun.calculate_muzzle_position(rifle_transform);
line_from[1] = muzzle;
const auto proj = crosshair_pos.get_projection_multiplier(barrel_center, muzzle);
if (proj > 1.f) {
line_to[1] = barrel_center + (muzzle - barrel_center) * proj;
callback(line_from[1], line_to[1], cols[1]);
}
}
}
}
}<commit_msg>raycasting along the lasers<commit_after>#include "all.h"
#include "game/transcendental/entity_handle.h"
#include "game/transcendental/cosmos.h"
#include "game/components/gun_component.h"
#include "augs/graphics/drawers.h"
#include "game/systems_temporary/physics_system.h"
#include "game/enums/filters.h"
namespace rendering_scripts {
void draw_crosshair_lines(
std::function<void(vec2, vec2, rgba)> callback,
const interpolation_system& interp,
const const_entity_handle crosshair,
const const_entity_handle character) {
if (crosshair.alive()) {
const auto& physics = crosshair.get_cosmos().systems_temporary.get<physics_system>();
vec2 line_from[2];
vec2 line_to[2];
rgba cols[2] = { cyan, cyan };
const auto crosshair_pos = crosshair.viewing_transform(interp).pos;
const auto guns = character.guns_wielded();
if (guns.size() >= 1) {
const auto subject_item = guns[0];
const auto& gun = subject_item.get<components::gun>();
const auto rifle_transform = subject_item.viewing_transform(interp);
const auto barrel_center = gun.calculate_barrel_center(rifle_transform);
const auto muzzle = gun.calculate_muzzle_position(rifle_transform);
line_from[0] = muzzle;
const auto proj = crosshair_pos.get_projection_multiplier(barrel_center, muzzle);
if (proj > 1.f) {
line_to[0] = barrel_center + (muzzle - barrel_center) * proj;
const auto raycast = physics.ray_cast_px(line_from[0], line_to[0], filters::bullet(), subject_item);
if (raycast.hit) {
line_to[0] = raycast.intersection;
}
callback(line_from[0], line_to[0], cols[0]);
}
}
if (guns.size() >= 2) {
const auto subject_item = guns[1];
const auto& gun = subject_item.get<components::gun>();
const auto rifle_transform = subject_item.viewing_transform(interp);
const auto barrel_center = gun.calculate_barrel_center(rifle_transform);
const auto muzzle = gun.calculate_muzzle_position(rifle_transform);
line_from[1] = muzzle;
const auto proj = crosshair_pos.get_projection_multiplier(barrel_center, muzzle);
if (proj > 1.f) {
line_to[1] = barrel_center + (muzzle - barrel_center) * proj;
const auto raycast = physics.ray_cast_px(line_from[1], line_to[1], filters::bullet(), subject_item);
if (raycast.hit) {
line_to[1] = raycast.intersection;
}
callback(line_from[1], line_to[1], cols[1]);
}
}
}
}
}<|endoftext|>
|
<commit_before>#include <vector>
#include <iostream>
#include <utility> // std::pair<T,U>
#include <pthread.h>
#include <algorithm>
#include <cmath>
#include "utils.hpp"
int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones);
void* does_work(void *ptr);
//////global
int problemSize =0;
//int threadCount = 24;
std::vector<std::vector<int> > results;
std::vector<int> wholeCost;
std::vector< std::vector<int> > Distance;
std::vector<std::vector<double> > Pher;
std::vector<int> Locations;
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "I needs a file dammit!" << std::endl;
return 1;
}
// well what now?
// something about an algorithm...
// oh yes! i think i need to build the distance and pheromones array
// call shortest path with itthr_count
// then print out the answer
std::string fileName(argv[1]);
std::vector< std::vector<int> > dist = read_the_file(fileName);// returns a filled distance vector
std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector
problemSize = (dist.size() * dist[0].size())/2;
for(int i =0; i < ANTCOUNT; i++)
{
std::vector<int> temp;
Locations.push_back(i);
results.push_back(temp);
wholeCost.push_back(0);
}
// start time
int answer = shortest_path_dist(dist, pheromones);
// end time
std::cout << answer << std::endl;
}
// this algorithm has a structure similar to floyds
// so look there for inspiration
// note: a thread pool is the sort of thing desired
int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones)
{
std::vector<pthread_t> cur;
for(int i = 0; i < GENERATIONS; i++)
{
for(int i = 0;i < ANTCOUNT; i++)
{
int * ii = new int(i);
pthread_t temp;
pthread_create(&temp, NULL, does_work,(void*)ii);
cur.push_back(temp);
}
while(!cur.empty())
{
pthread_join(cur.back(),NULL);
cur.pop_back();
}
cur.clear();
//global update
for(int i =0; i < cur.size();i++)
cur[i] = 0;
}
// start all needed threads
// for each iteration
// for each ant : IN PARALLEL
// initialize the ant
// share distance and pheromone graph for the thread
// while a tour is not finished
// choose the next city (eq 1,2)
// atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without
// end while // end of ant's travel
// atomic: global pheromone update (eq 4)
// terminate the thread, release resources
//}
// barrier: all ants
//} // end of iteration
}
void *does_work(void *ptr)
{
int pos = 0;
int antDist = 0;
int id = *((int *)ptr);
//std::vector<double> res;
std::vector<int> history;
std::vector<int> unvisited = Locations;
while(history.size() < problemSize)
{
//res.clear();
//for(int i =0;i < problemSize; i++)
//{
// res.push_back(0.0);
//}
double choice = ((double) rand() / (RAND_MAX)) + 1;
double choice2 = ((double) rand() / (RAND_MAX)) + 1;
double max = 0;
int maxIndex =0;
if(choice < Q0){
// expliait
for(int i =0; i< problemSize; i++)
{
if(std::find(history.begin(), history.end(), i) != history.end())
continue;
double temp = Pher[pos][i] / pow(Distance[pos][i], BETA) ;
if( temp > max)
{
max =temp;
maxIndex = i;
}
}
}
else //we expolore
{
std::vector cho = eq2(Distance, Pher, unvisited, pos);
maxIndex = eq2_helper(cho,choice2);
max = Pher[pos][maxIndex] / pow(Distance[pos][maxIndex], BETA);
}
Pher[pos][maxIndex] = eq3(Pher[pos][maxIndex],problemSize);
antDist += Distance[pos][maxIndex];
pos = maxIndex;
history.push_back(maxIndex);
int temp = std::find(unvisited.begin(),unvisited.end(),maxIndex);
unvisited.erase(unvisited.begin() + temp);
}
results[id] = history;
wholeCost[id] = antDist;
}
<commit_msg>commpiles now, should have check that first<commit_after>#include <vector>
#include <iostream>
#include <utility> // std::pair<T,U>
#include <pthread.h>
#include <algorithm>
#include <cmath>
#include "utils.hpp"
int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones);
void* does_work(void *ptr);
//////global
int problemSize =0;
//int threadCount = 24;
std::vector<std::vector<int> > results;
std::vector<int> wholeCost;
std::vector< std::vector<int> > Distance;
std::vector<std::vector<double> > Pher;
std::vector<int> Locations;
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "I needs a file dammit!" << std::endl;
return 1;
}
// well what now?
// something about an algorithm...
// oh yes! i think i need to build the distance and pheromones array
// call shortest path with itthr_count
// then print out the answer
std::string fileName(argv[1]);
std::vector< std::vector<int> > dist = read_the_file(fileName);// returns a filled distance vector
std::vector<std::vector<double> > pheromones = setup_pheromones(dist); // returns a filled pheromone vector
problemSize = (dist.size() * dist[0].size())/2;
for(int i =0; i < ANTCOUNT; i++)
{
std::vector<int> temp;
Locations.push_back(i);
results.push_back(temp);
wholeCost.push_back(0);
}
// start time
int answer = shortest_path_dist(dist, pheromones);
// end time
std::cout << answer << std::endl;
}
// this algorithm has a structure similar to floyds
// so look there for inspiration
// note: a thread pool is the sort of thing desired
int shortest_path_dist(std::vector< std::vector<int> > dist, std::vector< std::vector<double> > pheromones)
{
std::vector<pthread_t> cur;
for(int i = 0; i < GENERATIONS; i++)
{
for(int i = 0;i < ANTCOUNT; i++)
{
int * ii = new int(i);
pthread_t temp;
pthread_create(&temp, NULL, does_work,(void*)ii);
cur.push_back(temp);
}
while(!cur.empty())
{
pthread_join(cur.back(),NULL);
cur.pop_back();
}
cur.clear();
//global update
for(int i =0; i < cur.size();i++)
cur[i] = 0;
}
// start all needed threads
// for each iteration
// for each ant : IN PARALLEL
// initialize the ant
// share distance and pheromone graph for the thread
// while a tour is not finished
// choose the next city (eq 1,2)
// atomic: local pheromone update (eq 3) // after reading the paper (pg 3-4), it may be possible to drop this with minimal adverse affect, we will have to time with and without
// end while // end of ant's travel
// atomic: global pheromone update (eq 4)
// terminate the thread, release resources
//}
// barrier: all ants
//} // end of iteration
}
void *does_work(void *ptr)
{
int pos = 0;
int antDist = 0;
int id = *((int *)ptr);
//std::vector<double> res;
std::vector<int> history;
std::vector<int> unvisited = Locations;
while(history.size() < problemSize)
{
//res.clear();
//for(int i =0;i < problemSize; i++)
//{
// res.push_back(0.0);
//}
double choice = ((double) rand() / (RAND_MAX)) + 1;
double choice2 = ((double) rand() / (RAND_MAX)) + 1;
double max = 0;
int maxIndex =0;
if(choice < Q0){
// expliait
for(int i =0; i< problemSize; i++)
{
if(std::find(history.begin(), history.end(), i) != history.end())
continue;
double temp = Pher[pos][i] / pow(Distance[pos][i], BETA) ;
if( temp > max)
{
max =temp;
maxIndex = i;
}
}
}
else //we expolore
{
std::vector<double> cho = eq2(Distance, Pher, unvisited, pos);
maxIndex = eq2_helper(cho,choice2);
max = Pher[pos][maxIndex] / pow(Distance[pos][maxIndex], BETA);
}
Pher[pos][maxIndex] = eq3(Pher[pos][maxIndex],problemSize);
antDist += Distance[pos][maxIndex];
pos = maxIndex;
history.push_back(maxIndex);
int temp = *(std::find(unvisited.begin(),unvisited.end(),maxIndex));
unvisited.erase(unvisited.begin() + temp);
}
results[id] = history;
wholeCost[id] = antDist;
}
<|endoftext|>
|
<commit_before>//
// Exponent.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Exponential.h"
Exponential::Exponential(Expression* base, Rational* exponent){
this->type = "exponential";
this->base = base;
this->exponent = exponent;
Integer *exde = (Integer *)exponent->getDenominator();
if (exde->getValue() != 1) {
base = nthRoot(exde, base);
exponent = exponent->getNumerator();
}
Integer *exnu = (Integer *)exponent->getNumerator();
if (canExponentiate()) {
this = exponentiate();
}
}
Exponential::~Exponential(){
}
bool Exponential::canExponentiate() {
if(base->type == "euler"){
return false;
}else if(base->type == "exponential"){
Exponential* ex = (exponential *) base;
this->exponent *= ex->getExponent();
ex->setExponent(1); // may need to be corrected because exponent is not an int
return false; // false is returned because the base itself would have already been exponentiated if it were possible
}else if(base->type == "integer"){
return true;
}else if(base->type == "logarithm"){
return false;
}else if(base->type == "nthRoot"){
nthRoot* nr = (nthRoot *) base;
Rational* r = new Rational(this->exponent, nr->getRoot());
this->exponent = r;
nr->setRoot()=1;
}else if(base->type == "pi"){
return false;
}else if(base->type == "rational"){
Rational* r = (rational *) base;
if (r->getNumerator->type == "integer" && r->getDenominator->type == "integer") {
Exponential* nu = new Exponential(r->getNumerator, this->exponent);
r->setNumerator(nu);
Exponential* de = new Exponential(r->getDenominator, this->exponent);
r->setDenominator(de);
}
}else{
cout << "type not recognized" << endl;
}
return false;
}
Expression* Exponential::exponentiate(){
Expression* toReturn = base;
Expression* constantBase = base;
if (this->exponent.getNumerator()==0) {
Integer* ret = new Integer(1);
return ret;
}
bool toFlip = false;
if (exnu<0) {
exnu*=-1;
toFlip = true;
}
Expression* e = this;
for (int i = 1; i < exnu); i++) {
toReturn*=constantBase;
}
exnu = 1;
if (toFlip()) {
Rational* r = new Rational(1, toReturn);
return r;
}
return toReturn;
}
Expression* Exponential::add(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (ex->getBase()==this->base) {
if (ex->getExponent()==this->exponent) {
this*=2;
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::subtract(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (ex->getBase()==this->base) {
if (ex->getExponent()==this->exponent) {
this*=0;
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::multiply(Expression* a){
/*Expression* c = this;
if (*a == *c) //might require overriding
{
exponent += a->getExponent;
}
return c;*/
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (this->base == ex->getBase()) {
this->exponent += ex->getExponent();
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
Rational* r = (Rational *) r;
r->setNumerator(r->getNumerator.multiply(this));
this = r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::divide(Expression* a){
/*Expression* c = this;
if (*a == *c) //might require overriding
{
c->getExponent -= a->getExponent;
}
return c;*/
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (this->base == ex->getBase()) {
this->exponent -= ex->getExponent();
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
Rational* r = (Rational *) r;
r->setDenominator(r->getDenominator.multiply(this));
this = r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Rational* Exponential::getExponent() {
return exponent;
}
Expression* Exponential::getBase() {
return base;
}
Integer* Exponential::getExnu() {
return exnu;
}
Integer* Exponential::getExde() {
return exde;
}
void Exponential::setExnu(Integer* n) {
exnu = n;
}
void Exponential::setExde(Integer* n) {
exde = n;
}
void Exponential::setExponent(Rational e) {
exponent = e;
}
void Exponential::setBase(*Expression e) {
base = e;
}
string Exponential::toString() {
string str = base + "^" + exponent;
return str;
}
ostream& Exponential::print(std::ostream& output) const{
output << this->base << this->exponent; //overload cout so that it makes sense
return output;
}
<commit_msg>Mostly done. Lmk if I need to do anything else<commit_after>//
// Exponent.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "Exponential.h"
Exponential::Exponential(Expression* base, Rational* exponent){
this->type = "exponential";
this->base = base;
this->exponent = exponent;
Integer *exde = (Integer *)exponent->getDenominator();
if (exde->getValue() != 1) {
base = nthRoot(exde, base);
exponent = exponent->getNumerator();
}
Integer *exnu = (Integer *)exponent->getNumerator();
if (canExponentiate()) {
this = exponentiate();
}
}
Exponential::~Exponential(){
}
bool Exponential::canExponentiate() {
if(base->type == "euler"){
return false;
}else if(base->type == "exponential"){
Exponential* ex = (exponential *) base;
this->exponent *= ex->getExponent();
Integer* numSum = new Integer (1);
ex->getExponent->setNumerator(numSum);
return false; // false is returned because the base itself would have already been exponentiated if it were possible
}else if(base->type == "integer"){
return true;
}else if(base->type == "logarithm"){
return false;
}else if(base->type == "nthRoot"){
nthRoot* nr = (nthRoot *) base;
Rational* r = new Rational(this->exponent, nr->getRoot());
this->exponent = r;
nr->setRoot()=1;
}else if(base->type == "pi"){
return false;
}else if(base->type == "rational"){
Rational* r = (rational *) base;
if (r->getNumerator->type == "integer" && r->getDenominator->type == "integer") {
Exponential* nu = new Exponential(r->getNumerator, this->exponent);
r->setNumerator(nu);
Exponential* de = new Exponential(r->getDenominator, this->exponent);
r->setDenominator(de);
}
}else{
cout << "type not recognized" << endl;
}
return false;
}
Expression* Exponential::exponentiate(){
Expression* toReturn = base;
Expression* constantBase = base;
if (this->exponent.getNumerator()==0) {
Integer* ret = new Integer(1);
return ret;
}
bool toFlip = false;
if (exnu<0) {
exnu*=-1;
toFlip = true;
}
Expression* e = this;
for (int i = 1; i < exnu); i++) {
toReturn*=constantBase;
}
exnu = 1;
if (toFlip()) {
Rational* r = new Rational(1, toReturn);
return r;
}
return toReturn;
}
Expression* Exponential::add(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (ex->getBase()==this->base) {
if (ex->getExponent()==this->exponent) {
this*=2;
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::subtract(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (ex->getBase()==this->base) {
if (ex->getExponent()==this->exponent) {
this*=0;
}
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::multiply(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (this->base == ex->getBase()) {
this->exponent += ex->getExponent();
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
Rational* r = (Rational *) r;
r->setNumerator(r->getNumerator.multiply(this));
this = r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Expression* Exponential::divide(Expression* a){
if(a->type == "euler"){
}else if(a->type == "exponential"){
Exponential* ex = (Exponential *) a;
if (this->base == ex->getBase()) {
this->exponent -= ex->getExponent();
}
}else if(a->type == "integer"){
}else if(a->type == "logarithm"){
}else if(a->type == "nthRoot"){
}else if(a->type == "pi"){
}else if(a->type == "rational"){
Rational* r = (Rational *) r;
r->setDenominator(r->getDenominator.multiply(this));
this = r;
}else{
cout << "type not recognized" << endl;
}
return this;
}
Rational* Exponential::getExponent() {
return exponent;
}
Expression* Exponential::getBase() {
return base;
}
Integer* Exponential::getExnu() {
return exnu;
}
Integer* Exponential::getExde() {
return exde;
}
void Exponential::setExnu(Integer* n) {
exnu = n;
}
void Exponential::setExde(Integer* n) {
exde = n;
}
void Exponential::setExponent(Rational e) {
exponent = e;
}
void Exponential::setBase(*Expression e) {
base = e;
}
string Exponential::toString() {
string str = base + "^" + exponent;
return str;
}
ostream& Exponential::print(std::ostream& output) const{
output << this->base << this->exponent; //overload cout so that it makes sense
return output;
}
<|endoftext|>
|
<commit_before>#include "FileWrapper.h"
#include "ThrowError.h"
#define _LARGEFILE64_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#if defined(_MSC_VER)
#define stat64 _stat64
#define status_t _stat64
#define fseek64 _fseeki64
#elif defined(__MINGW32__)
#define stat64 _stat64
#define status_t __stat64
#define fseek64 _fseeki64
#else
#include <unistd.h>
#define status_t stat64
#define fseek64 lseek64
#endif
namespace
{
const int64_t MaxFileSize = MAX_INPUT_FILE_SIZE * 1024LL * 1024LL * 1024LL;
} //namespace
namespace external_sort
{
FileWrapper::FileWrapper()
: m_file(nullptr)
, m_size(0)
{
m_file = std::tmpfile();
CHECK_CONTRACT(m_file, "Cannot create temporary file");
}
FileWrapper::FileWrapper(const char *fileName, bool input)
: m_file(nullptr)
, m_size(0)
{
static_assert(MAX_INPUT_FILE_SIZE > 0, "File size limit cannot be zero");
CHECK_CONTRACT(fileName && fileName[0], "File name is empty");
m_file = std::fopen(fileName, input ? "rb" : "wb");
CHECK_CONTRACT(m_file, std::string("Cannot open file ") + fileName);
if (input) {
struct status_t fileStat;
CHECK_CONTRACT(!stat64(fileName, &fileStat), std::string("Cannot get file size ") + fileName);
m_size = fileStat.st_size;
CHECK_CONTRACT(m_size > 0, std::string("Empty input file ") + fileName);
CHECK_CONTRACT(MaxFileSize >= m_size, std::string("Too large file ") + fileName);
}
}
FileWrapper::FileWrapper(FileWrapper&& tmp)
: m_file(tmp.m_file)
, m_size(tmp.m_size)
{
tmp.m_file = nullptr;
tmp.m_size = 0;
}
FileWrapper::~FileWrapper() {
Close();
}
size_t FileWrapper::Read(int64_t offset, char* const chunk, size_t chunkSize) const {
assert(chunk && chunkSize);
assert(m_file);
assert(offset >= 0);
if (!fseek64(m_file, offset, SEEK_SET)) {
const size_t bytes = std::fread(chunk, sizeof(char), chunkSize, m_file);
if (bytes)
return bytes;
}
CHECK_CONTRACT(std::feof(m_file), "Cannot read from file");
return 0;
}
void FileWrapper::Write(const RangeConstChar &range) const {
assert(m_file);
CHECK_CONTRACT(range.size() == std::fwrite(range.begin(), sizeof(char), range.size(), m_file), "Cannot write to file");
std::fputc('\n', m_file);
}
void FileWrapper::Close() {
if (m_file)
fclose(m_file);
m_file = nullptr;
}
int64_t FileWrapper::GetFileSize() const {
return m_size;
}
void FileWrapper::Rewind() const {
rewind(m_file);
}
FileWrapper::FileWrapper(const external_sort::FileWrapper &wrapper) {
assert(false && "FileWrapper disable copy constructor");
}
void FileWrapper::operator=(const external_sort::FileWrapper &wrapper) {
assert(false && "FileWrapper disable assign operator");
}
} // namespace
<commit_msg>-adopt lseek64 usage with FILE<commit_after>#include "FileWrapper.h"
#include "ThrowError.h"
#include <sys/types.h>
#include <sys/stat.h>
#if defined(_MSC_VER)
#define stat64 _stat64
#define status_t _stat64
#define fseek64 _fseeki64
#elif defined(__MINGW32__)
#define stat64 _stat64
#define status_t __stat64
#define fseek64 _fseeki64
#else
#include <unistd.h>
#define status_t stat64
#define fseek64(file,ofs,from) lseek64(file->_file, ofs, from)
#endif
namespace
{
const int64_t MaxFileSize = MAX_INPUT_FILE_SIZE * 1024LL * 1024LL * 1024LL;
} //namespace
namespace external_sort
{
FileWrapper::FileWrapper()
: m_file(nullptr)
, m_size(0)
{
m_file = std::tmpfile();
CHECK_CONTRACT(m_file, "Cannot create temporary file");
}
FileWrapper::FileWrapper(const char *fileName, bool input)
: m_file(nullptr)
, m_size(0)
{
static_assert(MAX_INPUT_FILE_SIZE > 0, "File size limit cannot be zero");
CHECK_CONTRACT(fileName && fileName[0], "File name is empty");
m_file = std::fopen(fileName, input ? "rb" : "wb");
CHECK_CONTRACT(m_file, std::string("Cannot open file ") + fileName);
if (input) {
struct status_t fileStat;
CHECK_CONTRACT(!stat64(fileName, &fileStat), std::string("Cannot get file size ") + fileName);
m_size = fileStat.st_size;
CHECK_CONTRACT(m_size > 0, std::string("Empty input file ") + fileName);
CHECK_CONTRACT(MaxFileSize >= m_size, std::string("Too large file ") + fileName);
}
}
FileWrapper::FileWrapper(FileWrapper&& tmp)
: m_file(tmp.m_file)
, m_size(tmp.m_size)
{
tmp.m_file = nullptr;
tmp.m_size = 0;
}
FileWrapper::~FileWrapper() {
Close();
}
size_t FileWrapper::Read(int64_t offset, char* const chunk, size_t chunkSize) const {
assert(chunk && chunkSize);
assert(m_file);
assert(offset >= 0);
if (!fseek64(m_file, offset, SEEK_SET)) {
const size_t bytes = std::fread(chunk, sizeof(char), chunkSize, m_file);
if (bytes)
return bytes;
}
CHECK_CONTRACT(std::feof(m_file), "Cannot read from file");
return 0;
}
void FileWrapper::Write(const RangeConstChar &range) const {
assert(m_file);
CHECK_CONTRACT(range.size() == std::fwrite(range.begin(), sizeof(char), range.size(), m_file), "Cannot write to file");
std::fputc('\n', m_file);
}
void FileWrapper::Close() {
if (m_file)
fclose(m_file);
m_file = nullptr;
}
int64_t FileWrapper::GetFileSize() const {
return m_size;
}
void FileWrapper::Rewind() const {
rewind(m_file);
}
FileWrapper::FileWrapper(const external_sort::FileWrapper &wrapper) {
assert(false && "FileWrapper disable copy constructor");
}
void FileWrapper::operator=(const external_sort::FileWrapper &wrapper) {
assert(false && "FileWrapper disable assign operator");
}
} // namespace
<|endoftext|>
|
<commit_before>/*===========================================================================*
* This file is part of the BiCePS Linear Integer Solver (BLIS). *
* *
* BLIS is distributed under the Common Public License as part of the *
* COIN-OR repository (http://www.coin-or.org). *
* *
* Authors: Yan Xu, SAS Institute Inc. *
* Ted Ralphs, Lehigh University *
* Laszlo Ladanyi, IBM T.J. Watson Research Center *
* Matthew Saltzman, Clemson University *
* *
* *
* Copyright (C) 2001-2006, Lehigh University, Yan Xu, and Ted Ralphs. *
* All Rights Reserved. *
*===========================================================================*/
#include "CoinHelperFunctions.hpp"
#include "CoinTime.hpp"
#include "BlisModel.h"
#include "BlisHeurRound.h"
//#############################################################################
// Copy constructor
BlisHeurRound::BlisHeurRound(const BlisHeurRound & rhs)
:
BlisHeuristic(rhs),
matrix_(rhs.matrix_),
matrixByRow_(rhs.matrixByRow_),
seed_(rhs.seed_)
{}
//#############################################################################
// Clone
BlisHeuristic *
BlisHeurRound::clone() const
{
return new BlisHeurRound(*this);
}
//#############################################################################
// update model
void BlisHeurRound::setModel(BlisModel * model)
{
model_ = model;
// Get a copy of original matrix (and by row for rounding);
assert(model_->solver());
matrix_ = *model_->solver()->getMatrixByCol();
matrixByRow_ = *model_->solver()->getMatrixByRow();
}
//#############################################################################
// See if rounding will give solution
// Sets value of solution
// Assumes rhs for original matrix still okay
// At present only works with integers
// Fix values if asked for
// Returns 1 if solution, 0 if not
int
BlisHeurRound::searchSolution(double & solutionValue, double * betterSolution)
{
int foundBetter = false;
if (strategy_ == BLIS_NONE) {
// This heuristic has been disabled.
return foundBetter;
}
//------------------------------------------------------
// Start to search solution ...
//------------------------------------------------------
double start = CoinCpuTime();
// Get a copy of original matrix (and by row for rounding);
matrix_ = *(model_->solver()->getMatrixByCol());
matrixByRow_ = *(model_->solver()->getMatrixByRow());
seed_ = 1;
OsiSolverInterface * solver = model_->solver();
const double * lower = solver->getColLower();
const double * upper = solver->getColUpper();
const double * rowLower = solver->getRowLower();
const double * rowUpper = solver->getRowUpper();
const double * solution = solver->getColSolution();
const double * objective = solver->getObjCoefficients();
double integerTolerance = 1.0e-5;
//model_->getDblParam(BlisModel::BlisIntegerTolerance);
double primalTolerance;
solver->getDblParam(OsiPrimalTolerance, primalTolerance);
int numberRows = matrix_.getNumRows();
int numberIntegers = model_->getNumIntObjects();
const int * integerVariable = model_->getIntColIndices();
int i;
double direction = solver->getObjSense();
double newSolutionValue = direction * solver->getObjValue();
// Column copy
const double * element = matrix_.getElements();
const int * row = matrix_.getIndices();
const int * columnStart = matrix_.getVectorStarts();
const int * columnLength = matrix_.getVectorLengths();
// Row copy
const double * elementByRow = matrixByRow_.getElements();
const int * column = matrixByRow_.getIndices();
const int * rowStart = matrixByRow_.getVectorStarts();
const int * rowLength = matrixByRow_.getVectorLengths();
// Get solution array for heuristic solution
int numberColumns = solver->getNumCols();
double * newSolution = new double [numberColumns];
memcpy(newSolution, solution, numberColumns * sizeof(double));
double * rowActivity = new double[numberRows];
memset(rowActivity, 0, numberRows*sizeof(double));
for (i = 0; i < numberColumns; i++) {
int j;
double value = newSolution[i];
if (value) {
for (j = columnStart[i];
j < columnStart[i] + columnLength[i]; j++) {
int iRow = row[j];
rowActivity[iRow] += value*element[j];
}
}
}
// check was feasible - if not adjust (cleaning may move)
for (i = 0; i < numberRows; i++) {
if(rowActivity[i] < rowLower[i]) {
//assert (rowActivity[i]>rowLower[i]-1000.0*primalTolerance);
rowActivity[i] = rowLower[i];
} else if(rowActivity[i] > rowUpper[i]) {
//assert (rowActivity[i]<rowUpper[i]+1000.0*primalTolerance);
rowActivity[i] = rowUpper[i];
}
}
for (i = 0; i < numberIntegers; i++) {
int iColumn = integerVariable[i];
double value = newSolution[iColumn];
if (fabs(floor(value + 0.5) - value) > integerTolerance) {
double below = floor(value);
double newValue = newSolution[iColumn];
double cost = direction * objective[iColumn];
double move;
if (cost > 0.0) {
// try up
move = 1.0 - (value - below);
} else if (cost < 0.0) {
// try down
move = below - value;
} else {
// won't be able to move unless we can grab another variable
// just for now go down
move = below-value;
}
newValue += move;
newSolution[iColumn] = newValue;
newSolutionValue += move * cost;
int j;
for (j = columnStart[iColumn];
j < columnStart[iColumn] + columnLength[iColumn]; j++) {
int iRow = row[j];
rowActivity[iRow] += move * element[j];
}
}
}
double penalty = 0.0;
// see if feasible
for (i = 0; i < numberRows; i++) {
double value = rowActivity[i];
double thisInfeasibility = 0.0;
if (value < rowLower[i] - primalTolerance)
thisInfeasibility = value - rowLower[i];
else if (value > rowUpper[i] + primalTolerance)
thisInfeasibility = value - rowUpper[i];
if (thisInfeasibility) {
// See if there are any slacks I can use to fix up
// maybe put in coding for multiple slacks?
double bestCost = 1.0e50;
int k;
int iBest = -1;
double addCost = 0.0;
double newValue = 0.0;
double changeRowActivity = 0.0;
double absInfeasibility = fabs(thisInfeasibility);
for (k = rowStart[i]; k < rowStart[i] + rowLength[i]; k++) {
int iColumn = column[k];
if (columnLength[iColumn] == 1) {
double currentValue = newSolution[iColumn];
double elementValue = elementByRow[k];
double lowerValue = lower[iColumn];
double upperValue = upper[iColumn];
double gap = rowUpper[i] - rowLower[i];
double absElement = fabs(elementValue);
if (thisInfeasibility * elementValue > 0.0) {
// we want to reduce
if ((currentValue - lowerValue) * absElement >=
absInfeasibility) {
// possible - check if integer
double distance = absInfeasibility / absElement;
double thisCost =
-direction * objective[iColumn] * distance;
if (solver->isInteger(iColumn)) {
distance = ceil(distance - primalTolerance);
assert (currentValue - distance >=
lowerValue - primalTolerance);
if (absInfeasibility - distance * absElement
< -gap - primalTolerance)
thisCost = 1.0e100; // no good
else
thisCost =
-direction*objective[iColumn]*distance;
}
if (thisCost < bestCost) {
bestCost = thisCost;
iBest = iColumn;
addCost = thisCost;
newValue = currentValue - distance;
changeRowActivity = -distance * elementValue;
}
}
} else {
// we want to increase
if ((upperValue - currentValue) * absElement >=
absInfeasibility) {
// possible - check if integer
double distance = absInfeasibility / absElement;
double thisCost =
direction * objective[iColumn] * distance;
if (solver->isInteger(iColumn)) {
distance = ceil(distance - 1.0e-7);
assert (currentValue - distance <=
upperValue + primalTolerance);
if (absInfeasibility - distance * absElement
< -gap - primalTolerance)
thisCost = 1.0e100; // no good
else
thisCost =
direction*objective[iColumn]*distance;
}
if (thisCost < bestCost) {
bestCost = thisCost;
iBest = iColumn;
addCost = thisCost;
newValue = currentValue + distance;
changeRowActivity = distance * elementValue;
}
}
}
}
}
if (iBest >= 0) {
/*printf("Infeasibility of %g on row %d cost %g\n",
thisInfeasibility,i,addCost);*/
newSolution[iBest] = newValue;
thisInfeasibility = 0.0;
newSolutionValue += addCost;
rowActivity[i] += changeRowActivity;
}
penalty += fabs(thisInfeasibility);
}
}
// Could also set SOS (using random) and repeat
if (!penalty) {
// Got a feasible solution. Try to improve.
//seed_++;
//CoinSeedRandom(seed_);
// Random number between 0 and 1.
double randomNumber = CoinDrand48();
int iPass;
int start[2];
int end[2];
int iRandom = (int) (randomNumber * ((double) numberIntegers));
start[0] = iRandom;
end[0] = numberIntegers;
start[1] = 0;
end[1] = iRandom;
for (iPass = 0; iPass < 2; iPass++) {
int i;
for (i = start[iPass]; i < end[iPass]; i++) {
int iColumn = integerVariable[i];
#ifdef BLIS_DEBUG
double value = newSolution[iColumn];
assert(fabs(floor(value + 0.5) - value) < integerTolerance);
#endif
double cost = direction * objective[iColumn];
double move = 0.0;
if (cost > 0.0)
move = -1.0;
else if (cost < 0.0)
move = 1.0;
while (move) {
bool good = true;
double newValue = newSolution[iColumn] + move;
if (newValue < lower[iColumn] - primalTolerance||
newValue > upper[iColumn] + primalTolerance) {
move = 0.0;
} else {
// see if we can move
int j;
for (j = columnStart[iColumn];
j < columnStart[iColumn] + columnLength[iColumn];
j++) {
int iRow = row[j];
double newActivity =
rowActivity[iRow] + move*element[j];
if (newActivity < rowLower[iRow] - primalTolerance
||
newActivity > rowUpper[iRow]+primalTolerance) {
good = false;
break;
}
}
if (good) {
newSolution[iColumn] = newValue;
newSolutionValue += move * cost;
int j;
for (j = columnStart[iColumn];
j < columnStart[iColumn] +
columnLength[iColumn]; j++) {
int iRow = row[j];
rowActivity[iRow] += move*element[j];
}
} else {
move=0.0;
}
}
}
}
}
if (newSolutionValue < solutionValue) {
// paranoid check
memset(rowActivity, 0, numberRows * sizeof(double));
for (i = 0; i < numberColumns; i++) {
int j;
double value = newSolution[i];
if (value) {
for (j = columnStart[i];
j < columnStart[i] + columnLength[i]; j++) {
int iRow = row[j];
rowActivity[iRow] += value * element[j];
}
}
}
// check was approximately feasible
bool feasible = true;
for (i = 0; i < numberRows; i++) {
if(rowActivity[i] < rowLower[i]) {
if (rowActivity[i] < rowLower[i] - 1000.0*primalTolerance)
feasible = false;
} else if(rowActivity[i] > rowUpper[i]) {
if (rowActivity[i] > rowUpper[i] + 1000.0*primalTolerance)
feasible = false;
}
}
if (feasible) {
// new solution
memcpy(betterSolution, newSolution,
numberColumns * sizeof(double));
solutionValue = newSolutionValue;
//printf("** Solution of %g found by rounding\n",newSolutionValue);
foundBetter = true;
} else {
// Can easily happen
//printf("Debug BlisHeurRound giving bad solution\n");
}
}
}
delete [] newSolution;
delete [] rowActivity;
//------------------------------------------------------
// Update statistics.
//------------------------------------------------------
++calls_;
if (foundBetter) ++numSolutions_;
time_ += (CoinCpuTime() - start);
if (noSolsCalls_ > BLIS_HEUR_ROUND_DISABLE) {
if (strategy_ == BLIS_AUTO) {
strategy_ = BLIS_NONE;
}
}
return foundBetter;
}
//#############################################################################
<commit_msg>adjust strategy, clean up<commit_after>/*===========================================================================*
* This file is part of the BiCePS Linear Integer Solver (BLIS). *
* *
* BLIS is distributed under the Common Public License as part of the *
* COIN-OR repository (http://www.coin-or.org). *
* *
* Authors: Yan Xu, SAS Institute Inc. *
* Ted Ralphs, Lehigh University *
* Laszlo Ladanyi, IBM T.J. Watson Research Center *
* Matthew Saltzman, Clemson University *
* *
* *
* Copyright (C) 2001-2006, Lehigh University, Yan Xu, and Ted Ralphs. *
* All Rights Reserved. *
*===========================================================================*/
#include "CoinHelperFunctions.hpp"
#include "CoinTime.hpp"
#include "BlisModel.h"
#include "BlisHeurRound.h"
//#############################################################################
// Copy constructor
BlisHeurRound::BlisHeurRound(const BlisHeurRound & rhs)
:
BlisHeuristic(rhs),
matrix_(rhs.matrix_),
matrixByRow_(rhs.matrixByRow_),
seed_(rhs.seed_)
{}
//#############################################################################
// Clone
BlisHeuristic *
BlisHeurRound::clone() const
{
return new BlisHeurRound(*this);
}
//#############################################################################
// update model
void BlisHeurRound::setModel(BlisModel * model)
{
model_ = model;
// Get a copy of original matrix (and by row for rounding);
assert(model_->solver());
matrix_ = *model_->solver()->getMatrixByCol();
matrixByRow_ = *model_->solver()->getMatrixByRow();
}
//#############################################################################
// See if rounding will give solution
// Sets value of solution
// Assumes rhs for original matrix still okay
// At present only works with integers
// Fix values if asked for
// Returns 1 if solution, 0 if not
int
BlisHeurRound::searchSolution(double & solutionValue, double * betterSolution)
{
int foundBetter = false;
if (strategy_ == BLIS_NONE) {
// This heuristic has been disabled.
return foundBetter;
}
//------------------------------------------------------
// Start to search solution ...
//------------------------------------------------------
double start = CoinCpuTime();
// Get a copy of original matrix (and by row for rounding);
matrix_ = *(model_->solver()->getMatrixByCol());
matrixByRow_ = *(model_->solver()->getMatrixByRow());
seed_ = 1;
OsiSolverInterface * solver = model_->solver();
const double * lower = solver->getColLower();
const double * upper = solver->getColUpper();
const double * rowLower = solver->getRowLower();
const double * rowUpper = solver->getRowUpper();
const double * solution = solver->getColSolution();
const double * objective = solver->getObjCoefficients();
double integerTolerance = 1.0e-5;
//model_->getDblParam(BlisModel::BlisIntegerTolerance);
double primalTolerance;
solver->getDblParam(OsiPrimalTolerance, primalTolerance);
int numberRows = matrix_.getNumRows();
int numberIntegers = model_->getNumIntObjects();
const int * integerVariable = model_->getIntColIndices();
int i;
double direction = solver->getObjSense();
double newSolutionValue = direction * solver->getObjValue();
// Column copy
const double * element = matrix_.getElements();
const int * row = matrix_.getIndices();
const int * columnStart = matrix_.getVectorStarts();
const int * columnLength = matrix_.getVectorLengths();
// Row copy
const double * elementByRow = matrixByRow_.getElements();
const int * column = matrixByRow_.getIndices();
const int * rowStart = matrixByRow_.getVectorStarts();
const int * rowLength = matrixByRow_.getVectorLengths();
// Get solution array for heuristic solution
int numberColumns = solver->getNumCols();
double * newSolution = new double [numberColumns];
memcpy(newSolution, solution, numberColumns * sizeof(double));
double * rowActivity = new double[numberRows];
memset(rowActivity, 0, numberRows*sizeof(double));
for (i = 0; i < numberColumns; i++) {
int j;
double value = newSolution[i];
if (value) {
for (j = columnStart[i];
j < columnStart[i] + columnLength[i]; j++) {
int iRow = row[j];
rowActivity[iRow] += value*element[j];
}
}
}
// check was feasible - if not adjust (cleaning may move)
for (i = 0; i < numberRows; i++) {
if(rowActivity[i] < rowLower[i]) {
//assert (rowActivity[i]>rowLower[i]-1000.0*primalTolerance);
rowActivity[i] = rowLower[i];
} else if(rowActivity[i] > rowUpper[i]) {
//assert (rowActivity[i]<rowUpper[i]+1000.0*primalTolerance);
rowActivity[i] = rowUpper[i];
}
}
for (i = 0; i < numberIntegers; i++) {
int iColumn = integerVariable[i];
double value = newSolution[iColumn];
if (fabs(floor(value + 0.5) - value) > integerTolerance) {
double below = floor(value);
double newValue = newSolution[iColumn];
double cost = direction * objective[iColumn];
double move;
if (cost > 0.0) {
// try up
move = 1.0 - (value - below);
} else if (cost < 0.0) {
// try down
move = below - value;
} else {
// won't be able to move unless we can grab another variable
// just for now go down
move = below-value;
}
newValue += move;
newSolution[iColumn] = newValue;
newSolutionValue += move * cost;
int j;
for (j = columnStart[iColumn];
j < columnStart[iColumn] + columnLength[iColumn]; j++) {
int iRow = row[j];
rowActivity[iRow] += move * element[j];
}
}
}
double penalty = 0.0;
// see if feasible
for (i = 0; i < numberRows; i++) {
double value = rowActivity[i];
double thisInfeasibility = 0.0;
if (value < rowLower[i] - primalTolerance)
thisInfeasibility = value - rowLower[i];
else if (value > rowUpper[i] + primalTolerance)
thisInfeasibility = value - rowUpper[i];
if (thisInfeasibility) {
// See if there are any slacks I can use to fix up
// maybe put in coding for multiple slacks?
double bestCost = 1.0e50;
int k;
int iBest = -1;
double addCost = 0.0;
double newValue = 0.0;
double changeRowActivity = 0.0;
double absInfeasibility = fabs(thisInfeasibility);
for (k = rowStart[i]; k < rowStart[i] + rowLength[i]; k++) {
int iColumn = column[k];
if (columnLength[iColumn] == 1) {
double currentValue = newSolution[iColumn];
double elementValue = elementByRow[k];
double lowerValue = lower[iColumn];
double upperValue = upper[iColumn];
double gap = rowUpper[i] - rowLower[i];
double absElement = fabs(elementValue);
if (thisInfeasibility * elementValue > 0.0) {
// we want to reduce
if ((currentValue - lowerValue) * absElement >=
absInfeasibility) {
// possible - check if integer
double distance = absInfeasibility / absElement;
double thisCost =
-direction * objective[iColumn] * distance;
if (solver->isInteger(iColumn)) {
distance = ceil(distance - primalTolerance);
assert (currentValue - distance >=
lowerValue - primalTolerance);
if (absInfeasibility - distance * absElement
< -gap - primalTolerance)
thisCost = 1.0e100; // no good
else
thisCost =
-direction*objective[iColumn]*distance;
}
if (thisCost < bestCost) {
bestCost = thisCost;
iBest = iColumn;
addCost = thisCost;
newValue = currentValue - distance;
changeRowActivity = -distance * elementValue;
}
}
} else {
// we want to increase
if ((upperValue - currentValue) * absElement >=
absInfeasibility) {
// possible - check if integer
double distance = absInfeasibility / absElement;
double thisCost =
direction * objective[iColumn] * distance;
if (solver->isInteger(iColumn)) {
distance = ceil(distance - 1.0e-7);
assert (currentValue - distance <=
upperValue + primalTolerance);
if (absInfeasibility - distance * absElement
< -gap - primalTolerance)
thisCost = 1.0e100; // no good
else
thisCost =
direction*objective[iColumn]*distance;
}
if (thisCost < bestCost) {
bestCost = thisCost;
iBest = iColumn;
addCost = thisCost;
newValue = currentValue + distance;
changeRowActivity = distance * elementValue;
}
}
}
}
}
if (iBest >= 0) {
/*printf("Infeasibility of %g on row %d cost %g\n",
thisInfeasibility,i,addCost);*/
newSolution[iBest] = newValue;
thisInfeasibility = 0.0;
newSolutionValue += addCost;
rowActivity[i] += changeRowActivity;
}
penalty += fabs(thisInfeasibility);
}
}
// Could also set SOS (using random) and repeat
if (!penalty) {
// Got a feasible solution. Try to improve.
//seed_++;
//CoinSeedRandom(seed_);
// Random number between 0 and 1.
double randomNumber = CoinDrand48();
int iPass;
int start[2];
int end[2];
int iRandom = (int) (randomNumber * ((double) numberIntegers));
start[0] = iRandom;
end[0] = numberIntegers;
start[1] = 0;
end[1] = iRandom;
for (iPass = 0; iPass < 2; iPass++) {
int i;
for (i = start[iPass]; i < end[iPass]; i++) {
int iColumn = integerVariable[i];
#ifdef BLIS_DEBUG
double value = newSolution[iColumn];
assert(fabs(floor(value + 0.5) - value) < integerTolerance);
#endif
double cost = direction * objective[iColumn];
double move = 0.0;
if (cost > 0.0)
move = -1.0;
else if (cost < 0.0)
move = 1.0;
while (move) {
bool good = true;
double newValue = newSolution[iColumn] + move;
if (newValue < lower[iColumn] - primalTolerance||
newValue > upper[iColumn] + primalTolerance) {
move = 0.0;
} else {
// see if we can move
int j;
for (j = columnStart[iColumn];
j < columnStart[iColumn] + columnLength[iColumn];
j++) {
int iRow = row[j];
double newActivity =
rowActivity[iRow] + move*element[j];
if (newActivity < rowLower[iRow] - primalTolerance
||
newActivity > rowUpper[iRow]+primalTolerance) {
good = false;
break;
}
}
if (good) {
newSolution[iColumn] = newValue;
newSolutionValue += move * cost;
int j;
for (j = columnStart[iColumn];
j < columnStart[iColumn] +
columnLength[iColumn]; j++) {
int iRow = row[j];
rowActivity[iRow] += move*element[j];
}
} else {
move=0.0;
}
}
}
}
}
if (newSolutionValue < solutionValue) {
// paranoid check
memset(rowActivity, 0, numberRows * sizeof(double));
for (i = 0; i < numberColumns; i++) {
int j;
double value = newSolution[i];
if (value) {
for (j = columnStart[i];
j < columnStart[i] + columnLength[i]; j++) {
int iRow = row[j];
rowActivity[iRow] += value * element[j];
}
}
}
// check was approximately feasible
bool feasible = true;
for (i = 0; i < numberRows; i++) {
if(rowActivity[i] < rowLower[i]) {
if (rowActivity[i] < rowLower[i] - 1000.0*primalTolerance)
feasible = false;
} else if(rowActivity[i] > rowUpper[i]) {
if (rowActivity[i] > rowUpper[i] + 1000.0*primalTolerance)
feasible = false;
}
}
if (feasible) {
// new solution
memcpy(betterSolution, newSolution,
numberColumns * sizeof(double));
solutionValue = newSolutionValue;
//printf("** Solution of %g found by rounding\n",newSolutionValue);
foundBetter = true;
} else {
// Can easily happen
//printf("Debug BlisHeurRound giving bad solution\n");
}
}
}
delete [] newSolution;
delete [] rowActivity;
//------------------------------------------------------
// Adjust strategy
//------------------------------------------------------
// Let Blis do this, 12/17/06
//++calls_;
//if (foundBetter) ++numSolutions_;
//time_ += (CoinCpuTime() - start);
if (noSolsCalls_ > BLIS_HEUR_ROUND_DISABLE) {
if (strategy_ == BLIS_AUTO) {
strategy_ = BLIS_NONE;
}
}
return foundBetter;
}
//#############################################################################
<|endoftext|>
|
<commit_before>
// g++ -std=c++11 -DSTANDALONE_TEST -L/opt/local/lib chebyshev_cl.cpp -lOpenCL -lboost_system
//#include <cstdlib>
#include "chebyshev_cl.hpp"
// Print elements of vector to stdout
template<class T>
void printvector(const T &v){
for(int i=0;i<v.size();++i) {
std::cout << v[i] << std::endl;
}
std::cout << std::endl;
}
Chebyshev::Chebyshev(int n)
: N(n), M(2 * N - 2),
ctx(
vex::Filter::Type(CL_DEVICE_TYPE_GPU) &&
vex::Filter::DoublePrecision &&
vex::Filter::Count(1)
),
fft(ctx, M), ifft(ctx, M, vex::fft::inverse),
cplx_ifft(ctx, M, vex::fft::inverse),
sum(ctx),
slice(vex::extents[M]),
X2(ctx, M),
w0(ctx, N),
wi(ctx, N-2),
wN(ctx, N)
{
dev_dvec k2(ctx, N);
auto i = vex::tag<1>(vex::element_index());
k2 = 2 * i * i;
// 2,8,18,...,2*(N-2)^2,(N-1)^2
k2[N - 1] = (N - 1) * (N - 1);
coeff_to_nodal(k2,w0);
w0 = w0 / (N - 1);
w0[0] = 0.5 * w0[0];
w0[N - 1] = 0.5 * w0[N - 1];
wN = -vex::permutation(N - 1 - i)(w0);
wi = 1 / ( sin(vex::constants::pi() * (i + 1) / (N - 1)) );
}
std::string Chebyshev::get_device_name() {
std::ostringstream os;
// Write device name to output string stream
os << ctx.queue(0);
// extract string
std::string devName = os.str();
return devName;
}
void Chebyshev::catrev(const dev_dvec &a, dev_dvec &A2) {
// First half of A2 holds a:
slice[vex::range(0,N)](A2) = a;
// Second half of A2 holds reversed copy of a (with endpoints removed):
slice[vex::range(N, M)](A2) = vex::permutation( N - 2 - vex::element_index() )(A2);
}
host_dvec Chebyshev::coeff_to_nodal(const host_dvec &a) {
dev_dvec A(ctx, a);
dev_dvec B(ctx, N);
host_dvec b(N);
coeff_to_nodal(A,B);
vex::copy(B,b);
return b;
}
void Chebyshev::coeff_to_nodal(const dev_dvec &a, dev_dvec &b) {
catrev(a,X2);
X2[0] = 2 * a[0];
X2[N-1] = 2 * a[N-1];
X2 = fft(X2) / 2;
b = slice[vex::range(0,N)](X2);
}
// Compute Chebyshev expansion coefficient from grid values
void Chebyshev::nodal_to_coeff(const dev_dvec &b, dev_dvec &a){
catrev(b, X2);
X2 = ifft(X2) * 2;
a = slice[vex::range(0,N)](X2);
a[0] = 0.5*a[0];
a[N-1] = 0.5*a[N-1];
}
host_dvec Chebyshev::nodal_to_coeff(const host_dvec &b) {
dev_dvec B(ctx, b);
dev_dvec A(ctx,N);
host_dvec a(N);
nodal_to_coeff(B,A);
vex::copy(A,a);
return a;
}
// Differentiate a function on the grid
void Chebyshev::nodal_diff(const dev_dvec &u, dev_dvec &v){
catrev(u,X2);
// 0,1,...,N-1,-(N-2),...,-1
VEX_FUNCTION(double, kkrev, (ptrdiff_t, N)(ptrdiff_t, i),
if (i < N) return i;
return -2 * N + i + 2;
);
X2 = fft(X2) * kkrev(N, vex::element_index());
X2[N-1] = 0;
// Extract imaginary part of vector
VEX_FUNCTION(double, imag, (cl_double2, c),
return c.y;
);
X2 = imag(cplx_ifft(X2));
v[0] = sum(u*w0);
slice[vex::range(1,N-1)](v) = slice[vex::range(1,N-1)](X2) * wi;
v[N-1] = sum(wN*u);
}
host_dvec Chebyshev::nodal_diff(const host_dvec &u) {
dev_dvec U(ctx, u);
dev_dvec V(ctx, N);
host_dvec v(N);
nodal_diff(U,V);
vex::copy(V,v);
return v;
}
void Chebyshev::coeff_int(const dev_dvec &v, dev_dvec &u) {
u[0] = 0;
slice[vex::range(1,N)](u) = slice[vex::range(0,N-1)](v);
slice[vex::range(1,N-1)](u) = slice[vex::range(1,N-1)](u) -
slice[vex::range(2,N)](v);
u[1] = u[1] + 0.5*v[2];
VEX_FUNCTION(double, frac, (ptrdiff_t, i),
if (i < 2) return i;
return 1.0/(2*i);
);
u = u*frac(vex::element_index());
}
#ifdef STANDALONE_TEST
int main(int argc, char* argv[]) {
int N = argc > 1 ? atoi(argv[1]) : 16;
int k = argc > 2 ? atoi(argv[2]) : 0;
try {
Chebyshev cheb(N);
std::cout << cheb.get_device_name() << std::endl;
host_dvec a(N,0);
a[k] = 1;
// auto b = cheb.coeff_to_nodal(a);
// auto bx = cheb.nodal_diff(b);
// auto c = cheb.nodal_to_coeff(bx);
// printvector(b);
// printvector(bx);
dev_dvec A(a);
dev_dvec B(N);
cheb.coeff_int(A,B);
printvector(B);
} catch (const cl::Error &e) {
std::cerr << "OpenCL error: " << e << std::endl;
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
#endif
<commit_msg>Chebyshev::coeff_int optimization<commit_after>
// g++ -std=c++11 -DSTANDALONE_TEST -L/opt/local/lib chebyshev_cl.cpp -lOpenCL -lboost_system
//#include <cstdlib>
#include "chebyshev_cl.hpp"
// Print elements of vector to stdout
template<class T>
void printvector(const T &v){
for(int i=0;i<v.size();++i) {
std::cout << v[i] << std::endl;
}
std::cout << std::endl;
}
Chebyshev::Chebyshev(int n)
: N(n), M(2 * N - 2),
ctx(
vex::Filter::Type(CL_DEVICE_TYPE_GPU) &&
vex::Filter::DoublePrecision &&
vex::Filter::Count(1)
),
fft(ctx, M), ifft(ctx, M, vex::fft::inverse),
cplx_ifft(ctx, M, vex::fft::inverse),
sum(ctx),
slice(vex::extents[M]),
X2(ctx, M),
w0(ctx, N),
wi(ctx, N-2),
wN(ctx, N)
{
dev_dvec k2(ctx, N);
auto i = vex::tag<1>(vex::element_index());
k2 = 2 * i * i;
// 2,8,18,...,2*(N-2)^2,(N-1)^2
k2[N - 1] = (N - 1) * (N - 1);
coeff_to_nodal(k2,w0);
w0 = w0 / (N - 1);
w0[0] = 0.5 * w0[0];
w0[N - 1] = 0.5 * w0[N - 1];
wN = -vex::permutation(N - 1 - i)(w0);
wi = 1 / ( sin(vex::constants::pi() * (i + 1) / (N - 1)) );
}
std::string Chebyshev::get_device_name() {
std::ostringstream os;
// Write device name to output string stream
os << ctx.queue(0);
// extract string
std::string devName = os.str();
return devName;
}
void Chebyshev::catrev(const dev_dvec &a, dev_dvec &A2) {
// First half of A2 holds a:
slice[vex::range(0,N)](A2) = a;
// Second half of A2 holds reversed copy of a (with endpoints removed):
slice[vex::range(N, M)](A2) = vex::permutation( N - 2 - vex::element_index() )(A2);
}
host_dvec Chebyshev::coeff_to_nodal(const host_dvec &a) {
dev_dvec A(ctx, a);
dev_dvec B(ctx, N);
host_dvec b(N);
coeff_to_nodal(A,B);
vex::copy(B,b);
return b;
}
void Chebyshev::coeff_to_nodal(const dev_dvec &a, dev_dvec &b) {
catrev(a,X2);
X2[0] = 2 * a[0];
X2[N-1] = 2 * a[N-1];
X2 = fft(X2) / 2;
b = slice[vex::range(0,N)](X2);
}
// Compute Chebyshev expansion coefficient from grid values
void Chebyshev::nodal_to_coeff(const dev_dvec &b, dev_dvec &a){
catrev(b, X2);
X2 = ifft(X2) * 2;
a = slice[vex::range(0,N)](X2);
a[0] = 0.5*a[0];
a[N-1] = 0.5*a[N-1];
}
host_dvec Chebyshev::nodal_to_coeff(const host_dvec &b) {
dev_dvec B(ctx, b);
dev_dvec A(ctx,N);
host_dvec a(N);
nodal_to_coeff(B,A);
vex::copy(A,a);
return a;
}
// Differentiate a function on the grid
void Chebyshev::nodal_diff(const dev_dvec &u, dev_dvec &v){
catrev(u,X2);
// 0,1,...,N-1,-(N-2),...,-1
VEX_FUNCTION(double, kkrev, (ptrdiff_t, N)(ptrdiff_t, i),
if (i < N) return i;
return -2 * N + i + 2;
);
X2 = fft(X2) * kkrev(N, vex::element_index());
X2[N-1] = 0;
// Extract imaginary part of vector
VEX_FUNCTION(double, imag, (cl_double2, c),
return c.y;
);
X2 = imag(cplx_ifft(X2));
v[0] = sum(u*w0);
slice[vex::range(1,N-1)](v) = slice[vex::range(1,N-1)](X2) * wi;
v[N-1] = sum(wN*u);
}
host_dvec Chebyshev::nodal_diff(const host_dvec &u) {
dev_dvec U(ctx, u);
dev_dvec V(ctx, N);
host_dvec v(N);
nodal_diff(U,V);
vex::copy(V,v);
return v;
}
void Chebyshev::coeff_int(const dev_dvec &v, dev_dvec &u) {
VEX_FUNCTION(double, scaled_diff, (size_t, N)(size_t, i)(const double*, v),
if (i == 0) {
return 0;
} else if (i == 1) {
return v[0] - 0.5 * v[2];
} else if (i + 1 >= N){
return 0.5 * v[i - 1] / i;
} else {
return 0.5 * (v[i - 1] - v[i + 1]) / i;
}
);
u = scaled_diff(N, vex::element_index(), vex::raw_pointer(v));
}
#ifdef STANDALONE_TEST
int main(int argc, char* argv[]) {
int N = argc > 1 ? atoi(argv[1]) : 16;
int k = argc > 2 ? atoi(argv[2]) : 0;
try {
Chebyshev cheb(N);
std::cout << cheb.get_device_name() << std::endl;
host_dvec a(N,0);
a[k] = 1;
// auto b = cheb.coeff_to_nodal(a);
// auto bx = cheb.nodal_diff(b);
// auto c = cheb.nodal_to_coeff(bx);
// printvector(b);
// printvector(bx);
dev_dvec A(a);
dev_dvec B(N);
cheb.coeff_int(A,B);
printvector(B);
} catch (const cl::Error &e) {
std::cerr << "OpenCL error: " << e << std::endl;
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
#endif
<|endoftext|>
|
<commit_before>#include "process.hpp"
#include <cstring>
#include <TlHelp32.h>
#include <stdexcept>
Process::Data::Data(): id(0), handle(NULL) {}
//Based on the discussion thread: https://www.reddit.com/r/cpp/comments/3vpjqg/a_new_platform_independent_process_library_for_c11/cxq1wsj
std::mutex create_process_mutex;
//Based on the example at https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx.
Process::id_type Process::open(const std::string &command, const std::string &path) {
if(open_stdin)
stdin_fd=std::unique_ptr<fd_type>(new fd_type);
if(read_stdout)
stdout_fd=std::unique_ptr<fd_type>(new fd_type);
if(read_stderr)
stderr_fd=std::unique_ptr<fd_type>(new fd_type);
HANDLE stdin_rd_p = NULL;
HANDLE stdin_wr_p = NULL;
HANDLE stdout_rd_p = NULL;
HANDLE stdout_wr_p = NULL;
HANDLE stderr_rd_p = NULL;
HANDLE stderr_wr_p = NULL;
SECURITY_ATTRIBUTES security_attributes;
security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
security_attributes.bInheritHandle = TRUE;
security_attributes.lpSecurityDescriptor = NULL;
std::lock_guard<std::mutex> lock(create_process_mutex);
if(stdin_fd) {
if (!CreatePipe(&stdin_rd_p, &stdin_wr_p, &security_attributes, 0)) {
return 0;
}
if(!SetHandleInformation(stdin_wr_p, HANDLE_FLAG_INHERIT, 0)) {
CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);
return 0;
}
}
if(stdout_fd) {
if (!CreatePipe(&stdout_rd_p, &stdout_wr_p, &security_attributes, 0)) {
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
return 0;
}
if(!SetHandleInformation(stdout_rd_p, HANDLE_FLAG_INHERIT, 0)) {
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
CloseHandle(stdout_rd_p);CloseHandle(stdout_wr_p);
return 0;
}
}
if(stderr_fd) {
if (!CreatePipe(&stderr_rd_p, &stderr_wr_p, &security_attributes, 0)) {
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
if(stdout_fd) {CloseHandle(stdout_rd_p);CloseHandle(stdout_wr_p);}
return 0;
}
if(!SetHandleInformation(stderr_rd_p, HANDLE_FLAG_INHERIT, 0)) {
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
if(stdout_fd) {CloseHandle(stdout_rd_p);CloseHandle(stdout_wr_p);}
CloseHandle(stderr_rd_p);CloseHandle(stderr_wr_p);
return 0;
}
}
PROCESS_INFORMATION process_info;
STARTUPINFO startup_info;
ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION));
ZeroMemory(&startup_info, sizeof(STARTUPINFO));
startup_info.cb = sizeof(STARTUPINFO);
startup_info.hStdInput = stdin_fd?stdin_rd_p:INVALID_HANDLE_VALUE;
startup_info.hStdOutput = stdout_fd?stdout_wr_p:INVALID_HANDLE_VALUE;
startup_info.hStdError = stderr_fd?stderr_wr_p:INVALID_HANDLE_VALUE;
if(stdin_fd || stdout_fd || stderr_fd)
startup_info.dwFlags |= STARTF_USESTDHANDLES;
char* path_cstr;
if(path=="")
path_cstr=NULL;
else {
path_cstr=new char[path.size()+1];
std::strcpy(path_cstr, path.c_str());
}
char* command_cstr;
#ifdef MSYS_PROCESS_USE_SH
size_t pos=0;
std::string sh_command=command;
while((pos=sh_command.find('\\', pos))!=std::string::npos) {
sh_command.replace(pos, 1, "\\\\\\\\");
pos+=4;
}
pos=0;
while((pos=sh_command.find('\"', pos))!=std::string::npos) {
sh_command.replace(pos, 1, "\\\"");
pos+=2;
}
sh_command.insert(0, "sh -c \"");
sh_command+="\"";
command_cstr=new char[sh_command.size()+1];
std::strcpy(command_cstr, sh_command.c_str());
#else
command_cstr=new char[command.size()+1];
std::strcpy(command_cstr, command.c_str());
#endif
BOOL bSuccess = CreateProcess(NULL, command_cstr, NULL, NULL, TRUE, 0,
NULL, path_cstr, &startup_info, &process_info);
delete[] path_cstr;
delete[] command_cstr;
if(!bSuccess) {
CloseHandle(process_info.hProcess);
CloseHandle(process_info.hThread);
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
if(stdout_fd) {CloseHandle(stdout_rd_p);CloseHandle(stdout_wr_p);}
if(stderr_fd) {CloseHandle(stderr_rd_p);CloseHandle(stderr_wr_p);}
return 0;
}
else {
CloseHandle(process_info.hThread);
if(stdin_fd) CloseHandle(stdin_rd_p);
if(stdout_fd) CloseHandle(stdout_wr_p);
if(stderr_fd) CloseHandle(stderr_wr_p);
}
if(stdin_fd) *stdin_fd=stdin_wr_p;
if(stdout_fd) *stdout_fd=stdout_rd_p;
if(stderr_fd) *stderr_fd=stderr_rd_p;
closed=false;
data.id=process_info.dwProcessId;
data.handle=process_info.hProcess;
return process_info.dwProcessId;
}
void Process::async_read() {
if(data.id==0)
return;
if(stdout_fd) {
stdout_thread=std::thread([this](){
DWORD n;
std::unique_ptr<char[]> buffer(new char[buffer_size]);
for (;;) {
BOOL bSuccess = ReadFile(*stdout_fd, static_cast<CHAR*>(buffer.get()), static_cast<DWORD>(buffer_size), &n, NULL);
if(!bSuccess || n == 0)
break;
read_stdout(buffer.get(), static_cast<size_t>(n));
}
});
}
if(stderr_fd) {
stderr_thread=std::thread([this](){
DWORD n;
std::unique_ptr<char[]> buffer(new char[buffer_size]);
for (;;) {
BOOL bSuccess = ReadFile(*stderr_fd, static_cast<CHAR*>(buffer.get()), static_cast<DWORD>(buffer_size), &n, NULL);
if(!bSuccess || n == 0)
break;
read_stderr(buffer.get(), static_cast<size_t>(n));
}
});
}
}
int Process::get_exit_status() {
if(data.id==0)
return -1;
DWORD exit_status;
WaitForSingleObject(data.handle, INFINITE);
if(!GetExitCodeProcess(data.handle, &exit_status))
exit_status=-1;
{
std::lock_guard<std::mutex> lock(close_mutex);
CloseHandle(data.handle);
closed=true;
}
close_fds();
return static_cast<int>(exit_status);
}
void Process::close_fds() {
if(stdout_thread.joinable())
stdout_thread.join();
if(stderr_thread.joinable())
stderr_thread.join();
if(stdin_fd)
close_stdin();
if(stdout_fd) {
CloseHandle(*stdout_fd);
stdout_fd.reset();
}
if(stderr_fd) {
CloseHandle(*stderr_fd);
stderr_fd.reset();
}
}
bool Process::write(const char *bytes, size_t n) {
if(!open_stdin)
throw std::invalid_argument("Can't write to an unopened stdin pipe. Please set open_stdin=true when constructing the process.");
std::lock_guard<std::mutex> lock(stdin_mutex);
if(stdin_fd) {
DWORD written;
BOOL bSuccess=WriteFile(*stdin_fd, bytes, static_cast<DWORD>(n), &written, NULL);
if(!bSuccess || written==0) {
return false;
}
else {
return true;
}
}
return false;
}
void Process::close_stdin() {
std::lock_guard<std::mutex> lock(stdin_mutex);
if(stdin_fd) {
CloseHandle(*stdin_fd);
stdin_fd.reset();
}
}
//Based on http://stackoverflow.com/a/1173396
void Process::kill(bool force) {
std::lock_guard<std::mutex> lock(close_mutex);
if(data.id>0 && !closed) {
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(snapshot) {
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
if(Process32First(snapshot, &process)) {
do {
if(process.th32ParentProcessID==data.id) {
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
if(process_handle) TerminateProcess(process_handle, 2);
}
} while (Process32Next(snapshot, &process));
}
}
TerminateProcess(data.handle, 2);
}
}
//Based on http://stackoverflow.com/a/1173396
void Process::kill(id_type id, bool force) {
if(id==0)
return;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(snapshot) {
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
if(Process32First(snapshot, &process)) {
do {
if(process.th32ParentProcessID==id) {
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
if(process_handle) TerminateProcess(process_handle, 2);
}
} while (Process32Next(snapshot, &process));
}
}
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);
if(process_handle) TerminateProcess(process_handle, 2);
}
<commit_msg>On Windows, double check to avoid calling CloseHandle on not initialized handle, when CreateProcess fails.<commit_after>#include "process.hpp"
#include <cstring>
#include <TlHelp32.h>
#include <stdexcept>
Process::Data::Data(): id(0), handle(NULL) {}
//Based on the discussion thread: https://www.reddit.com/r/cpp/comments/3vpjqg/a_new_platform_independent_process_library_for_c11/cxq1wsj
std::mutex create_process_mutex;
//Based on the example at https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx.
Process::id_type Process::open(const std::string &command, const std::string &path) {
if(open_stdin)
stdin_fd=std::unique_ptr<fd_type>(new fd_type(NULL));
if(read_stdout)
stdout_fd=std::unique_ptr<fd_type>(new fd_type(NULL));
if(read_stderr)
stderr_fd=std::unique_ptr<fd_type>(new fd_type(NULL));
HANDLE stdin_rd_p = NULL;
HANDLE stdin_wr_p = NULL;
HANDLE stdout_rd_p = NULL;
HANDLE stdout_wr_p = NULL;
HANDLE stderr_rd_p = NULL;
HANDLE stderr_wr_p = NULL;
SECURITY_ATTRIBUTES security_attributes;
security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
security_attributes.bInheritHandle = TRUE;
security_attributes.lpSecurityDescriptor = NULL;
std::lock_guard<std::mutex> lock(create_process_mutex);
if(stdin_fd) {
if (!CreatePipe(&stdin_rd_p, &stdin_wr_p, &security_attributes, 0)) {
return 0;
}
if(!SetHandleInformation(stdin_wr_p, HANDLE_FLAG_INHERIT, 0)) {
CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);
return 0;
}
}
if(stdout_fd) {
if (!CreatePipe(&stdout_rd_p, &stdout_wr_p, &security_attributes, 0)) {
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
return 0;
}
if(!SetHandleInformation(stdout_rd_p, HANDLE_FLAG_INHERIT, 0)) {
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
CloseHandle(stdout_rd_p);CloseHandle(stdout_wr_p);
return 0;
}
}
if(stderr_fd) {
if (!CreatePipe(&stderr_rd_p, &stderr_wr_p, &security_attributes, 0)) {
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
if(stdout_fd) {CloseHandle(stdout_rd_p);CloseHandle(stdout_wr_p);}
return 0;
}
if(!SetHandleInformation(stderr_rd_p, HANDLE_FLAG_INHERIT, 0)) {
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
if(stdout_fd) {CloseHandle(stdout_rd_p);CloseHandle(stdout_wr_p);}
CloseHandle(stderr_rd_p);CloseHandle(stderr_wr_p);
return 0;
}
}
PROCESS_INFORMATION process_info;
STARTUPINFO startup_info;
ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION));
ZeroMemory(&startup_info, sizeof(STARTUPINFO));
startup_info.cb = sizeof(STARTUPINFO);
startup_info.hStdInput = stdin_fd?stdin_rd_p:INVALID_HANDLE_VALUE;
startup_info.hStdOutput = stdout_fd?stdout_wr_p:INVALID_HANDLE_VALUE;
startup_info.hStdError = stderr_fd?stderr_wr_p:INVALID_HANDLE_VALUE;
if(stdin_fd || stdout_fd || stderr_fd)
startup_info.dwFlags |= STARTF_USESTDHANDLES;
char* path_cstr;
if(path=="")
path_cstr=NULL;
else {
path_cstr=new char[path.size()+1];
std::strcpy(path_cstr, path.c_str());
}
char* command_cstr;
#ifdef MSYS_PROCESS_USE_SH
size_t pos=0;
std::string sh_command=command;
while((pos=sh_command.find('\\', pos))!=std::string::npos) {
sh_command.replace(pos, 1, "\\\\\\\\");
pos+=4;
}
pos=0;
while((pos=sh_command.find('\"', pos))!=std::string::npos) {
sh_command.replace(pos, 1, "\\\"");
pos+=2;
}
sh_command.insert(0, "sh -c \"");
sh_command+="\"";
command_cstr=new char[sh_command.size()+1];
std::strcpy(command_cstr, sh_command.c_str());
#else
command_cstr=new char[command.size()+1];
std::strcpy(command_cstr, command.c_str());
#endif
BOOL bSuccess = CreateProcess(NULL, command_cstr, NULL, NULL, TRUE, 0,
NULL, path_cstr, &startup_info, &process_info);
delete[] path_cstr;
delete[] command_cstr;
if(!bSuccess) {
CloseHandle(process_info.hProcess);
CloseHandle(process_info.hThread);
if(stdin_fd) {CloseHandle(stdin_rd_p);CloseHandle(stdin_wr_p);}
if(stdout_fd) {CloseHandle(stdout_rd_p);CloseHandle(stdout_wr_p);}
if(stderr_fd) {CloseHandle(stderr_rd_p);CloseHandle(stderr_wr_p);}
return 0;
}
else {
CloseHandle(process_info.hThread);
if(stdin_fd) CloseHandle(stdin_rd_p);
if(stdout_fd) CloseHandle(stdout_wr_p);
if(stderr_fd) CloseHandle(stderr_wr_p);
}
if(stdin_fd) *stdin_fd=stdin_wr_p;
if(stdout_fd) *stdout_fd=stdout_rd_p;
if(stderr_fd) *stderr_fd=stderr_rd_p;
closed=false;
data.id=process_info.dwProcessId;
data.handle=process_info.hProcess;
return process_info.dwProcessId;
}
void Process::async_read() {
if(data.id==0)
return;
if(stdout_fd) {
stdout_thread=std::thread([this](){
DWORD n;
std::unique_ptr<char[]> buffer(new char[buffer_size]);
for (;;) {
BOOL bSuccess = ReadFile(*stdout_fd, static_cast<CHAR*>(buffer.get()), static_cast<DWORD>(buffer_size), &n, NULL);
if(!bSuccess || n == 0)
break;
read_stdout(buffer.get(), static_cast<size_t>(n));
}
});
}
if(stderr_fd) {
stderr_thread=std::thread([this](){
DWORD n;
std::unique_ptr<char[]> buffer(new char[buffer_size]);
for (;;) {
BOOL bSuccess = ReadFile(*stderr_fd, static_cast<CHAR*>(buffer.get()), static_cast<DWORD>(buffer_size), &n, NULL);
if(!bSuccess || n == 0)
break;
read_stderr(buffer.get(), static_cast<size_t>(n));
}
});
}
}
int Process::get_exit_status() {
if(data.id==0)
return -1;
DWORD exit_status;
WaitForSingleObject(data.handle, INFINITE);
if(!GetExitCodeProcess(data.handle, &exit_status))
exit_status=-1;
{
std::lock_guard<std::mutex> lock(close_mutex);
CloseHandle(data.handle);
closed=true;
}
close_fds();
return static_cast<int>(exit_status);
}
void Process::close_fds() {
if(stdout_thread.joinable())
stdout_thread.join();
if(stderr_thread.joinable())
stderr_thread.join();
if(stdin_fd)
close_stdin();
if(stdout_fd && *stdout_fd != NULL) {
CloseHandle(*stdout_fd);
stdout_fd.reset();
}
if(stderr_fd && *stderr_fd != NULL) {
CloseHandle(*stderr_fd);
stderr_fd.reset();
}
}
bool Process::write(const char *bytes, size_t n) {
if(!open_stdin)
throw std::invalid_argument("Can't write to an unopened stdin pipe. Please set open_stdin=true when constructing the process.");
std::lock_guard<std::mutex> lock(stdin_mutex);
if(stdin_fd) {
DWORD written;
BOOL bSuccess=WriteFile(*stdin_fd, bytes, static_cast<DWORD>(n), &written, NULL);
if(!bSuccess || written==0) {
return false;
}
else {
return true;
}
}
return false;
}
void Process::close_stdin() {
std::lock_guard<std::mutex> lock(stdin_mutex);
if(stdin_fd && *stdin_fd != NULL) {
CloseHandle(*stdin_fd);
stdin_fd.reset();
}
}
//Based on http://stackoverflow.com/a/1173396
void Process::kill(bool force) {
std::lock_guard<std::mutex> lock(close_mutex);
if(data.id>0 && !closed) {
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(snapshot) {
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
if(Process32First(snapshot, &process)) {
do {
if(process.th32ParentProcessID==data.id) {
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
if(process_handle) TerminateProcess(process_handle, 2);
}
} while (Process32Next(snapshot, &process));
}
}
TerminateProcess(data.handle, 2);
}
}
//Based on http://stackoverflow.com/a/1173396
void Process::kill(id_type id, bool force) {
if(id==0)
return;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(snapshot) {
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
if(Process32First(snapshot, &process)) {
do {
if(process.th32ParentProcessID==id) {
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
if(process_handle) TerminateProcess(process_handle, 2);
}
} while (Process32Next(snapshot, &process));
}
}
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);
if(process_handle) TerminateProcess(process_handle, 2);
}
<|endoftext|>
|
<commit_before>#include "process.hpp"
#include <cstring>
#include "TlHelp32.h"
#include <iostream> //TODO: remove
using namespace std; //TODO: remove
Process::Data::Data(): id(0), handle(NULL) {}
//Based on the example at https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx.
//Note: on Windows it seems impossible to specify which pipes to use.
//Thus, if read_stdout==nullptr, read_stderr==nullptr and open_stdin==false, the stdout, stderr and stdin are sent to the parent process instead.
Process::id_type Process::open(const std::string &command, const std::string &path) {
if(open_stdin)
stdin_fd=std::unique_ptr<fd_type>(new fd_type);
if(read_stdout)
stdout_fd=std::unique_ptr<fd_type>(new fd_type);
if(read_stderr)
stderr_fd=std::unique_ptr<fd_type>(new fd_type);
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hChildStd_ERR_Rd = NULL;
HANDLE g_hChildStd_ERR_Wr = NULL;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if(stdin_fd) {
if (!CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
return 0;
if(!SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0)) {
CloseHandle(g_hChildStd_IN_Rd);
CloseHandle(g_hChildStd_IN_Wr);
return 0;
}
}
if(stdout_fd) {
if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)) {
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Wr);
return 0;
}
if(!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) {
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Wr);
CloseHandle(g_hChildStd_OUT_Rd);
CloseHandle(g_hChildStd_OUT_Wr);
return 0;
}
}
if(stderr_fd) {
if (!CreatePipe(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, &saAttr, 0)) {
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Wr);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Rd);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Wr);
return 0;
}
if(!SetHandleInformation(g_hChildStd_ERR_Rd, HANDLE_FLAG_INHERIT, 0)) {
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Wr);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Rd);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Wr);
CloseHandle(g_hChildStd_ERR_Rd);
CloseHandle(g_hChildStd_ERR_Wr);
return 0;
}
}
PROCESS_INFORMATION process_info;
STARTUPINFO siStartInfo;
ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION));
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
if(stdin_fd) siStartInfo.hStdInput = g_hChildStd_IN_Rd;
if(stdout_fd) siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
if(stderr_fd) siStartInfo.hStdError = g_hChildStd_ERR_Wr;
if(stdin_fd || stdout_fd || stderr_fd)
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
char* path_ptr;
if(path=="")
path_ptr=NULL;
else {
path_ptr=new char[path.size()+1];
std::strcpy(path_ptr, path.c_str());
}
char* command_cstr;
#ifdef MSYS_PROCESS_USE_SH
size_t pos=0;
std::string sh_command=command;
while((pos=sh_command.find('\"', pos))!=std::string::npos) {
if(pos>0 && sh_command[pos-1]!='\\') {
sh_command.replace(pos, 1, "\\\"");
pos++;
}
pos++;
}
pos=0;
while((pos=sh_command.find('\\', pos))!=std::string::npos) {
if((pos+1)==sh_command.size() || sh_command[pos+1]!='\"') {
sh_command.replace(pos, 1, "\\\\\\");
pos++;
}
pos+=2;
}
sh_command.insert(0, "sh -c \"");
sh_command+="\"";
command_cstr=new char[sh_command.size()+1];
std::strcpy(command_cstr, sh_command.c_str());
#else
command_cstr=new char[command.size()+1];
std::strcpy(command_cstr, command.c_str());
#endif
BOOL bSuccess = CreateProcess(NULL, command_cstr, NULL, NULL, TRUE, 0,
NULL, path_ptr, &siStartInfo, &process_info);
if(!bSuccess) {
CloseHandle(process_info.hProcess);
CloseHandle(process_info.hThread);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Wr);
if(stderr_fd) CloseHandle(g_hChildStd_ERR_Wr);
return 0;
}
else {
CloseHandle(process_info.hThread);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Wr);
if(stderr_fd) CloseHandle(g_hChildStd_ERR_Wr);
}
if(stdin_fd) *stdin_fd=g_hChildStd_IN_Wr;
if(stdout_fd) *stdout_fd=g_hChildStd_OUT_Rd;
if(stderr_fd) *stderr_fd=g_hChildStd_ERR_Rd;
closed=false;
data.id=process_info.dwProcessId;
data.handle=process_info.hProcess;
return process_info.dwProcessId;
}
void Process::async_read() {
if(data.id==0)
return;
if(stdout_fd) {
stdout_thread=std::thread([this](){
DWORD n;
char buffer[buffer_size];
for (;;) {
BOOL bSuccess = ReadFile(*stdout_fd, static_cast<CHAR*>(buffer), static_cast<DWORD>(buffer_size), &n, NULL);
if(!bSuccess || n == 0)
break;
read_stdout(buffer, static_cast<size_t>(n));
}
});
}
if(stderr_fd) {
stderr_thread=std::thread([this](){
DWORD n;
char buffer[buffer_size];
for (;;) {
BOOL bSuccess = ReadFile(*stderr_fd, static_cast<CHAR*>(buffer), static_cast<DWORD>(buffer_size), &n, NULL);
if(!bSuccess || n == 0)
break;
read_stderr(buffer, static_cast<size_t>(n));
}
});
}
}
int Process::get_exit_status() {
if(data.id==0)
return -1;
DWORD exit_status;
WaitForSingleObject(data.handle, INFINITE);
if(!GetExitCodeProcess(data.handle, &exit_status))
exit_status=-1;
close_mutex.lock();
CloseHandle(data.handle);
closed=true;
close_mutex.unlock();
close_fds();
return static_cast<int>(exit_status);
}
void Process::close_fds() {
if(stdout_thread.joinable())
stdout_thread.join();
if(stderr_thread.joinable())
stderr_thread.join();
if(stdin_fd)
close_stdin();
if(stdout_fd) {
CloseHandle(*stdout_fd);
stdout_fd.reset();
}
if(stderr_fd) {
CloseHandle(*stderr_fd);
stderr_fd.reset();
}
}
bool Process::write(const char *bytes, size_t n) {
stdin_mutex.lock();
if(stdin_fd) {
DWORD written;
BOOL bSuccess=WriteFile(*stdin_fd, bytes, static_cast<DWORD>(n), &written, NULL);
if(!bSuccess || written==0) {
stdin_mutex.unlock();
return false;
}
else {
stdin_mutex.unlock();
return true;
}
}
stdin_mutex.unlock();
return false;
}
void Process::close_stdin() {
stdin_mutex.lock();
if(stdin_fd) {
CloseHandle(*stdin_fd);
stdin_fd.reset();
}
stdin_mutex.unlock();
}
//Based on http://stackoverflow.com/a/1173396
void Process::kill(bool force) {
close_mutex.lock();
if(data.id>0 && !closed) {
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(snapshot) {
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
if(Process32First(snapshot, &process)) {
do {
if(process.th32ParentProcessID==data.id) {
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
if(process_handle) TerminateProcess(process_handle, 2);
}
} while (Process32Next(snapshot, &process));
}
}
TerminateProcess(data.handle, 2);
}
close_mutex.unlock();
}
//Based on http://stackoverflow.com/a/1173396
void Process::kill(id_type id, bool force) {
if(id==0)
return;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(snapshot) {
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
if(Process32First(snapshot, &process)) {
do {
if(process.th32ParentProcessID==id) {
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
if(process_handle) TerminateProcess(process_handle, 2);
}
} while (Process32Next(snapshot, &process));
}
}
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);
if(process_handle) TerminateProcess(process_handle, 2);
}
<commit_msg>Now frees up path_ptr and command_cstr<commit_after>#include "process.hpp"
#include <cstring>
#include "TlHelp32.h"
#include <iostream> //TODO: remove
using namespace std; //TODO: remove
Process::Data::Data(): id(0), handle(NULL) {}
//Based on the example at https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx.
//Note: on Windows it seems impossible to specify which pipes to use.
//Thus, if read_stdout==nullptr, read_stderr==nullptr and open_stdin==false, the stdout, stderr and stdin are sent to the parent process instead.
Process::id_type Process::open(const std::string &command, const std::string &path) {
if(open_stdin)
stdin_fd=std::unique_ptr<fd_type>(new fd_type);
if(read_stdout)
stdout_fd=std::unique_ptr<fd_type>(new fd_type);
if(read_stderr)
stderr_fd=std::unique_ptr<fd_type>(new fd_type);
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hChildStd_ERR_Rd = NULL;
HANDLE g_hChildStd_ERR_Wr = NULL;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if(stdin_fd) {
if (!CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
return 0;
if(!SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0)) {
CloseHandle(g_hChildStd_IN_Rd);
CloseHandle(g_hChildStd_IN_Wr);
return 0;
}
}
if(stdout_fd) {
if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)) {
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Wr);
return 0;
}
if(!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) {
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Wr);
CloseHandle(g_hChildStd_OUT_Rd);
CloseHandle(g_hChildStd_OUT_Wr);
return 0;
}
}
if(stderr_fd) {
if (!CreatePipe(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, &saAttr, 0)) {
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Wr);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Rd);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Wr);
return 0;
}
if(!SetHandleInformation(g_hChildStd_ERR_Rd, HANDLE_FLAG_INHERIT, 0)) {
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Wr);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Rd);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Wr);
CloseHandle(g_hChildStd_ERR_Rd);
CloseHandle(g_hChildStd_ERR_Wr);
return 0;
}
}
PROCESS_INFORMATION process_info;
STARTUPINFO siStartInfo;
ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION));
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
if(stdin_fd) siStartInfo.hStdInput = g_hChildStd_IN_Rd;
if(stdout_fd) siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
if(stderr_fd) siStartInfo.hStdError = g_hChildStd_ERR_Wr;
if(stdin_fd || stdout_fd || stderr_fd)
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
char* path_ptr;
if(path=="")
path_ptr=NULL;
else {
path_ptr=new char[path.size()+1];
std::strcpy(path_ptr, path.c_str());
}
char* command_cstr;
#ifdef MSYS_PROCESS_USE_SH
size_t pos=0;
std::string sh_command=command;
while((pos=sh_command.find('\"', pos))!=std::string::npos) {
if(pos>0 && sh_command[pos-1]!='\\') {
sh_command.replace(pos, 1, "\\\"");
pos++;
}
pos++;
}
pos=0;
while((pos=sh_command.find('\\', pos))!=std::string::npos) {
if((pos+1)==sh_command.size() || sh_command[pos+1]!='\"') {
sh_command.replace(pos, 1, "\\\\\\");
pos++;
}
pos+=2;
}
sh_command.insert(0, "sh -c \"");
sh_command+="\"";
command_cstr=new char[sh_command.size()+1];
std::strcpy(command_cstr, sh_command.c_str());
#else
command_cstr=new char[command.size()+1];
std::strcpy(command_cstr, command.c_str());
#endif
BOOL bSuccess = CreateProcess(NULL, command_cstr, NULL, NULL, TRUE, 0,
NULL, path_ptr, &siStartInfo, &process_info);
delete[] path_ptr;
delete[] command_cstr;
if(!bSuccess) {
CloseHandle(process_info.hProcess);
CloseHandle(process_info.hThread);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Wr);
if(stderr_fd) CloseHandle(g_hChildStd_ERR_Wr);
return 0;
}
else {
CloseHandle(process_info.hThread);
if(stdin_fd) CloseHandle(g_hChildStd_IN_Rd);
if(stdout_fd) CloseHandle(g_hChildStd_OUT_Wr);
if(stderr_fd) CloseHandle(g_hChildStd_ERR_Wr);
}
if(stdin_fd) *stdin_fd=g_hChildStd_IN_Wr;
if(stdout_fd) *stdout_fd=g_hChildStd_OUT_Rd;
if(stderr_fd) *stderr_fd=g_hChildStd_ERR_Rd;
closed=false;
data.id=process_info.dwProcessId;
data.handle=process_info.hProcess;
return process_info.dwProcessId;
}
void Process::async_read() {
if(data.id==0)
return;
if(stdout_fd) {
stdout_thread=std::thread([this](){
DWORD n;
char buffer[buffer_size];
for (;;) {
BOOL bSuccess = ReadFile(*stdout_fd, static_cast<CHAR*>(buffer), static_cast<DWORD>(buffer_size), &n, NULL);
if(!bSuccess || n == 0)
break;
read_stdout(buffer, static_cast<size_t>(n));
}
});
}
if(stderr_fd) {
stderr_thread=std::thread([this](){
DWORD n;
char buffer[buffer_size];
for (;;) {
BOOL bSuccess = ReadFile(*stderr_fd, static_cast<CHAR*>(buffer), static_cast<DWORD>(buffer_size), &n, NULL);
if(!bSuccess || n == 0)
break;
read_stderr(buffer, static_cast<size_t>(n));
}
});
}
}
int Process::get_exit_status() {
if(data.id==0)
return -1;
DWORD exit_status;
WaitForSingleObject(data.handle, INFINITE);
if(!GetExitCodeProcess(data.handle, &exit_status))
exit_status=-1;
close_mutex.lock();
CloseHandle(data.handle);
closed=true;
close_mutex.unlock();
close_fds();
return static_cast<int>(exit_status);
}
void Process::close_fds() {
if(stdout_thread.joinable())
stdout_thread.join();
if(stderr_thread.joinable())
stderr_thread.join();
if(stdin_fd)
close_stdin();
if(stdout_fd) {
CloseHandle(*stdout_fd);
stdout_fd.reset();
}
if(stderr_fd) {
CloseHandle(*stderr_fd);
stderr_fd.reset();
}
}
bool Process::write(const char *bytes, size_t n) {
stdin_mutex.lock();
if(stdin_fd) {
DWORD written;
BOOL bSuccess=WriteFile(*stdin_fd, bytes, static_cast<DWORD>(n), &written, NULL);
if(!bSuccess || written==0) {
stdin_mutex.unlock();
return false;
}
else {
stdin_mutex.unlock();
return true;
}
}
stdin_mutex.unlock();
return false;
}
void Process::close_stdin() {
stdin_mutex.lock();
if(stdin_fd) {
CloseHandle(*stdin_fd);
stdin_fd.reset();
}
stdin_mutex.unlock();
}
//Based on http://stackoverflow.com/a/1173396
void Process::kill(bool force) {
close_mutex.lock();
if(data.id>0 && !closed) {
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(snapshot) {
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
if(Process32First(snapshot, &process)) {
do {
if(process.th32ParentProcessID==data.id) {
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
if(process_handle) TerminateProcess(process_handle, 2);
}
} while (Process32Next(snapshot, &process));
}
}
TerminateProcess(data.handle, 2);
}
close_mutex.unlock();
}
//Based on http://stackoverflow.com/a/1173396
void Process::kill(id_type id, bool force) {
if(id==0)
return;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(snapshot) {
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
if(Process32First(snapshot, &process)) {
do {
if(process.th32ParentProcessID==id) {
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process.th32ProcessID);
if(process_handle) TerminateProcess(process_handle, 2);
}
} while (Process32Next(snapshot, &process));
}
}
HANDLE process_handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);
if(process_handle) TerminateProcess(process_handle, 2);
}
<|endoftext|>
|
<commit_before>/*
* Test Driver for Botan
*/
#include <vector>
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <botan/botan.h>
#include <botan/mp_types.h>
using namespace Botan_types;
#include "getopt.h"
const std::string VALIDATION_FILE = "checks/validate.dat";
const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat";
const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat";
const std::string EXPECTED_FAIL_FILE = "checks/fail.dat";
void benchmark(const std::string&, bool html, double seconds);
void bench_pk(const std::string&, bool html, double seconds);
u32bit bench_algo(const std::string&, double);
int validate();
int main(int argc, char* argv[])
{
try
{
OptionParser opts("help|html|init=|validate|"
"benchmark|bench-type=|bench-algo=|seconds=");
opts.parse(argv);
Botan::InitializerOptions init_options(opts.value_if_set("init"));
Botan::LibraryInitializer init(init_options);
if(opts.is_set("help") || argc <= 1)
{
std::cerr << "Test driver for "
<< Botan::version_string() << "\n"
<< "Options:\n"
<< " --validate: Check test vectors\n"
<< " --benchmark: Benchmark everything\n"
<< " --bench-type={block,mode,stream,hash,mac,rng,pk}:\n"
<< " Benchmark only algorithms of a particular type\n"
<< " --html: Produce HTML output for benchmarks\n"
<< " --seconds=n: Benchmark for n seconds\n"
<< " --init=<str>: Pass <str> to the library\n"
<< " --help: Print this message\n";
return 1;
}
if(opts.is_set("validate"))
return validate();
double seconds = 1.5;
if(opts.is_set("seconds"))
{
seconds = std::atof(opts.value("seconds").c_str());
if(seconds && (seconds < 0.1 || seconds > (5 * 60)))
{
std::cout << "Invalid argument to --seconds\n";
return 2;
}
}
const bool html = opts.is_set("html");
if(opts.is_set("bench-algo"))
{
std::vector<std::string> algs =
Botan::split_on(opts.value("bench-algo"), ',');
for(u32bit j = 0; j != algs.size(); j++)
{
const std::string alg = algs[j];
u32bit found = bench_algo(alg, seconds);
if(!found) // maybe it's a PK algorithm
bench_pk(alg, html, seconds);
}
}
if(opts.is_set("benchmark"))
benchmark("All", html, seconds);
else if(opts.is_set("bench-type"))
{
const std::string type = opts.value("bench-type");
if(type == "all")
benchmark("All", html, seconds);
else if(type == "block")
benchmark("Block Cipher", html, seconds);
else if(type == "stream")
benchmark("Stream Cipher", html, seconds);
else if(type == "hash")
benchmark("Hash", html, seconds);
else if(type == "mac")
benchmark("MAC", html, seconds);
else if(type == "rng")
benchmark("RNG", html, seconds);
else if(type == "pk")
bench_pk("All", html, seconds);
}
}
catch(Botan::Exception& e)
{
std::cout << "Exception caught:\n " << e.what() << std::endl;
return 1;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught:\n "
<< e.what() << std::endl;
return 1;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 1;
}
return 0;
}
int validate()
{
void test_types();
u32bit do_validation_tests(const std::string&, bool = true);
u32bit do_bigint_tests(const std::string&);
u32bit do_pk_validation_tests(const std::string&);
std::cout << "Beginning validation tests..." << std::endl;
test_types();
u32bit errors = 0;
try {
errors += do_validation_tests(VALIDATION_FILE);
errors += do_validation_tests(EXPECTED_FAIL_FILE, false);
errors += do_bigint_tests(BIGINT_VALIDATION_FILE);
errors += do_pk_validation_tests(PK_VALIDATION_FILE);
}
catch(Botan::Exception& e)
{
std::cout << "Exception caught: " << e.what() << std::endl;
return 1;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: "
<< e.what() << std::endl;
return 1;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 1;
}
if(errors)
{
std::cout << errors << " test" << ((errors == 1) ? "" : "s")
<< " failed." << std::endl;
return 1;
}
std::cout << "All tests passed!" << std::endl;
return 0;
}
template<typename T>
bool test(const char* type, int digits, bool is_signed)
{
bool passed = true;
if(std::numeric_limits<T>::is_specialized == false)
{
std::cout << "WARNING: Could not check parameters of " << type
<< " in std::numeric_limits" << std::endl;
return true;
}
if(std::numeric_limits<T>::digits != digits && digits != 0)
{
std::cout << "ERROR: numeric_limits<" << type << ">::digits != "
<< digits << std::endl;
passed = false;
}
if(std::numeric_limits<T>::is_signed != is_signed)
{
std::cout << "ERROR: numeric_limits<" << type << ">::is_signed != "
<< std::boolalpha << is_signed << std::endl;
passed = false;
}
if(std::numeric_limits<T>::is_integer == false)
{
std::cout << "ERROR: numeric_limits<" << type
<< ">::is_integer == false " << std::endl;
passed = false;
}
return passed;
}
void test_types()
{
bool passed = true;
passed = passed && test<Botan::byte >("byte", 8, false);
passed = passed && test<Botan::u16bit>("u16bit", 16, false);
passed = passed && test<Botan::u32bit>("u32bit", 32, false);
passed = passed && test<Botan::u64bit>("u64bit", 64, false);
passed = passed && test<Botan::s32bit>("s32bit", 31, true);
passed = passed && test<Botan::word>("word", 0, false);
if(!passed)
{
std::cout << "Important settings in types.h are wrong. Please fix "
"and recompile." << std::endl;
std::exit(1);
}
}
<commit_msg>Prevent lines > 80 columns<commit_after>/*
* Test Driver for Botan
*/
#include <vector>
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <limits>
#include <botan/botan.h>
#include <botan/mp_types.h>
using namespace Botan_types;
#include "getopt.h"
const std::string VALIDATION_FILE = "checks/validate.dat";
const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat";
const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat";
const std::string EXPECTED_FAIL_FILE = "checks/fail.dat";
void benchmark(const std::string&, bool html, double seconds);
void bench_pk(const std::string&, bool html, double seconds);
u32bit bench_algo(const std::string&, double);
int validate();
int main(int argc, char* argv[])
{
try
{
OptionParser opts("help|html|init=|validate|"
"benchmark|bench-type=|bench-algo=|seconds=");
opts.parse(argv);
Botan::InitializerOptions init_options(opts.value_if_set("init"));
Botan::LibraryInitializer init(init_options);
if(opts.is_set("help") || argc <= 1)
{
std::cerr << "Test driver for "
<< Botan::version_string() << "\n"
<< "Options:\n"
<< " --validate: Check test vectors\n"
<< " --benchmark: Benchmark everything\n"
<< " --bench-type={block,mode,stream,hash,mac,rng,pk}:\n"
<< " Benchmark only algorithms of a particular type\n"
<< " --html: Produce HTML output for benchmarks\n"
<< " --seconds=n: Benchmark for n seconds\n"
<< " --init=<str>: Pass <str> to the library\n"
<< " --help: Print this message\n";
return 1;
}
if(opts.is_set("validate"))
return validate();
double seconds = 1.5;
if(opts.is_set("seconds"))
{
seconds = std::atof(opts.value("seconds").c_str());
if(seconds && (seconds < 0.1 || seconds > (5 * 60)))
{
std::cout << "Invalid argument to --seconds\n";
return 2;
}
}
const bool html = opts.is_set("html");
if(opts.is_set("bench-algo"))
{
std::vector<std::string> algs =
Botan::split_on(opts.value("bench-algo"), ',');
for(u32bit j = 0; j != algs.size(); j++)
{
const std::string alg = algs[j];
u32bit found = bench_algo(alg, seconds);
if(!found) // maybe it's a PK algorithm
bench_pk(alg, html, seconds);
}
}
if(opts.is_set("benchmark"))
benchmark("All", html, seconds);
else if(opts.is_set("bench-type"))
{
const std::string type = opts.value("bench-type");
if(type == "all")
benchmark("All", html, seconds);
else if(type == "block")
benchmark("Block Cipher", html, seconds);
else if(type == "stream")
benchmark("Stream Cipher", html, seconds);
else if(type == "hash")
benchmark("Hash", html, seconds);
else if(type == "mac")
benchmark("MAC", html, seconds);
else if(type == "rng")
benchmark("RNG", html, seconds);
else if(type == "pk")
bench_pk("All", html, seconds);
}
}
catch(Botan::Exception& e)
{
std::cout << "Exception caught:\n " << e.what() << std::endl;
return 1;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught:\n "
<< e.what() << std::endl;
return 1;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 1;
}
return 0;
}
int validate()
{
void test_types();
u32bit do_validation_tests(const std::string&, bool = true);
u32bit do_bigint_tests(const std::string&);
u32bit do_pk_validation_tests(const std::string&);
std::cout << "Beginning validation tests..." << std::endl;
test_types();
u32bit errors = 0;
try {
errors += do_validation_tests(VALIDATION_FILE);
errors += do_validation_tests(EXPECTED_FAIL_FILE, false);
errors += do_bigint_tests(BIGINT_VALIDATION_FILE);
errors += do_pk_validation_tests(PK_VALIDATION_FILE);
}
catch(Botan::Exception& e)
{
std::cout << "Exception caught: " << e.what() << std::endl;
return 1;
}
catch(std::exception& e)
{
std::cout << "Standard library exception caught: "
<< e.what() << std::endl;
return 1;
}
catch(...)
{
std::cout << "Unknown exception caught." << std::endl;
return 1;
}
if(errors)
{
std::cout << errors << " test" << ((errors == 1) ? "" : "s")
<< " failed." << std::endl;
return 1;
}
std::cout << "All tests passed!" << std::endl;
return 0;
}
template<typename T>
bool test(const char* type, int digits, bool is_signed)
{
bool passed = true;
if(std::numeric_limits<T>::is_specialized == false)
{
std::cout << "WARNING: Could not check parameters of " << type
<< " in std::numeric_limits" << std::endl;
return true;
}
if(std::numeric_limits<T>::digits != digits && digits != 0)
{
std::cout << "ERROR: numeric_limits<" << type << ">::digits != "
<< digits << std::endl;
passed = false;
}
if(std::numeric_limits<T>::is_signed != is_signed)
{
std::cout << "ERROR: numeric_limits<" << type << ">::is_signed != "
<< std::boolalpha << is_signed << std::endl;
passed = false;
}
if(std::numeric_limits<T>::is_integer == false)
{
std::cout << "ERROR: numeric_limits<" << type
<< ">::is_integer == false " << std::endl;
passed = false;
}
return passed;
}
void test_types()
{
bool passed = true;
passed = passed && test<Botan::byte >("byte", 8, false);
passed = passed && test<Botan::u16bit>("u16bit", 16, false);
passed = passed && test<Botan::u32bit>("u32bit", 32, false);
passed = passed && test<Botan::u64bit>("u64bit", 64, false);
passed = passed && test<Botan::s32bit>("s32bit", 31, true);
passed = passed && test<Botan::word>("word", 0, false);
if(!passed)
{
std::cout << "Important settings in types.h are wrong. Please fix "
"and recompile." << std::endl;
std::exit(1);
}
}
<|endoftext|>
|
<commit_before>/*!
* This file is part of CameraPlus.
*
* Copyright (C) 2012 Mohammed Sameer <msameer@foolab.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.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "camera.h"
#include "qtcamera.h"
#include "qtcamdevice.h"
#include "qtcammode.h"
#include "qtcamimagemode.h"
#include "qtcamvideomode.h"
#include "qtcamgraphicsviewfinder.h"
#include "qtcamconfig.h"
#include "notifications.h"
#include "notificationscontainer.h"
#include "sounds.h"
#include <QDeclarativeInfo>
#include "zoom.h"
#include "flash.h"
#include "scene.h"
#include "evcomp.h"
#include "whitebalance.h"
#include "colortone.h"
#include "iso.h"
#include "exposure.h"
#include "aperture.h"
#include "noisereduction.h"
#include "flickerreduction.h"
#include "focus.h"
#include "autofocus.h"
#include "videomute.h"
#include "videotorch.h"
Camera::Camera(QDeclarativeItem *parent) :
QDeclarativeItem(parent),
m_cam(new QtCamera(this)),
m_dev(0),
m_vf(new QtCamGraphicsViewfinder(m_cam->config(), this)),
m_mode(Camera::UnknownMode),
m_notifications(new NotificationsContainer(this)),
m_zoom(0),
m_flash(0),
m_scene(0),
m_evComp(0),
m_whiteBalance(0),
m_colorTone(0),
m_iso(0),
m_exposure(0),
m_aperture(0),
m_noiseReduction(0),
m_flickerReduction(0),
m_focus(0),
m_autoFocus(0),
m_videoMute(0),
m_videoTorch(0) {
QObject::connect(m_vf, SIGNAL(renderAreaChanged()), this, SIGNAL(renderAreaChanged()));
QObject::connect(m_vf, SIGNAL(videoResolutionChanged()), this, SIGNAL(videoResolutionChanged()));
QObject::connect(m_vf, SIGNAL(renderingEnabledChanged()), this, SIGNAL(renderingEnabledChanged()));
}
Camera::~Camera() {
if (m_dev) {
m_dev->stop(true);
m_dev->deleteLater();
m_dev = 0;
}
delete m_zoom;
delete m_flash;
delete m_scene;
delete m_evComp;
delete m_whiteBalance;
delete m_colorTone;
delete m_iso;
delete m_exposure;
delete m_aperture;
delete m_noiseReduction;
delete m_flickerReduction;
delete m_focus;
delete m_autoFocus;
delete m_videoMute;
delete m_videoTorch;
// TODO: cleanup
}
void Camera::componentComplete() {
QDeclarativeItem::componentComplete();
emit deviceCountChanged();
}
int Camera::deviceCount() const {
return m_cam ? m_cam->devices().size() : 0;
}
QString Camera::deviceName(int index) const {
return m_cam->devices().at(index).first;
}
QVariant Camera::deviceId(int index) const {
return m_cam->devices().at(index).second;
}
bool Camera::reset(const QVariant& deviceId, const CameraMode& mode) {
if (mode == Camera::UnknownMode) {
qmlInfo(this) << "Cannot set mode to unknown";
return false;
}
if (!isComponentComplete()) {
qmlInfo(this) << "Component is still not ready";
return false;
}
QVariant oldId = m_id;
Camera::CameraMode oldMode = m_mode;
if (setDeviceId(deviceId) && setMode(mode)) {
if (oldId != m_id) {
emit deviceIdChanged();
emit deviceChanged();
resetCapabilities();
}
if (oldMode != m_mode) {
emit modeChanged();
}
return true;
}
return false;
}
bool Camera::setDeviceId(const QVariant& deviceId) {
if (deviceId == m_id) {
return true;
}
if (m_dev && m_dev->stop(false)) {
delete m_dev;
}
else if (m_dev) {
qmlInfo(this) << "Failed to stop device";
return false;
}
m_dev = m_cam->device(deviceId, this);
m_id = deviceId;
m_vf->setDevice(m_dev);
QObject::connect(m_dev, SIGNAL(runningStateChanged(bool)),
this, SIGNAL(runningStateChanged()));
QObject::connect(m_dev, SIGNAL(idleStateChanged(bool)), this, SIGNAL(idleStateChanged()));
QObject::connect(m_dev, SIGNAL(error(const QString&, int, const QString&)),
this, SIGNAL(error(const QString&, int, const QString&)));
m_notifications->setDevice(m_dev);
return true;
}
QVariant Camera::deviceId() const {
return m_id;
}
void Camera::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
m_vf->setGeometry(newGeometry);
}
QtCamDevice *Camera::device() const {
return m_dev;
}
bool Camera::setMode(const Camera::CameraMode& mode) {
if (m_mode == mode) {
return true;
}
if (!m_dev) {
return false;
}
m_mode = mode;
if (m_dev->isRunning()) {
applyMode();
}
return true;
}
Camera::CameraMode Camera::mode() {
return m_mode;
}
bool Camera::start() {
if (!m_dev) {
return false;
}
if (!applyMode()) {
return false;
}
return m_dev->start();
}
bool Camera::stop(bool force) {
if (m_dev) {
return m_dev->stop(force);
}
return true;
}
bool Camera::isIdle() {
return m_dev ? m_dev->isIdle() : true;
}
bool Camera::isRunning() {
return m_dev ? m_dev->isRunning() : false;
}
bool Camera::applyMode() {
if (m_mode == Camera::UnknownMode) {
return false;
}
if (m_mode == Camera::VideoMode && m_dev->activeMode() != m_dev->videoMode()) {
m_dev->videoMode()->activate();
}
else if (m_mode == Camera::ImageMode && m_dev->activeMode() != m_dev->imageMode()) {
m_dev->imageMode()->activate();
}
return true;
}
QString Camera::imageSuffix() const {
return m_cam->config()->imageSuffix();
}
QString Camera::videoSuffix() const {
return m_cam->config()->videoSuffix();
}
Notifications *Camera::notifications() const {
return m_notifications->notifications();
}
void Camera::setNotifications(Notifications *notifications) {
if (m_notifications->setNotifications(notifications)) {
if (Sounds *s = dynamic_cast<Sounds *>(notifications)) {
s->setConfig(m_cam->config());
s->reload();
}
emit notificationsChanged();
}
}
QRectF Camera::renderArea() const {
return m_vf->renderArea();
}
QSizeF Camera::videoResolution() const {
return m_vf->videoResolution();
}
void Camera::resetCapabilities() {
QtCamDevice *dev = device();
delete m_zoom;
m_zoom = new Zoom(dev, this);
emit zoomChanged();
delete m_flash;
m_flash = new Flash(dev, this);
emit flashChanged();
delete m_scene;
m_scene = new Scene(dev, this);
emit sceneChanged();
delete m_evComp;
m_evComp = new EvComp(dev, this);
emit evCompChanged();
delete m_whiteBalance;
m_whiteBalance = new WhiteBalance(dev, this);
emit whiteBalanceChanged();
delete m_colorTone;
m_colorTone = new ColorTone(dev, this);
emit colorToneChanged();
delete m_iso;
m_iso = new Iso(dev, this);
emit isoChanged();
delete m_exposure;
m_exposure = new Exposure(dev, this);
emit exposureChanged();
delete m_aperture;
m_aperture = new Aperture(dev, this);
emit apertureChanged();
delete m_noiseReduction;
m_noiseReduction = new NoiseReduction(dev, this);
emit noiseReductionChanged();
delete m_flickerReduction;
m_flickerReduction = new FlickerReduction(dev, this);
emit flickerReductionChanged();
delete m_focus;
m_focus = new Focus(dev, this);
emit focusChanged();
delete m_autoFocus;
m_autoFocus = new AutoFocus(dev, this);
emit autoFocusChanged();
delete m_videoMute;
m_videoMute = new VideoMute(dev, this);
emit videoMuteChanged();
delete m_videoTorch;
m_videoTorch = new VideoTorch(dev, this);
emit videoTorchChanged();
}
Zoom *Camera::zoom() const {
return m_zoom;
}
Flash *Camera::flash() const {
return m_flash;
}
Scene *Camera::scene() const {
return m_scene;
}
EvComp *Camera::evComp() const {
return m_evComp;
}
WhiteBalance *Camera::whiteBalance() const {
return m_whiteBalance;
}
ColorTone *Camera::colorTone() const {
return m_colorTone;
}
Iso *Camera::iso() const {
return m_iso;
}
Exposure *Camera::exposure() const {
return m_exposure;
}
Aperture *Camera::aperture() const {
return m_aperture;
}
NoiseReduction *Camera::noiseReduction() const {
return m_noiseReduction;
}
FlickerReduction *Camera::flickerReduction() const {
return m_flickerReduction;
}
Focus *Camera::focus() const {
return m_focus;
}
AutoFocus *Camera::autoFocus() const {
return m_autoFocus;
}
VideoMute *Camera::videoMute() const {
return m_videoMute;
}
VideoTorch *Camera::videoTorch() const {
return m_videoTorch;
}
bool Camera::isRenderingEnabled() const {
return m_vf->isRenderingEnabled();
}
void Camera::setRenderingEnabled(bool enabled) {
m_vf->setRenderingEnabled(enabled);
}
<commit_msg>Declarative Camera should deactivete active mode when destroyed before stopping the device. This will prevent losing the video being recorded when closing camera while recording<commit_after>/*!
* This file is part of CameraPlus.
*
* Copyright (C) 2012 Mohammed Sameer <msameer@foolab.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.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "camera.h"
#include "qtcamera.h"
#include "qtcamdevice.h"
#include "qtcammode.h"
#include "qtcamimagemode.h"
#include "qtcamvideomode.h"
#include "qtcamgraphicsviewfinder.h"
#include "qtcamconfig.h"
#include "notifications.h"
#include "notificationscontainer.h"
#include "sounds.h"
#include <QDeclarativeInfo>
#include "zoom.h"
#include "flash.h"
#include "scene.h"
#include "evcomp.h"
#include "whitebalance.h"
#include "colortone.h"
#include "iso.h"
#include "exposure.h"
#include "aperture.h"
#include "noisereduction.h"
#include "flickerreduction.h"
#include "focus.h"
#include "autofocus.h"
#include "videomute.h"
#include "videotorch.h"
Camera::Camera(QDeclarativeItem *parent) :
QDeclarativeItem(parent),
m_cam(new QtCamera(this)),
m_dev(0),
m_vf(new QtCamGraphicsViewfinder(m_cam->config(), this)),
m_mode(Camera::UnknownMode),
m_notifications(new NotificationsContainer(this)),
m_zoom(0),
m_flash(0),
m_scene(0),
m_evComp(0),
m_whiteBalance(0),
m_colorTone(0),
m_iso(0),
m_exposure(0),
m_aperture(0),
m_noiseReduction(0),
m_flickerReduction(0),
m_focus(0),
m_autoFocus(0),
m_videoMute(0),
m_videoTorch(0) {
QObject::connect(m_vf, SIGNAL(renderAreaChanged()), this, SIGNAL(renderAreaChanged()));
QObject::connect(m_vf, SIGNAL(videoResolutionChanged()), this, SIGNAL(videoResolutionChanged()));
QObject::connect(m_vf, SIGNAL(renderingEnabledChanged()), this, SIGNAL(renderingEnabledChanged()));
}
Camera::~Camera() {
if (m_dev) {
if (m_dev->activeMode()) {
m_dev->activeMode()->deactivate();
}
m_dev->stop(true);
m_dev->deleteLater();
m_dev = 0;
}
delete m_zoom;
delete m_flash;
delete m_scene;
delete m_evComp;
delete m_whiteBalance;
delete m_colorTone;
delete m_iso;
delete m_exposure;
delete m_aperture;
delete m_noiseReduction;
delete m_flickerReduction;
delete m_focus;
delete m_autoFocus;
delete m_videoMute;
delete m_videoTorch;
// TODO: cleanup
}
void Camera::componentComplete() {
QDeclarativeItem::componentComplete();
emit deviceCountChanged();
}
int Camera::deviceCount() const {
return m_cam ? m_cam->devices().size() : 0;
}
QString Camera::deviceName(int index) const {
return m_cam->devices().at(index).first;
}
QVariant Camera::deviceId(int index) const {
return m_cam->devices().at(index).second;
}
bool Camera::reset(const QVariant& deviceId, const CameraMode& mode) {
if (mode == Camera::UnknownMode) {
qmlInfo(this) << "Cannot set mode to unknown";
return false;
}
if (!isComponentComplete()) {
qmlInfo(this) << "Component is still not ready";
return false;
}
QVariant oldId = m_id;
Camera::CameraMode oldMode = m_mode;
if (setDeviceId(deviceId) && setMode(mode)) {
if (oldId != m_id) {
emit deviceIdChanged();
emit deviceChanged();
resetCapabilities();
}
if (oldMode != m_mode) {
emit modeChanged();
}
return true;
}
return false;
}
bool Camera::setDeviceId(const QVariant& deviceId) {
if (deviceId == m_id) {
return true;
}
if (m_dev && m_dev->stop(false)) {
delete m_dev;
}
else if (m_dev) {
qmlInfo(this) << "Failed to stop device";
return false;
}
m_dev = m_cam->device(deviceId, this);
m_id = deviceId;
m_vf->setDevice(m_dev);
QObject::connect(m_dev, SIGNAL(runningStateChanged(bool)),
this, SIGNAL(runningStateChanged()));
QObject::connect(m_dev, SIGNAL(idleStateChanged(bool)), this, SIGNAL(idleStateChanged()));
QObject::connect(m_dev, SIGNAL(error(const QString&, int, const QString&)),
this, SIGNAL(error(const QString&, int, const QString&)));
m_notifications->setDevice(m_dev);
return true;
}
QVariant Camera::deviceId() const {
return m_id;
}
void Camera::geometryChanged(const QRectF& newGeometry, const QRectF& oldGeometry) {
QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
m_vf->setGeometry(newGeometry);
}
QtCamDevice *Camera::device() const {
return m_dev;
}
bool Camera::setMode(const Camera::CameraMode& mode) {
if (m_mode == mode) {
return true;
}
if (!m_dev) {
return false;
}
m_mode = mode;
if (m_dev->isRunning()) {
applyMode();
}
return true;
}
Camera::CameraMode Camera::mode() {
return m_mode;
}
bool Camera::start() {
if (!m_dev) {
return false;
}
if (!applyMode()) {
return false;
}
return m_dev->start();
}
bool Camera::stop(bool force) {
if (m_dev) {
return m_dev->stop(force);
}
return true;
}
bool Camera::isIdle() {
return m_dev ? m_dev->isIdle() : true;
}
bool Camera::isRunning() {
return m_dev ? m_dev->isRunning() : false;
}
bool Camera::applyMode() {
if (m_mode == Camera::UnknownMode) {
return false;
}
if (m_mode == Camera::VideoMode && m_dev->activeMode() != m_dev->videoMode()) {
m_dev->videoMode()->activate();
}
else if (m_mode == Camera::ImageMode && m_dev->activeMode() != m_dev->imageMode()) {
m_dev->imageMode()->activate();
}
return true;
}
QString Camera::imageSuffix() const {
return m_cam->config()->imageSuffix();
}
QString Camera::videoSuffix() const {
return m_cam->config()->videoSuffix();
}
Notifications *Camera::notifications() const {
return m_notifications->notifications();
}
void Camera::setNotifications(Notifications *notifications) {
if (m_notifications->setNotifications(notifications)) {
if (Sounds *s = dynamic_cast<Sounds *>(notifications)) {
s->setConfig(m_cam->config());
s->reload();
}
emit notificationsChanged();
}
}
QRectF Camera::renderArea() const {
return m_vf->renderArea();
}
QSizeF Camera::videoResolution() const {
return m_vf->videoResolution();
}
void Camera::resetCapabilities() {
QtCamDevice *dev = device();
delete m_zoom;
m_zoom = new Zoom(dev, this);
emit zoomChanged();
delete m_flash;
m_flash = new Flash(dev, this);
emit flashChanged();
delete m_scene;
m_scene = new Scene(dev, this);
emit sceneChanged();
delete m_evComp;
m_evComp = new EvComp(dev, this);
emit evCompChanged();
delete m_whiteBalance;
m_whiteBalance = new WhiteBalance(dev, this);
emit whiteBalanceChanged();
delete m_colorTone;
m_colorTone = new ColorTone(dev, this);
emit colorToneChanged();
delete m_iso;
m_iso = new Iso(dev, this);
emit isoChanged();
delete m_exposure;
m_exposure = new Exposure(dev, this);
emit exposureChanged();
delete m_aperture;
m_aperture = new Aperture(dev, this);
emit apertureChanged();
delete m_noiseReduction;
m_noiseReduction = new NoiseReduction(dev, this);
emit noiseReductionChanged();
delete m_flickerReduction;
m_flickerReduction = new FlickerReduction(dev, this);
emit flickerReductionChanged();
delete m_focus;
m_focus = new Focus(dev, this);
emit focusChanged();
delete m_autoFocus;
m_autoFocus = new AutoFocus(dev, this);
emit autoFocusChanged();
delete m_videoMute;
m_videoMute = new VideoMute(dev, this);
emit videoMuteChanged();
delete m_videoTorch;
m_videoTorch = new VideoTorch(dev, this);
emit videoTorchChanged();
}
Zoom *Camera::zoom() const {
return m_zoom;
}
Flash *Camera::flash() const {
return m_flash;
}
Scene *Camera::scene() const {
return m_scene;
}
EvComp *Camera::evComp() const {
return m_evComp;
}
WhiteBalance *Camera::whiteBalance() const {
return m_whiteBalance;
}
ColorTone *Camera::colorTone() const {
return m_colorTone;
}
Iso *Camera::iso() const {
return m_iso;
}
Exposure *Camera::exposure() const {
return m_exposure;
}
Aperture *Camera::aperture() const {
return m_aperture;
}
NoiseReduction *Camera::noiseReduction() const {
return m_noiseReduction;
}
FlickerReduction *Camera::flickerReduction() const {
return m_flickerReduction;
}
Focus *Camera::focus() const {
return m_focus;
}
AutoFocus *Camera::autoFocus() const {
return m_autoFocus;
}
VideoMute *Camera::videoMute() const {
return m_videoMute;
}
VideoTorch *Camera::videoTorch() const {
return m_videoTorch;
}
bool Camera::isRenderingEnabled() const {
return m_vf->isRenderingEnabled();
}
void Camera::setRenderingEnabled(bool enabled) {
m_vf->setRenderingEnabled(enabled);
}
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
const string FEATURES2D_DIR = "features2d";
const string IMAGE_FILENAME = "tsukuba.png";
/****************************************************************************************\
* Test for KeyPoint *
\****************************************************************************************/
class CV_FeatureDetectorKeypointsTest : public cvtest::BaseTest
{
public:
CV_FeatureDetectorKeypointsTest(const Ptr<FeatureDetector>& _detector) :
detector(_detector) {}
protected:
virtual void run(int)
{
cv::initModule_features2d();
CV_Assert(!detector.empty());
string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME;
// Read the test image.
Mat image = imread(imgFilename);
if(image.empty())
{
ts->printf(cvtest::TS::LOG, "Image %s can not be read.\n", imgFilename.c_str());
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);
return;
}
vector<KeyPoint> keypoints;
detector->detect(image, keypoints);
if(keypoints.empty())
{
ts->printf(cvtest::TS::LOG, "Detector can't find keypoints in image.\n");
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return;
}
Rect r(0, 0, image.cols, image.rows);
for(size_t i = 0; i < keypoints.size(); i++)
{
const KeyPoint& kp = keypoints[i];
if(!r.contains(kp.pt))
{
ts->printf(cvtest::TS::LOG, "KeyPoint::pt is out of image (x=%f, y=%f).\n", kp.pt.x, kp.pt.y);
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return;
}
if(kp.size <= 0.f)
{
ts->printf(cvtest::TS::LOG, "KeyPoint::size is not positive (%f).\n", kp.size);
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return;
}
if((kp.angle < 0.f && kp.angle != -1.f) || kp.angle >= 360.f)
{
ts->printf(cvtest::TS::LOG, "KeyPoint::angle is out of range [0, 360). It's %f.\n", kp.angle);
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return;
}
}
ts->set_failed_test_info(cvtest::TS::OK);
}
Ptr<FeatureDetector> detector;
};
// Registration of tests
TEST(Features2d_Detector_Keypoints_FAST, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.FAST"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_HARRIS, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.HARRIS"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_GFTT, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.GFTT"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_MSER, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.MSER"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_ORB, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.ORB"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_Star, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.STAR"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_Dense, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.Dense"));
test.safe_run();
}
<commit_msg>add more test to BRISK<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
const string FEATURES2D_DIR = "features2d";
const string IMAGE_FILENAME = "tsukuba.png";
/****************************************************************************************\
* Test for KeyPoint *
\****************************************************************************************/
class CV_FeatureDetectorKeypointsTest : public cvtest::BaseTest
{
public:
CV_FeatureDetectorKeypointsTest(const Ptr<FeatureDetector>& _detector) :
detector(_detector) {}
protected:
virtual void run(int)
{
cv::initModule_features2d();
CV_Assert(!detector.empty());
string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME;
// Read the test image.
Mat image = imread(imgFilename);
if(image.empty())
{
ts->printf(cvtest::TS::LOG, "Image %s can not be read.\n", imgFilename.c_str());
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);
return;
}
vector<KeyPoint> keypoints;
detector->detect(image, keypoints);
if(keypoints.empty())
{
ts->printf(cvtest::TS::LOG, "Detector can't find keypoints in image.\n");
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return;
}
Rect r(0, 0, image.cols, image.rows);
for(size_t i = 0; i < keypoints.size(); i++)
{
const KeyPoint& kp = keypoints[i];
if(!r.contains(kp.pt))
{
ts->printf(cvtest::TS::LOG, "KeyPoint::pt is out of image (x=%f, y=%f).\n", kp.pt.x, kp.pt.y);
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return;
}
if(kp.size <= 0.f)
{
ts->printf(cvtest::TS::LOG, "KeyPoint::size is not positive (%f).\n", kp.size);
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return;
}
if((kp.angle < 0.f && kp.angle != -1.f) || kp.angle >= 360.f)
{
ts->printf(cvtest::TS::LOG, "KeyPoint::angle is out of range [0, 360). It's %f.\n", kp.angle);
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return;
}
}
ts->set_failed_test_info(cvtest::TS::OK);
}
Ptr<FeatureDetector> detector;
};
// Registration of tests
TEST(Features2d_Detector_Keypoints_BRISK, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.BRISK"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_FAST, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.FAST"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_HARRIS, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.HARRIS"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_GFTT, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.GFTT"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_MSER, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.MSER"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_ORB, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.ORB"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_Star, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.STAR"));
test.safe_run();
}
TEST(Features2d_Detector_Keypoints_Dense, validation)
{
CV_FeatureDetectorKeypointsTest test(Algorithm::create<FeatureDetector>("Feature2D.Dense"));
test.safe_run();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-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 "chrome/common/resource_bundle.h"
#include <atlbase.h>
#include "base/file_util.h"
#include "base/gfx/png_decoder.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/resource_util.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/win_util.h"
#include "SkBitmap.h"
using namespace std;
ResourceBundle *ResourceBundle::g_shared_instance_ = NULL;
// Returns the flags that should be passed to LoadLibraryEx.
DWORD GetDataDllLoadFlags() {
if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA)
return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;
return LOAD_LIBRARY_AS_DATAFILE;
}
/* static */
void ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) {
DCHECK(g_shared_instance_ == NULL) << "ResourceBundle initialized twice";
g_shared_instance_ = new ResourceBundle();
g_shared_instance_->LoadLocaleResources(pref_locale);
}
/* static */
void ResourceBundle::CleanupSharedInstance() {
if (g_shared_instance_) {
delete g_shared_instance_;
g_shared_instance_ = NULL;
}
}
/* static */
ResourceBundle& ResourceBundle::GetSharedInstance() {
// Must call InitSharedInstance before this function.
CHECK(g_shared_instance_ != NULL);
return *g_shared_instance_;
}
ResourceBundle::ResourceBundle()
: locale_resources_dll_(NULL),
theme_dll_(NULL) {
}
ResourceBundle::~ResourceBundle() {
for (SkImageMap::iterator i = skia_images_.begin();
i != skia_images_.end(); i++) {
delete i->second;
}
skia_images_.clear();
if (locale_resources_dll_) {
BOOL rv = FreeLibrary(locale_resources_dll_);
DCHECK(rv);
}
if (theme_dll_) {
BOOL rv = FreeLibrary(theme_dll_);
DCHECK(rv);
}
}
void ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) {
DCHECK(NULL == locale_resources_dll_) << "locale dll already loaded";
const std::wstring& locale_path = GetLocaleDllPath(pref_locale);
if (locale_path.empty()) {
// It's possible that there are no locale dlls found, in which case we just
// return.
NOTREACHED();
return;
}
// The dll should only have resources, not executable code.
locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL,
GetDataDllLoadFlags());
DCHECK(locale_resources_dll_ != NULL) << "unable to load generated resources";
}
std::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) {
std::wstring locale_path;
PathService::Get(chrome::DIR_LOCALES, &locale_path);
const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale);
if (app_locale.empty())
return app_locale;
file_util::AppendToPath(&locale_path, app_locale + L".dll");
return locale_path;
}
void ResourceBundle::LoadThemeResources() {
DCHECK(NULL == theme_dll_) << "theme dll already loaded";
std::wstring theme_dll_path;
PathService::Get(chrome::DIR_THEMES, &theme_dll_path);
file_util::AppendToPath(&theme_dll_path, L"default.dll");
// The dll should only have resources, not executable code.
theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL,
GetDataDllLoadFlags());
DCHECK(theme_dll_ != NULL) << "unable to load " << theme_dll_path;
}
/* static */
SkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) {
void* data_ptr = NULL;
size_t data_size;
bool success = base::GetDataResourceFromModule(dll_inst, resource_id,
&data_ptr, &data_size);
if (!success)
return NULL;
unsigned char* data = static_cast<unsigned char*>(data_ptr);
// Decode the PNG.
vector<unsigned char> png_data;
int image_width;
int image_height;
if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA,
&png_data, &image_width, &image_height)) {
NOTREACHED() << "Unable to decode theme resource " << resource_id;
return NULL;
}
return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data,
image_width,
image_height);
}
SkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) {
AutoLock lock_scope(lock_);
SkImageMap::const_iterator found = skia_images_.find(resource_id);
SkBitmap* bitmap = NULL;
// If not found load and store the image
if (found == skia_images_.end()) {
// Load the image
bitmap = LoadBitmap(theme_dll_, resource_id);
// We did not find the bitmap in the theme DLL, try the current one.
if (!bitmap)
bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id);
skia_images_[resource_id] = bitmap;
} else {
bitmap = found->second;
}
// This bitmap will be returned when a bitmap is requested that can not be
// found. The data inside is lazily initialized, so users must lock and
static SkBitmap* empty_bitmap = NULL;
// Handle the case where loading the bitmap failed.
if (!bitmap) {
LOG(WARNING) << "Unable to load bitmap with id " << resource_id;
if (!empty_bitmap) {
empty_bitmap = new SkBitmap();
}
return empty_bitmap;
}
return bitmap;
}
bool ResourceBundle::LoadImageResourceBytes(int resource_id,
vector<unsigned char>* bytes) {
return LoadModuleResourceBytes(theme_dll_, resource_id, bytes);
}
bool ResourceBundle::LoadDataResourceBytes(int resource_id,
vector<unsigned char>* bytes) {
return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(),
resource_id, bytes);
}
bool ResourceBundle::LoadModuleResourceBytes(
HINSTANCE module,
int resource_id,
std::vector<unsigned char>* bytes) {
void* data_ptr;
size_t data_size;
if (base::GetDataResourceFromModule(module, resource_id, &data_ptr,
&data_size)) {
bytes->resize(data_size);
memcpy(&(bytes->front()), data_ptr, data_size);
return true;
} else {
return false;
}
}
HICON ResourceBundle::LoadThemeIcon(int icon_id) {
return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id));
}
std::string ResourceBundle::GetDataResource(int resource_id) {
return GetRawDataResource(resource_id).as_string();
}
StringPiece ResourceBundle::GetRawDataResource(int resource_id) {
void* data_ptr;
size_t data_size;
if (base::GetDataResourceFromModule(
_AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size))
return StringPiece(static_cast<const char*>(data_ptr), data_size);
return StringPiece();
}
// Loads and returns the global accelerators from the current module.
HACCEL ResourceBundle::GetGlobalAccelerators() {
return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(),
MAKEINTRESOURCE(IDR_MAINFRAME));
}
// Loads and returns a cursor from the current module.
HCURSOR ResourceBundle::LoadCursor(int cursor_id) {
return ::LoadCursor(_AtlBaseModule.GetModuleInstance(),
MAKEINTRESOURCE(cursor_id));
}
std::wstring ResourceBundle::GetLocalizedString(int message_id) {
// If for some reason we were unable to load a resource dll, return an empty
// string (better than crashing).
if (!locale_resources_dll_)
return std::wstring();
DCHECK(IS_INTRESOURCE(message_id));
// Get a reference directly to the string resource.
HINSTANCE hinstance = locale_resources_dll_;
const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance,
message_id);
if (!image) {
// Fall back on the current module (shouldn't be any strings here except
// in unittests).
image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(),
message_id);
if (!image) {
NOTREACHED() << "unable to find resource: " << message_id;
return std::wstring();
}
}
// Copy into a wstring and return.
return std::wstring(image->achString, image->nLength);
}
void ResourceBundle::LoadFontsIfNecessary() {
AutoLock lock_scope(lock_);
if (!base_font_.get()) {
base_font_.reset(new ChromeFont());
small_font_.reset(new ChromeFont());
*small_font_ = base_font_->DeriveFont(-2);
medium_font_.reset(new ChromeFont());
*medium_font_ = base_font_->DeriveFont(3);
medium_bold_font_.reset(new ChromeFont());
*medium_bold_font_ =
base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD);
large_font_.reset(new ChromeFont());
*large_font_ = base_font_->DeriveFont(8);
web_font_.reset(new ChromeFont());
*web_font_ = base_font_->DeriveFont(1,
base_font_->style() | ChromeFont::WEB);
}
}
ChromeFont ResourceBundle::GetFont(FontStyle style) {
LoadFontsIfNecessary();
switch(style) {
case SmallFont:
return *small_font_;
case MediumFont:
return *medium_font_;
case MediumBoldFont:
return *medium_bold_font_;
case LargeFont:
return *large_font_;
case WebFont:
return *web_font_;
default:
return *base_font_;
}
}
<commit_msg>Revert 2243 to check if it's why the startup test regressed.<commit_after>// Copyright (c) 2006-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 "chrome/common/resource_bundle.h"
#include <atlbase.h>
#include "base/file_util.h"
#include "base/gfx/png_decoder.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/resource_util.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/win_util.h"
#include "SkBitmap.h"
using namespace std;
ResourceBundle *ResourceBundle::g_shared_instance_ = NULL;
// Returns the flags that should be passed to LoadLibraryEx.
DWORD GetDataDllLoadFlags() {
if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA)
return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;
return 0;
}
/* static */
void ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) {
DCHECK(g_shared_instance_ == NULL) << "ResourceBundle initialized twice";
g_shared_instance_ = new ResourceBundle();
g_shared_instance_->LoadLocaleResources(pref_locale);
}
/* static */
void ResourceBundle::CleanupSharedInstance() {
if (g_shared_instance_) {
delete g_shared_instance_;
g_shared_instance_ = NULL;
}
}
/* static */
ResourceBundle& ResourceBundle::GetSharedInstance() {
// Must call InitSharedInstance before this function.
CHECK(g_shared_instance_ != NULL);
return *g_shared_instance_;
}
ResourceBundle::ResourceBundle()
: locale_resources_dll_(NULL),
theme_dll_(NULL) {
}
ResourceBundle::~ResourceBundle() {
for (SkImageMap::iterator i = skia_images_.begin();
i != skia_images_.end(); i++) {
delete i->second;
}
skia_images_.clear();
if (locale_resources_dll_) {
BOOL rv = FreeLibrary(locale_resources_dll_);
DCHECK(rv);
}
if (theme_dll_) {
BOOL rv = FreeLibrary(theme_dll_);
DCHECK(rv);
}
}
void ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) {
DCHECK(NULL == locale_resources_dll_) << "locale dll already loaded";
const std::wstring& locale_path = GetLocaleDllPath(pref_locale);
if (locale_path.empty()) {
// It's possible that there are no locale dlls found, in which case we just
// return.
NOTREACHED();
return;
}
// The dll should only have resources, not executable code.
locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL,
GetDataDllLoadFlags());
DCHECK(locale_resources_dll_ != NULL) << "unable to load generated resources";
}
std::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) {
std::wstring locale_path;
PathService::Get(chrome::DIR_LOCALES, &locale_path);
const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale);
if (app_locale.empty())
return app_locale;
file_util::AppendToPath(&locale_path, app_locale + L".dll");
return locale_path;
}
void ResourceBundle::LoadThemeResources() {
DCHECK(NULL == theme_dll_) << "theme dll already loaded";
std::wstring theme_dll_path;
PathService::Get(chrome::DIR_THEMES, &theme_dll_path);
file_util::AppendToPath(&theme_dll_path, L"default.dll");
// The dll should only have resources, not executable code.
theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL,
GetDataDllLoadFlags());
DCHECK(theme_dll_ != NULL) << "unable to load " << theme_dll_path;
}
/* static */
SkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) {
void* data_ptr = NULL;
size_t data_size;
bool success = base::GetDataResourceFromModule(dll_inst, resource_id,
&data_ptr, &data_size);
if (!success)
return NULL;
unsigned char* data = static_cast<unsigned char*>(data_ptr);
// Decode the PNG.
vector<unsigned char> png_data;
int image_width;
int image_height;
if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA,
&png_data, &image_width, &image_height)) {
NOTREACHED() << "Unable to decode theme resource " << resource_id;
return NULL;
}
return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data,
image_width,
image_height);
}
SkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) {
AutoLock lock_scope(lock_);
SkImageMap::const_iterator found = skia_images_.find(resource_id);
SkBitmap* bitmap = NULL;
// If not found load and store the image
if (found == skia_images_.end()) {
// Load the image
bitmap = LoadBitmap(theme_dll_, resource_id);
// We did not find the bitmap in the theme DLL, try the current one.
if (!bitmap)
bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id);
skia_images_[resource_id] = bitmap;
} else {
bitmap = found->second;
}
// This bitmap will be returned when a bitmap is requested that can not be
// found. The data inside is lazily initialized, so users must lock and
static SkBitmap* empty_bitmap = NULL;
// Handle the case where loading the bitmap failed.
if (!bitmap) {
LOG(WARNING) << "Unable to load bitmap with id " << resource_id;
if (!empty_bitmap) {
empty_bitmap = new SkBitmap();
}
return empty_bitmap;
}
return bitmap;
}
bool ResourceBundle::LoadImageResourceBytes(int resource_id,
vector<unsigned char>* bytes) {
return LoadModuleResourceBytes(theme_dll_, resource_id, bytes);
}
bool ResourceBundle::LoadDataResourceBytes(int resource_id,
vector<unsigned char>* bytes) {
return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(),
resource_id, bytes);
}
bool ResourceBundle::LoadModuleResourceBytes(
HINSTANCE module,
int resource_id,
std::vector<unsigned char>* bytes) {
void* data_ptr;
size_t data_size;
if (base::GetDataResourceFromModule(module, resource_id, &data_ptr,
&data_size)) {
bytes->resize(data_size);
memcpy(&(bytes->front()), data_ptr, data_size);
return true;
} else {
return false;
}
}
HICON ResourceBundle::LoadThemeIcon(int icon_id) {
return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id));
}
std::string ResourceBundle::GetDataResource(int resource_id) {
return GetRawDataResource(resource_id).as_string();
}
StringPiece ResourceBundle::GetRawDataResource(int resource_id) {
void* data_ptr;
size_t data_size;
if (base::GetDataResourceFromModule(
_AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size))
return StringPiece(static_cast<const char*>(data_ptr), data_size);
return StringPiece();
}
// Loads and returns the global accelerators from the current module.
HACCEL ResourceBundle::GetGlobalAccelerators() {
return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(),
MAKEINTRESOURCE(IDR_MAINFRAME));
}
// Loads and returns a cursor from the current module.
HCURSOR ResourceBundle::LoadCursor(int cursor_id) {
return ::LoadCursor(_AtlBaseModule.GetModuleInstance(),
MAKEINTRESOURCE(cursor_id));
}
std::wstring ResourceBundle::GetLocalizedString(int message_id) {
// If for some reason we were unable to load a resource dll, return an empty
// string (better than crashing).
if (!locale_resources_dll_)
return std::wstring();
DCHECK(IS_INTRESOURCE(message_id));
// Get a reference directly to the string resource.
HINSTANCE hinstance = locale_resources_dll_;
const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance,
message_id);
if (!image) {
// Fall back on the current module (shouldn't be any strings here except
// in unittests).
image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(),
message_id);
if (!image) {
NOTREACHED() << "unable to find resource: " << message_id;
return std::wstring();
}
}
// Copy into a wstring and return.
return std::wstring(image->achString, image->nLength);
}
void ResourceBundle::LoadFontsIfNecessary() {
AutoLock lock_scope(lock_);
if (!base_font_.get()) {
base_font_.reset(new ChromeFont());
small_font_.reset(new ChromeFont());
*small_font_ = base_font_->DeriveFont(-2);
medium_font_.reset(new ChromeFont());
*medium_font_ = base_font_->DeriveFont(3);
medium_bold_font_.reset(new ChromeFont());
*medium_bold_font_ =
base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD);
large_font_.reset(new ChromeFont());
*large_font_ = base_font_->DeriveFont(8);
web_font_.reset(new ChromeFont());
*web_font_ = base_font_->DeriveFont(1,
base_font_->style() | ChromeFont::WEB);
}
}
ChromeFont ResourceBundle::GetFont(FontStyle style) {
LoadFontsIfNecessary();
switch(style) {
case SmallFont:
return *small_font_;
case MediumFont:
return *medium_font_;
case MediumBoldFont:
return *medium_bold_font_;
case LargeFont:
return *large_font_;
case WebFont:
return *web_font_;
default:
return *base_font_;
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------
// Implementation of the Event Time class
// for the Event Data Summary class
// This class contains the Event Time
// as estimated by the TOF combinatorial algorithm
// Origin: A.De Caro, decaro@lsa.infn.it
//-----------------------------------------------------------------
//---- standard headers ----
#include "Riostream.h"
//---- Root headers --------
#include "TArrayF.h"
#include "TArrayI.h"
//---- AliRoot headers -----
#include "AliTOFHeader.h"
ClassImp(AliTOFHeader)
//--------------------------------------------------------------------------
AliTOFHeader::AliTOFHeader() :
TObject(),
fDefaultEventTimeValue(0.),
fDefaultEventTimeRes(0.),
fNbins(0),
fEventTimeValues(new TArrayF(1)),
fEventTimeRes(new TArrayF(1)),
fNvalues(new TArrayI(1)),
fTOFtimeResolution(0.),
fT0spread(0.)
{
//
// Default Constructor
//
}
//--------------------------------------------------------------------------
AliTOFHeader::AliTOFHeader(Float_t defEvTime, Float_t defResEvTime,
Int_t nDifPbins, Float_t *times, Float_t *res,
Int_t *nPbin, Float_t tofTimeRes, Float_t t0spread) :
TObject(),
fDefaultEventTimeValue(defEvTime),
fDefaultEventTimeRes(defResEvTime),
fNbins(nDifPbins),
fEventTimeValues(new TArrayF(nDifPbins)),
fEventTimeRes(new TArrayF(nDifPbins)),
fNvalues(new TArrayI(nDifPbins)),
fTOFtimeResolution(tofTimeRes),
fT0spread(t0spread)
{
//
// Constructor for vertex Z from pixels
//
for (Int_t ii=0; ii<fNbins; ii++) {
fEventTimeValues->SetAt(times[ii],ii);
fEventTimeRes->SetAt(res[ii],ii);
fNvalues->SetAt(nPbin[ii],ii);
}
}
//--------------------------------------------------------------------------
AliTOFHeader::AliTOFHeader(const AliTOFHeader &source):
TObject(source),
fDefaultEventTimeValue(source.fDefaultEventTimeValue),
fDefaultEventTimeRes(source.fDefaultEventTimeRes),
fNbins(source.fNbins),
fEventTimeValues(new TArrayF(fNbins)),
fEventTimeRes(new TArrayF(fNbins)),
fNvalues(new TArrayI(fNbins)),
fTOFtimeResolution(source.fTOFtimeResolution),
fT0spread(source.fT0spread)
{
//
// Copy constructor
//
for(Int_t i=0;i<fNbins;i++) {
fEventTimeValues->SetAt(source.fEventTimeValues->GetAt(i),i);
fEventTimeRes->SetAt(source.fEventTimeRes->GetAt(i),i);
fNvalues->SetAt(source.fNvalues->GetAt(i),i);
}
}
//--------------------------------------------------------------------------
AliTOFHeader &AliTOFHeader::operator=(const AliTOFHeader &source){
//
// assignment operator
//
if(&source != this){
TObject::operator=(source);
fDefaultEventTimeValue=source.fDefaultEventTimeValue;
fDefaultEventTimeRes=source.fDefaultEventTimeRes;
fNbins=source.fNbins;
fEventTimeValues=new TArrayF(fNbins);
fEventTimeRes=new TArrayF(fNbins);
fNvalues=new TArrayI(fNbins);
fTOFtimeResolution=source.fTOFtimeResolution;
fT0spread=source.fT0spread;
for(Int_t i=0;i<fNbins;i++) {
fEventTimeValues->SetAt(source.fEventTimeValues->GetAt(i),i);
fEventTimeRes->SetAt(source.fEventTimeRes->GetAt(i),i);
fNvalues->SetAt(source.fNvalues->GetAt(i),i);
}
}
return *this;
}
//--------------------------------------------------------------------------
void AliTOFHeader::Copy(TObject &obj) const {
// this overwrites the virtual TOBject::Copy()
// to allow run time copying without casting
// in AliESDEvent
if(this==&obj)return;
AliTOFHeader *robj = dynamic_cast<AliTOFHeader*>(&obj);
if(!robj)return; // not an AliTOFHeader
*robj = *this;
}
//--------------------------------------------------------------------------
AliTOFHeader::~AliTOFHeader()
{
fEventTimeValues->Reset();
fEventTimeRes->Reset();
fNvalues->Reset();
delete fEventTimeValues;
delete fEventTimeRes;
delete fNvalues;
}
//--------------------------------------------------------------------------
void AliTOFHeader::SetNbins(Int_t nbins)
{
//
//
//
fNbins=nbins;
fEventTimeValues->Set(nbins);
fEventTimeRes->Set(nbins);
fNvalues->Set(nbins);
}
//--------------------------------------------------------------------------
void AliTOFHeader::SetEventTimeValues(TArrayF *arr)
{
//
//
//
fNbins=arr->GetSize();
fEventTimeValues->Set(arr->GetSize());
for (Int_t ii=0; ii<arr->GetSize(); ii++)
fEventTimeValues->SetAt(arr->GetAt(ii),ii);
}
//--------------------------------------------------------------------------
void AliTOFHeader::SetEventTimeRes(TArrayF *arr)
{
//
//
//
fNbins=arr->GetSize();
fEventTimeRes->Set(arr->GetSize());
for (Int_t ii=0; ii<arr->GetSize(); ii++)
fEventTimeRes->SetAt(arr->GetAt(ii),ii);
}
//--------------------------------------------------------------------------
void AliTOFHeader::SetNvalues(TArrayI *arr)
{
//
//
//
fNbins=arr->GetSize();
fNvalues->Set(arr->GetSize());
for (Int_t ii=0; ii<arr->GetSize(); ii++)
fNvalues->SetAt(arr->GetAt(ii),ii);
}
<commit_msg>removing leak<commit_after>/**************************************************************************
* Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------
// Implementation of the Event Time class
// for the Event Data Summary class
// This class contains the Event Time
// as estimated by the TOF combinatorial algorithm
// Origin: A.De Caro, decaro@lsa.infn.it
//-----------------------------------------------------------------
//---- standard headers ----
#include "Riostream.h"
//---- Root headers --------
#include "TArrayF.h"
#include "TArrayI.h"
//---- AliRoot headers -----
#include "AliTOFHeader.h"
ClassImp(AliTOFHeader)
//--------------------------------------------------------------------------
AliTOFHeader::AliTOFHeader() :
TObject(),
fDefaultEventTimeValue(0.),
fDefaultEventTimeRes(0.),
fNbins(0),
fEventTimeValues(0),
fEventTimeRes(0),
fNvalues(0),
fTOFtimeResolution(0.),
fT0spread(0.)
{
//
// Default Constructor
//
}
//--------------------------------------------------------------------------
AliTOFHeader::AliTOFHeader(Float_t defEvTime, Float_t defResEvTime,
Int_t nDifPbins, Float_t *times, Float_t *res,
Int_t *nPbin, Float_t tofTimeRes, Float_t t0spread) :
TObject(),
fDefaultEventTimeValue(defEvTime),
fDefaultEventTimeRes(defResEvTime),
fNbins(nDifPbins),
fEventTimeValues(new TArrayF(nDifPbins)),
fEventTimeRes(new TArrayF(nDifPbins)),
fNvalues(new TArrayI(nDifPbins)),
fTOFtimeResolution(tofTimeRes),
fT0spread(t0spread)
{
//
// Constructor for vertex Z from pixels
//
for (Int_t ii=0; ii<fNbins; ii++) {
fEventTimeValues->SetAt(times[ii],ii);
fEventTimeRes->SetAt(res[ii],ii);
fNvalues->SetAt(nPbin[ii],ii);
}
}
//--------------------------------------------------------------------------
AliTOFHeader::AliTOFHeader(const AliTOFHeader &source):
TObject(source),
fDefaultEventTimeValue(source.fDefaultEventTimeValue),
fDefaultEventTimeRes(source.fDefaultEventTimeRes),
fNbins(source.fNbins),
fEventTimeValues(new TArrayF(fNbins)),
fEventTimeRes(new TArrayF(fNbins)),
fNvalues(new TArrayI(fNbins)),
fTOFtimeResolution(source.fTOFtimeResolution),
fT0spread(source.fT0spread)
{
//
// Copy constructor
//
for(Int_t i=0;i<fNbins;i++) {
fEventTimeValues->SetAt(source.fEventTimeValues->GetAt(i),i);
fEventTimeRes->SetAt(source.fEventTimeRes->GetAt(i),i);
fNvalues->SetAt(source.fNvalues->GetAt(i),i);
}
}
//--------------------------------------------------------------------------
AliTOFHeader &AliTOFHeader::operator=(const AliTOFHeader &source){
//
// assignment operator
//
if(&source != this){
TObject::operator=(source);
fDefaultEventTimeValue=source.fDefaultEventTimeValue;
fDefaultEventTimeRes=source.fDefaultEventTimeRes;
fNbins=source.fNbins;
fEventTimeValues=new TArrayF(fNbins);
fEventTimeRes=new TArrayF(fNbins);
fNvalues=new TArrayI(fNbins);
fTOFtimeResolution=source.fTOFtimeResolution;
fT0spread=source.fT0spread;
for(Int_t i=0;i<fNbins;i++) {
fEventTimeValues->SetAt(source.fEventTimeValues->GetAt(i),i);
fEventTimeRes->SetAt(source.fEventTimeRes->GetAt(i),i);
fNvalues->SetAt(source.fNvalues->GetAt(i),i);
}
}
return *this;
}
//--------------------------------------------------------------------------
void AliTOFHeader::Copy(TObject &obj) const {
// this overwrites the virtual TOBject::Copy()
// to allow run time copying without casting
// in AliESDEvent
if(this==&obj)return;
AliTOFHeader *robj = dynamic_cast<AliTOFHeader*>(&obj);
if(!robj)return; // not an AliTOFHeader
*robj = *this;
}
//--------------------------------------------------------------------------
AliTOFHeader::~AliTOFHeader()
{
delete fEventTimeValues;
delete fEventTimeRes;
delete fNvalues;
}
//--------------------------------------------------------------------------
void AliTOFHeader::SetNbins(Int_t nbins)
{
//
//
//
fNbins=nbins;
fEventTimeValues->Set(nbins);
fEventTimeRes->Set(nbins);
fNvalues->Set(nbins);
}
//--------------------------------------------------------------------------
void AliTOFHeader::SetEventTimeValues(TArrayF *arr)
{
//
//
//
fNbins=arr->GetSize();
fEventTimeValues->Set(arr->GetSize());
for (Int_t ii=0; ii<arr->GetSize(); ii++)
fEventTimeValues->SetAt(arr->GetAt(ii),ii);
}
//--------------------------------------------------------------------------
void AliTOFHeader::SetEventTimeRes(TArrayF *arr)
{
//
//
//
fNbins=arr->GetSize();
fEventTimeRes->Set(arr->GetSize());
for (Int_t ii=0; ii<arr->GetSize(); ii++)
fEventTimeRes->SetAt(arr->GetAt(ii),ii);
}
//--------------------------------------------------------------------------
void AliTOFHeader::SetNvalues(TArrayI *arr)
{
//
//
//
fNbins=arr->GetSize();
fNvalues->Set(arr->GetSize());
for (Int_t ii=0; ii<arr->GetSize(); ii++)
fNvalues->SetAt(arr->GetAt(ii),ii);
}
<|endoftext|>
|
<commit_before>#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Pass.h"
#include "llvm/DataLayout.h"
#include "llvm/Support/raw_ostream.h"
#include "accept.h"
using namespace llvm;
namespace {
struct AcceptAA : public ImmutablePass, public AliasAnalysis {
static char ID;
AcceptAA() : ImmutablePass(ID) {
initializeAcceptAAPass(*PassRegistry::getPassRegistry());
}
virtual const char *getPassName() const {
return "ACCEPT approximate alias analysis";
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AliasAnalysis::getAnalysisUsage(AU);
// dependencies?
}
virtual void initializePass() {
InitializeAliasAnalysis(this);
}
virtual AliasResult alias(const Location &LocA, const Location &LocB) {
const Instruction *instA = dyn_cast<Instruction>(LocA.Ptr);
const Instruction *instB = dyn_cast<Instruction>(LocB.Ptr);
if (instA && instB && isApprox(instA) && isApprox(instB)) {
return NoAlias;
}
// Delegate to other alias analyses.
return AliasAnalysis::alias(LocA, LocB);
}
// This required bit works around C++'s multiple inheritance weirdness.
// Casting this to AliasAnalysis* gets the correct vtable for those calls.
virtual void *getAdjustedAnalysisPointer(const void *ID) {
if (ID == &AliasAnalysis::ID)
return (AliasAnalysis*)this;
return this;
}
};
}
char AcceptAA::ID = 0;
INITIALIZE_AG_PASS(AcceptAA, AliasAnalysis, "acceptaa",
"ACCEPT approximate alias analysis",
false, true, false)
ImmutablePass *llvm::createAcceptAAPass() { return new AcceptAA(); }
<commit_msg>(commented-out) alias analysis debugging<commit_after>#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Pass.h"
#include "llvm/DataLayout.h"
#include "llvm/Support/raw_ostream.h"
#include "accept.h"
using namespace llvm;
namespace {
struct AcceptAA : public ImmutablePass, public AliasAnalysis {
static char ID;
AcceptAA() : ImmutablePass(ID) {
initializeAcceptAAPass(*PassRegistry::getPassRegistry());
}
virtual const char *getPassName() const {
return "ACCEPT approximate alias analysis";
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AliasAnalysis::getAnalysisUsage(AU);
// dependencies?
}
virtual void initializePass() {
InitializeAliasAnalysis(this);
}
virtual AliasResult alias(const Location &LocA, const Location &LocB) {
const Instruction *instA = dyn_cast<Instruction>(LocA.Ptr);
const Instruction *instB = dyn_cast<Instruction>(LocB.Ptr);
if (instA && instB && isApprox(instA) && isApprox(instB)) {
return NoAlias;
}
/* DEBUG
else if (instA && instB) {
errs() << "instructions:\n";
instA->dump();
instB->dump();
} else {
const GlobalValue *gvA = dyn_cast<GlobalValue>(LocA.Ptr);
const GlobalValue *gvB = dyn_cast<GlobalValue>(LocB.Ptr);
if (gvA && gvB) {
errs() << "global values:\n";
gvA->dump();
gvB->dump();
}
}
*/
// Delegate to other alias analyses.
return AliasAnalysis::alias(LocA, LocB);
}
// This required bit works around C++'s multiple inheritance weirdness.
// Casting this to AliasAnalysis* gets the correct vtable for those calls.
virtual void *getAdjustedAnalysisPointer(const void *ID) {
if (ID == &AliasAnalysis::ID)
return (AliasAnalysis*)this;
return this;
}
};
}
char AcceptAA::ID = 0;
INITIALIZE_AG_PASS(AcceptAA, AliasAnalysis, "acceptaa",
"ACCEPT approximate alias analysis",
false, true, false)
ImmutablePass *llvm::createAcceptAAPass() { return new AcceptAA(); }
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SelectionMultiplex.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-07-06 10:17:43 $
*
* 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 INCLUDED_COMPHELPER_SELECTION_MULTIPLEX_HXX
#define INCLUDED_COMPHELPER_SELECTION_MULTIPLEX_HXX
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONCHANGELISTENER_HPP_
#include <com/sun/star/view/XSelectionChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_
#include <com/sun/star/view/XSelectionSupplier.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
//=========================================================================
//= selection helper classes
//=========================================================================
//.........................................................................
namespace comphelper
{
//.........................................................................
class OSelectionChangeMultiplexer;
//==================================================================
//= OSelectionChangeListener
//==================================================================
/// simple listener adapter for selections
class COMPHELPER_DLLPUBLIC OSelectionChangeListener
{
friend class OSelectionChangeMultiplexer;
OSelectionChangeMultiplexer* m_pAdapter;
::osl::Mutex& m_rMutex;
public:
OSelectionChangeListener(::osl::Mutex& _rMutex)
: m_pAdapter(NULL), m_rMutex(_rMutex) { }
virtual ~OSelectionChangeListener();
virtual void _selectionChanged( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException) = 0;
virtual void _disposing(const ::com::sun::star::lang::EventObject& _rSource) throw( ::com::sun::star::uno::RuntimeException);
protected:
/** If the derivee also owns the mutex which we know as reference, then call this within your
derivee's dtor.
*/
void disposeAdapter();
// pseudo-private. Making it private now could break compatibility
void setAdapter( OSelectionChangeMultiplexer* _pAdapter );
};
//==================================================================
//= OSelectionChangeMultiplexer
//==================================================================
/// multiplexer for selection changes
class COMPHELPER_DLLPUBLIC OSelectionChangeMultiplexer :public cppu::WeakImplHelper1< ::com::sun::star::view::XSelectionChangeListener>
{
friend class OSelectionChangeListener;
::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionSupplier> m_xSet;
OSelectionChangeListener* m_pListener;
sal_Int32 m_nLockCount;
sal_Bool m_bListening : 1;
sal_Bool m_bAutoSetRelease : 1;
OSelectionChangeMultiplexer(const OSelectionChangeMultiplexer&);
OSelectionChangeMultiplexer& operator=(const OSelectionChangeMultiplexer&);
protected:
virtual ~OSelectionChangeMultiplexer();
public:
OSelectionChangeMultiplexer(OSelectionChangeListener* _pListener, const ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionSupplier>& _rxSet, sal_Bool _bAutoReleaseSet = sal_True);
// XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException);
// XSelectionChangeListener
virtual void SAL_CALL selectionChanged( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException);
/// incremental lock
void lock();
/// incremental unlock
void unlock();
/// get the lock count
sal_Int32 locked() const { return m_nLockCount; }
void dispose();
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // INCLUDED_COMPHELPER_SELECTION_MULTIPLEX_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.96); FILE MERGED 2008/04/01 15:05:17 thb 1.2.96.3: #i85898# Stripping all external header guards 2008/04/01 12:26:23 thb 1.2.96.2: #i85898# Stripping all external header guards 2008/03/31 12:19:26 rt 1.2.96.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: SelectionMultiplex.hxx,v $
* $Revision: 1.3 $
*
* 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 INCLUDED_COMPHELPER_SELECTION_MULTIPLEX_HXX
#define INCLUDED_COMPHELPER_SELECTION_MULTIPLEX_HXX
#include <com/sun/star/view/XSelectionChangeListener.hpp>
#include <com/sun/star/view/XSelectionSupplier.hpp>
#include <cppuhelper/implbase1.hxx>
#include "comphelper/comphelperdllapi.h"
//=========================================================================
//= selection helper classes
//=========================================================================
//.........................................................................
namespace comphelper
{
//.........................................................................
class OSelectionChangeMultiplexer;
//==================================================================
//= OSelectionChangeListener
//==================================================================
/// simple listener adapter for selections
class COMPHELPER_DLLPUBLIC OSelectionChangeListener
{
friend class OSelectionChangeMultiplexer;
OSelectionChangeMultiplexer* m_pAdapter;
::osl::Mutex& m_rMutex;
public:
OSelectionChangeListener(::osl::Mutex& _rMutex)
: m_pAdapter(NULL), m_rMutex(_rMutex) { }
virtual ~OSelectionChangeListener();
virtual void _selectionChanged( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException) = 0;
virtual void _disposing(const ::com::sun::star::lang::EventObject& _rSource) throw( ::com::sun::star::uno::RuntimeException);
protected:
/** If the derivee also owns the mutex which we know as reference, then call this within your
derivee's dtor.
*/
void disposeAdapter();
// pseudo-private. Making it private now could break compatibility
void setAdapter( OSelectionChangeMultiplexer* _pAdapter );
};
//==================================================================
//= OSelectionChangeMultiplexer
//==================================================================
/// multiplexer for selection changes
class COMPHELPER_DLLPUBLIC OSelectionChangeMultiplexer :public cppu::WeakImplHelper1< ::com::sun::star::view::XSelectionChangeListener>
{
friend class OSelectionChangeListener;
::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionSupplier> m_xSet;
OSelectionChangeListener* m_pListener;
sal_Int32 m_nLockCount;
sal_Bool m_bListening : 1;
sal_Bool m_bAutoSetRelease : 1;
OSelectionChangeMultiplexer(const OSelectionChangeMultiplexer&);
OSelectionChangeMultiplexer& operator=(const OSelectionChangeMultiplexer&);
protected:
virtual ~OSelectionChangeMultiplexer();
public:
OSelectionChangeMultiplexer(OSelectionChangeListener* _pListener, const ::com::sun::star::uno::Reference< ::com::sun::star::view::XSelectionSupplier>& _rxSet, sal_Bool _bAutoReleaseSet = sal_True);
// XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException);
// XSelectionChangeListener
virtual void SAL_CALL selectionChanged( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException);
/// incremental lock
void lock();
/// incremental unlock
void unlock();
/// get the lock count
sal_Int32 locked() const { return m_nLockCount; }
void dispose();
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // INCLUDED_COMPHELPER_SELECTION_MULTIPLEX_HXX
<|endoftext|>
|
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */
#define GRANARY_INTERNAL
#include "granary/arch/base.h"
#include "granary/base/base.h"
#include "granary/base/string.h"
#include "granary/cfg/basic_block.h"
#include "granary/cfg/instruction.h"
#include "granary/arch/decode.h"
#include "granary/arch/x86-64/instruction.h"
#include "granary/arch/x86-64/mangle/early.h"
#include "granary/breakpoint.h"
namespace granary {
namespace arch {
// Decoder state that sets the mode to 64-bit.
extern xed_state_t XED_STATE;
// Initialize the instruction decoder.
InstructionDecoder::InstructionDecoder(void) {}
// Decode an instruction, and update the program counter by reference to point
// to the next logical instruction. Returns `true` iff the instruction was
// successfully decoded.
bool InstructionDecoder::DecodeNext(DecodedBasicBlock *block,
Instruction *instr, AppPC *pc) {
*pc = DecodeInternal(block, instr, *pc);
return nullptr != *pc;
}
// Decode an x86 instruction into an instruction IR.
bool InstructionDecoder::Decode(DecodedBasicBlock *block,
Instruction *instr, AppPC pc) {
return nullptr != DecodeInternal(block, instr, pc);
}
namespace {
// Returns true if an instruction might cross a page boundary.
static bool InstructionMightCrossPageBoundary(PC pc) {
auto pc_ptr = reinterpret_cast<uintptr_t>(pc);
auto max_pc_ptr = pc_ptr + XED_MAX_INSTRUCTION_BYTES;
return (pc_ptr / GRANARY_ARCH_PAGE_FRAME_SIZE) !=
(max_pc_ptr / GRANARY_ARCH_PAGE_FRAME_SIZE);
}
// Try decoding and instruction without reading in `XED_MAX_INSTRUCTION_BYTES`
// byte (i.e. try decoding as a 1-byte instruction, then as a 2-byte, etc.).
static xed_error_enum_t TryDecodeBytes(xed_decoded_inst_t *xedd, PC pc) {
auto decode_status = XED_ERROR_LAST;
for (auto i = 1U; i <= XED_MAX_INSTRUCTION_BYTES; ++i) {
decode_status = xed_decode(xedd, pc, XED_MAX_INSTRUCTION_BYTES);
if (XED_ERROR_NONE == decode_status) {
break;
}
}
return decode_status;
}
// Decode some bytes into a `xed_decoded_inst_t` instruction.
static xed_error_enum_t DecodeBytes(xed_decoded_inst_t *xedd, PC pc) {
xed_decoded_inst_zero_set_mode(xedd, &XED_STATE);
xed_decoded_inst_set_input_chip(xedd, XED_CHIP_INVALID);
if (GRANARY_UNLIKELY(InstructionMightCrossPageBoundary(pc))) {
return TryDecodeBytes(xedd, pc);
} else {
return xed_decode(xedd, pc, XED_MAX_INSTRUCTION_BYTES);
}
}
// Pull out a register operand from the XED instruction.
static void ConvertRegisterOperand(Instruction *instr, Operand *instr_op,
const xed_decoded_inst_t *xedd,
xed_operand_enum_t op_name) {
auto reg = xed_decoded_inst_get_reg(xedd, op_name);
instr_op->type = XED_ENCODER_OPERAND_TYPE_REG;
instr_op->reg.DecodeFromNative(reg);
instr_op->width = static_cast<int8_t>(xed_get_register_width_bits64(reg));
// Update the stack pointer tracking.
if (GRANARY_UNLIKELY(instr_op->reg.IsStackPointer())) {
if (instr_op->IsRead()) {
instr->reads_from_stack_pointer = true;
}
if (instr_op->IsWrite()) {
instr->writes_to_stack_pointer = true;
}
}
}
static PC NextDecodedAddress(const Instruction *instr) {
return instr->decoded_pc + instr->decoded_length;
}
// Get a PC-relative address.
static PC GetPCRelativeBranchTarget(const Instruction *instr,
const xed_decoded_inst_t *xedd) {
auto disp = xed_decoded_inst_get_branch_displacement(xedd);
return NextDecodedAddress(instr) + disp;
}
// Get a PC-relative memory address.
static const void *GetPCRelativeMemoryAddress(const Instruction *instr,
const xed_decoded_inst_t *xedd,
unsigned index) {
auto disp = xed_decoded_inst_get_memory_displacement(xedd, index);
return reinterpret_cast<const void *>(NextDecodedAddress(instr) + disp);
}
// Pull out a PC-relative branch target from the XED instruction.
static void ConvertRelativeBranch(Instruction *instr, Operand *instr_op,
const xed_decoded_inst_t *xedd) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_BRDISP;
instr_op->width = arch::ADDRESS_WIDTH_BITS;
instr_op->branch_target.as_pc = GetPCRelativeBranchTarget(instr, xedd);
}
// Returns true if a register is the instruction pointer.
static bool RegIsInstructionPointer(xed_reg_enum_t reg) {
return XED_REG_RIP == reg || XED_REG_EIP == reg || XED_REG_IP == reg;
}
// Convert a memory operand into an `Operand`.
static void ConvertMemoryOperand(Instruction *instr, Operand *instr_op,
const xed_decoded_inst_t *xedd,
unsigned index) {
auto is_sticky = instr->has_prefix_rep || instr->has_prefix_repne ||
XED_ICLASS_XLAT == instr->iclass;
auto disp = xed_decoded_inst_get_memory_displacement(xedd, index);
auto scale = xed_decoded_inst_get_scale(xedd, index);
auto segment_reg = xed_decoded_inst_get_seg_reg(xedd, index);
auto base_reg = xed_decoded_inst_get_base_reg(xedd, index);
auto index_reg = xed_decoded_inst_get_index_reg(xedd, index);
if (XED_REG_INVALID == index_reg && XED_REG_INVALID == segment_reg && !disp) {
instr_op->reg.DecodeFromNative(static_cast<int>(base_reg));
} else {
instr_op->mem.disp = static_cast<int32_t>(disp);
instr_op->mem.reg_base = base_reg;
instr_op->mem.reg_index = index_reg;
instr_op->mem.reg_seg = segment_reg;
instr_op->mem.scale = static_cast<uint8_t>(scale);
instr_op->is_compound = true;
}
instr_op->type = XED_ENCODER_OPERAND_TYPE_MEM;
instr_op->width = static_cast<int8_t>(xed3_operand_get_mem_width(xedd) * 8);
instr_op->is_sticky = instr_op->is_sticky || is_sticky;
instr_op->is_effective_address = XED_ICLASS_LEA == instr->iclass;
}
// Pull out an effective address from a LEA_GPRv_AGEN instruction. We actually
// treat the effective address as either an immediate or as a base/disp, unlike
// the expected XED_OPERAND_AGEN, and at encoding time convert back to an AGEN.
//
// Note: XED_OPERAND_AGEN's memory operand index is 0. See docs for function
// `xed_agen`.
static void ConvertBaseDisp(Instruction *instr, Operand *instr_op,
const xed_decoded_inst_t *xedd, unsigned index) {
if (RegIsInstructionPointer(xed_decoded_inst_get_base_reg(xedd, index))) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_PTR; // Overloaded meaning.
instr_op->addr.as_ptr = GetPCRelativeMemoryAddress(instr, xedd, index);
instr_op->width = static_cast<int8_t>(
xed3_operand_get_mem_width(xedd) * 8); // Width of addressed memory.
} else {
ConvertMemoryOperand(instr, instr_op, xedd, index);
}
}
// Pull out an immediate operand from the XED instruction.
static void ConvertImmediateOperand(Operand *instr_op,
const xed_decoded_inst_t *xedd,
xed_operand_enum_t op_name) {
if (XED_OPERAND_IMM0SIGNED == op_name) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_SIMM0;
instr_op->imm.as_int = static_cast<intptr_t>(
xed_decoded_inst_get_signed_immediate(xedd));
} else if (XED_OPERAND_IMM0 == op_name) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_IMM0;
instr_op->imm.as_uint = xed_decoded_inst_get_unsigned_immediate(xedd);
} else if (XED_OPERAND_IMM1 == op_name ||
XED_OPERAND_IMM1_BYTES == op_name) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_IMM1;
instr_op->imm.as_uint = static_cast<uintptr_t>(
xed_decoded_inst_get_second_immediate(xedd));
}
instr_op->width = static_cast<int8_t>(
xed_decoded_inst_get_immediate_width_bits(xedd));
}
// Convert a `xed_operand_t` into an `Operand`. This operates on explicit
// operands only, and when an increments `instr->num_ops` when a new explicit
// operand is found.
static bool ConvertDecodedOperand(Instruction *instr,
const xed_decoded_inst_t *xedd,
unsigned op_num) {
auto xedi = xed_decoded_inst_inst(xedd);
auto op = xed_inst_operand(xedi, op_num);
auto iform = xed_decoded_inst_get_iform_enum(xedd);
bool is_explicit = XED_OPVIS_EXPLICIT == xed_operand_operand_visibility(op) ||
IsAmbiguousOperand(instr->iclass, iform, op_num);
if (!is_explicit) {
return false;
}
auto op_name = xed_operand_name(op);
auto op_type = xed_operand_type(op);
auto instr_op = &(instr->ops[op_num]);
instr_op->rw = xed_operand_rw(op);
instr_op->is_sticky = !is_explicit;
instr_op->is_explicit = true;
if (xed_operand_is_register(op_name)) {
ConvertRegisterOperand(instr, instr_op, xedd, op_name);
} else if (XED_OPERAND_RELBR == op_name) {
ConvertRelativeBranch(instr, instr_op, xedd);
} else if (XED_OPERAND_MEM0 == op_name) {
ConvertBaseDisp(instr, instr_op, xedd, 0);
} else if (XED_OPERAND_MEM1 == op_name) {
ConvertBaseDisp(instr, instr_op, xedd, 1);
} else if (XED_OPERAND_TYPE_IMM == op_type ||
XED_OPERAND_TYPE_IMM_CONST == op_type) {
ConvertImmediateOperand(instr_op, xedd, op_name);
} else {
// Ignore `XED_OPERAND_AGEN`, which is only for LEA.
instr_op->type = XED_ENCODER_OPERAND_TYPE_INVALID;
GRANARY_ASSERT(false); // TODO(pag): Implement this!
}
++instr->num_explicit_ops;
return true;
}
// Convert the operands of a `xed_decoded_inst_t` to `Operand` types.
static void ConvertDecodedOperands(Instruction *instr,
const xed_decoded_inst_t *xedd,
unsigned num_ops) {
for (auto o = 0U; o < num_ops; ++o) {
if (!ConvertDecodedOperand(instr, xedd, o)) {
break;
}
}
}
// Get the prefixes out of the instruction; however, ignore branch hint
// prefixes.
static void ConvertDecodedPrefixes(Instruction *instr,
const xed_decoded_inst_t *xedd) {
instr->has_prefix_rep = xed_operand_values_has_rep_prefix(xedd);
instr->has_prefix_repne = xed_operand_values_has_repne_prefix(xedd);
instr->has_prefix_br_hint_taken = xed_operand_values_branch_taken_hint(xedd);
instr->has_prefix_br_hint_not_taken = \
xed_operand_values_branch_not_taken_hint(xedd);
}
// Convert a `xed_decoded_inst_t` into an `Instruction`.
static void ConvertDecodedInstruction(Instruction *instr,
const xed_decoded_inst_t *xedd,
AppPC pc) {
auto xedi = xed_decoded_inst_inst(xedd);
memset(instr, 0, sizeof *instr);
instr->decoded_pc = pc;
instr->iclass = xed_decoded_inst_get_iclass(xedd);
instr->category = xed_decoded_inst_get_category(xedd);
instr->decoded_length = static_cast<uint8_t>(
xed_decoded_inst_get_length(xedd));
ConvertDecodedPrefixes(instr, xedd);
instr->is_atomic = xed_operand_values_get_atomic(xedd);
instr->effective_operand_width = static_cast<int8_t>(
xed_decoded_inst_get_operand_width(xedd));
ConvertDecodedOperands(instr, xedd, xed_inst_noperands(xedi));
instr->AnalyzeStackUsage();
}
} // namespace
// Decode an x86-64 instruction into a Granary `Instruction`, by first going
// through XED's `xed_decoded_inst_t` IR.
AppPC InstructionDecoder::DecodeInternal(DecodedBasicBlock *block,
Instruction *instr, AppPC pc) {
if (pc) {
xed_decoded_inst_t xedd;
if (XED_ERROR_NONE == DecodeBytes(&xedd, pc)) {
ConvertDecodedInstruction(instr, &xedd, pc);
auto next_pc = pc + instr->decoded_length;
MangleDecodedInstruction(block, instr);
return next_pc;
}
}
return nullptr;
}
} // namespace arch
} // namespace granary
<commit_msg>Made it so that the decoder of memory ops recognizes a different form of simple base/disp mem op.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */
#define GRANARY_INTERNAL
#include "granary/arch/base.h"
#include "granary/base/base.h"
#include "granary/base/string.h"
#include "granary/cfg/basic_block.h"
#include "granary/cfg/instruction.h"
#include "granary/arch/decode.h"
#include "granary/arch/x86-64/instruction.h"
#include "granary/arch/x86-64/mangle/early.h"
#include "granary/breakpoint.h"
namespace granary {
namespace arch {
// Decoder state that sets the mode to 64-bit.
extern xed_state_t XED_STATE;
// Initialize the instruction decoder.
InstructionDecoder::InstructionDecoder(void) {}
// Decode an instruction, and update the program counter by reference to point
// to the next logical instruction. Returns `true` iff the instruction was
// successfully decoded.
bool InstructionDecoder::DecodeNext(DecodedBasicBlock *block,
Instruction *instr, AppPC *pc) {
*pc = DecodeInternal(block, instr, *pc);
return nullptr != *pc;
}
// Decode an x86 instruction into an instruction IR.
bool InstructionDecoder::Decode(DecodedBasicBlock *block,
Instruction *instr, AppPC pc) {
return nullptr != DecodeInternal(block, instr, pc);
}
namespace {
// Returns true if an instruction might cross a page boundary.
static bool InstructionMightCrossPageBoundary(PC pc) {
auto pc_ptr = reinterpret_cast<uintptr_t>(pc);
auto max_pc_ptr = pc_ptr + XED_MAX_INSTRUCTION_BYTES;
return (pc_ptr / GRANARY_ARCH_PAGE_FRAME_SIZE) !=
(max_pc_ptr / GRANARY_ARCH_PAGE_FRAME_SIZE);
}
// Try decoding and instruction without reading in `XED_MAX_INSTRUCTION_BYTES`
// byte (i.e. try decoding as a 1-byte instruction, then as a 2-byte, etc.).
static xed_error_enum_t TryDecodeBytes(xed_decoded_inst_t *xedd, PC pc) {
auto decode_status = XED_ERROR_LAST;
for (auto i = 1U; i <= XED_MAX_INSTRUCTION_BYTES; ++i) {
decode_status = xed_decode(xedd, pc, XED_MAX_INSTRUCTION_BYTES);
if (XED_ERROR_NONE == decode_status) {
break;
}
}
return decode_status;
}
// Decode some bytes into a `xed_decoded_inst_t` instruction.
static xed_error_enum_t DecodeBytes(xed_decoded_inst_t *xedd, PC pc) {
xed_decoded_inst_zero_set_mode(xedd, &XED_STATE);
xed_decoded_inst_set_input_chip(xedd, XED_CHIP_INVALID);
if (GRANARY_UNLIKELY(InstructionMightCrossPageBoundary(pc))) {
return TryDecodeBytes(xedd, pc);
} else {
return xed_decode(xedd, pc, XED_MAX_INSTRUCTION_BYTES);
}
}
// Pull out a register operand from the XED instruction.
static void ConvertRegisterOperand(Instruction *instr, Operand *instr_op,
const xed_decoded_inst_t *xedd,
xed_operand_enum_t op_name) {
auto reg = xed_decoded_inst_get_reg(xedd, op_name);
instr_op->type = XED_ENCODER_OPERAND_TYPE_REG;
instr_op->reg.DecodeFromNative(reg);
instr_op->width = static_cast<int8_t>(xed_get_register_width_bits64(reg));
// Update the stack pointer tracking.
if (GRANARY_UNLIKELY(instr_op->reg.IsStackPointer())) {
if (instr_op->IsRead()) {
instr->reads_from_stack_pointer = true;
}
if (instr_op->IsWrite()) {
instr->writes_to_stack_pointer = true;
}
}
}
static PC NextDecodedAddress(const Instruction *instr) {
return instr->decoded_pc + instr->decoded_length;
}
// Get a PC-relative address.
static PC GetPCRelativeBranchTarget(const Instruction *instr,
const xed_decoded_inst_t *xedd) {
auto disp = xed_decoded_inst_get_branch_displacement(xedd);
return NextDecodedAddress(instr) + disp;
}
// Get a PC-relative memory address.
static const void *GetPCRelativeMemoryAddress(const Instruction *instr,
const xed_decoded_inst_t *xedd,
unsigned index) {
auto disp = xed_decoded_inst_get_memory_displacement(xedd, index);
return reinterpret_cast<const void *>(NextDecodedAddress(instr) + disp);
}
// Pull out a PC-relative branch target from the XED instruction.
static void ConvertRelativeBranch(Instruction *instr, Operand *instr_op,
const xed_decoded_inst_t *xedd) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_BRDISP;
instr_op->width = arch::ADDRESS_WIDTH_BITS;
instr_op->branch_target.as_pc = GetPCRelativeBranchTarget(instr, xedd);
}
// Returns true if a register is the instruction pointer.
static bool RegIsInstructionPointer(xed_reg_enum_t reg) {
return XED_REG_RIP == reg || XED_REG_EIP == reg || XED_REG_IP == reg;
}
// Convert a memory operand into an `Operand`.
static void ConvertMemoryOperand(Instruction *instr, Operand *instr_op,
const xed_decoded_inst_t *xedd,
unsigned index) {
auto is_sticky = instr->has_prefix_rep || instr->has_prefix_repne ||
XED_ICLASS_XLAT == instr->iclass;
auto disp = xed_decoded_inst_get_memory_displacement(xedd, index);
auto scale = xed_decoded_inst_get_scale(xedd, index);
auto segment_reg = xed_decoded_inst_get_seg_reg(xedd, index);
auto base_reg = xed_decoded_inst_get_base_reg(xedd, index);
auto index_reg = xed_decoded_inst_get_index_reg(xedd, index);
if (XED_REG_INVALID == segment_reg &&
((XED_REG_INVALID == index_reg && !disp) ||
(XED_REG_INVALID == base_reg && 1 == disp))) {
instr_op->reg.DecodeFromNative(static_cast<int>(base_reg));
} else {
instr_op->mem.disp = static_cast<int32_t>(disp);
instr_op->mem.reg_base = base_reg;
instr_op->mem.reg_index = index_reg;
instr_op->mem.reg_seg = segment_reg;
instr_op->mem.scale = static_cast<uint8_t>(scale);
instr_op->is_compound = true;
}
instr_op->type = XED_ENCODER_OPERAND_TYPE_MEM;
instr_op->width = static_cast<int8_t>(xed3_operand_get_mem_width(xedd) * 8);
instr_op->is_sticky = instr_op->is_sticky || is_sticky;
instr_op->is_effective_address = XED_ICLASS_LEA == instr->iclass;
}
// Pull out an effective address from a LEA_GPRv_AGEN instruction. We actually
// treat the effective address as either an immediate or as a base/disp, unlike
// the expected XED_OPERAND_AGEN, and at encoding time convert back to an AGEN.
//
// Note: XED_OPERAND_AGEN's memory operand index is 0. See docs for function
// `xed_agen`.
static void ConvertBaseDisp(Instruction *instr, Operand *instr_op,
const xed_decoded_inst_t *xedd, unsigned index) {
if (RegIsInstructionPointer(xed_decoded_inst_get_base_reg(xedd, index))) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_PTR; // Overloaded meaning.
instr_op->addr.as_ptr = GetPCRelativeMemoryAddress(instr, xedd, index);
instr_op->width = static_cast<int8_t>(
xed3_operand_get_mem_width(xedd) * 8); // Width of addressed memory.
} else {
ConvertMemoryOperand(instr, instr_op, xedd, index);
}
}
// Pull out an immediate operand from the XED instruction.
static void ConvertImmediateOperand(Operand *instr_op,
const xed_decoded_inst_t *xedd,
xed_operand_enum_t op_name) {
if (XED_OPERAND_IMM0SIGNED == op_name) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_SIMM0;
instr_op->imm.as_int = static_cast<intptr_t>(
xed_decoded_inst_get_signed_immediate(xedd));
} else if (XED_OPERAND_IMM0 == op_name) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_IMM0;
instr_op->imm.as_uint = xed_decoded_inst_get_unsigned_immediate(xedd);
} else if (XED_OPERAND_IMM1 == op_name ||
XED_OPERAND_IMM1_BYTES == op_name) {
instr_op->type = XED_ENCODER_OPERAND_TYPE_IMM1;
instr_op->imm.as_uint = static_cast<uintptr_t>(
xed_decoded_inst_get_second_immediate(xedd));
}
instr_op->width = static_cast<int8_t>(
xed_decoded_inst_get_immediate_width_bits(xedd));
}
// Convert a `xed_operand_t` into an `Operand`. This operates on explicit
// operands only, and when an increments `instr->num_ops` when a new explicit
// operand is found.
static bool ConvertDecodedOperand(Instruction *instr,
const xed_decoded_inst_t *xedd,
unsigned op_num) {
auto xedi = xed_decoded_inst_inst(xedd);
auto op = xed_inst_operand(xedi, op_num);
auto iform = xed_decoded_inst_get_iform_enum(xedd);
bool is_explicit = XED_OPVIS_EXPLICIT == xed_operand_operand_visibility(op) ||
IsAmbiguousOperand(instr->iclass, iform, op_num);
if (!is_explicit) {
return false;
}
auto op_name = xed_operand_name(op);
auto op_type = xed_operand_type(op);
auto instr_op = &(instr->ops[op_num]);
instr_op->rw = xed_operand_rw(op);
instr_op->is_sticky = !is_explicit;
instr_op->is_explicit = true;
if (xed_operand_is_register(op_name)) {
ConvertRegisterOperand(instr, instr_op, xedd, op_name);
} else if (XED_OPERAND_RELBR == op_name) {
ConvertRelativeBranch(instr, instr_op, xedd);
} else if (XED_OPERAND_MEM0 == op_name) {
ConvertBaseDisp(instr, instr_op, xedd, 0);
} else if (XED_OPERAND_MEM1 == op_name) {
ConvertBaseDisp(instr, instr_op, xedd, 1);
} else if (XED_OPERAND_TYPE_IMM == op_type ||
XED_OPERAND_TYPE_IMM_CONST == op_type) {
ConvertImmediateOperand(instr_op, xedd, op_name);
} else {
// Ignore `XED_OPERAND_AGEN`, which is only for LEA.
instr_op->type = XED_ENCODER_OPERAND_TYPE_INVALID;
GRANARY_ASSERT(false); // TODO(pag): Implement this!
}
++instr->num_explicit_ops;
return true;
}
// Convert the operands of a `xed_decoded_inst_t` to `Operand` types.
static void ConvertDecodedOperands(Instruction *instr,
const xed_decoded_inst_t *xedd,
unsigned num_ops) {
for (auto o = 0U; o < num_ops; ++o) {
if (!ConvertDecodedOperand(instr, xedd, o)) {
break;
}
}
}
// Get the prefixes out of the instruction; however, ignore branch hint
// prefixes.
static void ConvertDecodedPrefixes(Instruction *instr,
const xed_decoded_inst_t *xedd) {
instr->has_prefix_rep = xed_operand_values_has_rep_prefix(xedd);
instr->has_prefix_repne = xed_operand_values_has_repne_prefix(xedd);
instr->has_prefix_br_hint_taken = xed_operand_values_branch_taken_hint(xedd);
instr->has_prefix_br_hint_not_taken = \
xed_operand_values_branch_not_taken_hint(xedd);
}
// Convert a `xed_decoded_inst_t` into an `Instruction`.
static void ConvertDecodedInstruction(Instruction *instr,
const xed_decoded_inst_t *xedd,
AppPC pc) {
auto xedi = xed_decoded_inst_inst(xedd);
memset(instr, 0, sizeof *instr);
instr->decoded_pc = pc;
instr->iclass = xed_decoded_inst_get_iclass(xedd);
instr->category = xed_decoded_inst_get_category(xedd);
instr->decoded_length = static_cast<uint8_t>(
xed_decoded_inst_get_length(xedd));
ConvertDecodedPrefixes(instr, xedd);
instr->is_atomic = xed_operand_values_get_atomic(xedd);
instr->effective_operand_width = static_cast<int8_t>(
xed_decoded_inst_get_operand_width(xedd));
ConvertDecodedOperands(instr, xedd, xed_inst_noperands(xedi));
instr->AnalyzeStackUsage();
}
} // namespace
// Decode an x86-64 instruction into a Granary `Instruction`, by first going
// through XED's `xed_decoded_inst_t` IR.
AppPC InstructionDecoder::DecodeInternal(DecodedBasicBlock *block,
Instruction *instr, AppPC pc) {
if (pc) {
xed_decoded_inst_t xedd;
if (XED_ERROR_NONE == DecodeBytes(&xedd, pc)) {
ConvertDecodedInstruction(instr, &xedd, pc);
auto next_pc = pc + instr->decoded_length;
MangleDecodedInstruction(block, instr);
return next_pc;
}
}
return nullptr;
}
} // namespace arch
} // namespace granary
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef MEMORY_HH_
#define MEMORY_HH_
#include "resource.hh"
#include "bitops.hh"
#include <new>
#include <functional>
#include <vector>
namespace seastar {
/// \defgroup memory-module Memory management
///
/// Functions and classes for managing memory.
///
/// Memory management in seastar consists of the following:
///
/// - Low-level memory management in the \ref memory namespace.
/// - Various smart pointers: \ref shared_ptr, \ref lw_shared_ptr,
/// and \ref foreign_ptr.
/// - zero-copy support: \ref temporary_buffer and \ref deleter.
/// Low-level memory management support
///
/// The \c memory namespace provides functions and classes for interfacing
/// with the seastar memory allocator.
///
/// The seastar memory allocator splits system memory into a pool per
/// logical core (lcore). Memory allocated one an lcore should be freed
/// on the same lcore; failing to do so carries a severe performance
/// penalty. It is possible to share memory with another core, but this
/// should be limited to avoid cache coherency traffic.
namespace memory {
/// \cond internal
#ifdef SEASTAR_OVERRIDE_ALLOCATOR_PAGE_SIZE
#define SEASTAR_INTERNAL_ALLOCATOR_PAGE_SIZE (SEASTAR_OVERRIDE_ALLOCATOR_PAGE_SIZE)
#else
#define SEASTAR_INTERNAL_ALLOCATOR_PAGE_SIZE 4096
#endif
static constexpr size_t page_size = SEASTAR_INTERNAL_ALLOCATOR_PAGE_SIZE;
static constexpr size_t page_bits = log2ceil(page_size);
static constexpr size_t huge_page_size =
#if defined(__x86_64__) || defined(__i386__) || defined(__s390x__) || defined(__zarch__)
1 << 21; // 2M
#elif defined(__PPC__)
1 << 24; // 16M
#else
#error "Huge page size is not defined for this architecture"
#endif
void configure(std::vector<resource::memory> m, bool mbind,
std::experimental::optional<std::string> hugetlbfs_path = {});
void enable_abort_on_allocation_failure();
class disable_abort_on_alloc_failure_temporarily {
public:
disable_abort_on_alloc_failure_temporarily();
~disable_abort_on_alloc_failure_temporarily() noexcept;
};
void set_heap_profiling_enabled(bool);
enum class reclaiming_result {
reclaimed_nothing,
reclaimed_something
};
// Determines when reclaimer can be invoked
enum class reclaimer_scope {
//
// Reclaimer is only invoked in its own fiber. That fiber will be
// given higher priority than regular application fibers.
//
async,
//
// Reclaimer may be invoked synchronously with allocation.
// It may also be invoked in async scope.
//
// Reclaimer may invoke allocation, though it is discouraged because
// the system may be low on memory and such allocations may fail.
// Reclaimers which allocate should be prepared for re-entry.
//
sync
};
class reclaimer {
public:
using reclaim_fn = std::function<reclaiming_result ()>;
private:
reclaim_fn _reclaim;
reclaimer_scope _scope;
public:
// Installs new reclaimer which will be invoked when system is falling
// low on memory. 'scope' determines when reclaimer can be executed.
reclaimer(reclaim_fn reclaim, reclaimer_scope scope = reclaimer_scope::async);
~reclaimer();
reclaiming_result do_reclaim() { return _reclaim(); }
reclaimer_scope scope() const { return _scope; }
};
// Call periodically to recycle objects that were freed
// on cpu other than the one they were allocated on.
//
// Returns @true if any work was actually performed.
bool drain_cross_cpu_freelist();
// We don't want the memory code calling back into the rest of
// the system, so allow the rest of the system to tell the memory
// code how to initiate reclaim.
//
// When memory is low, calling \c hook(fn) will result in fn being called
// in a safe place wrt. allocations.
void set_reclaim_hook(
std::function<void (std::function<void ()>)> hook);
using physical_address = uint64_t;
struct translation {
translation() = default;
translation(physical_address a, size_t s) : addr(a), size(s) {}
physical_address addr = 0;
size_t size = 0;
};
// Translate a virtual address range to a physical range.
//
// Can return a smaller range (in which case the reminder needs
// to be translated again), or a zero sized range in case the
// translation is not known.
translation translate(const void* addr, size_t size);
/// \endcond
class statistics;
/// Capture a snapshot of memory allocation statistics for this lcore.
statistics stats();
/// Memory allocation statistics.
class statistics {
uint64_t _mallocs;
uint64_t _frees;
uint64_t _cross_cpu_frees;
size_t _total_memory;
size_t _free_memory;
uint64_t _reclaims;
private:
statistics(uint64_t mallocs, uint64_t frees, uint64_t cross_cpu_frees,
uint64_t total_memory, uint64_t free_memory, uint64_t reclaims)
: _mallocs(mallocs), _frees(frees), _cross_cpu_frees(cross_cpu_frees)
, _total_memory(total_memory), _free_memory(free_memory), _reclaims(reclaims) {}
public:
/// Total number of memory allocations calls since the system was started.
uint64_t mallocs() const { return _mallocs; }
/// Total number of memory deallocations calls since the system was started.
uint64_t frees() const { return _frees; }
/// Total number of memory deallocations that occured on a different lcore
/// than the one on which they were allocated.
uint64_t cross_cpu_frees() const { return _cross_cpu_frees; }
/// Total number of objects which were allocated but not freed.
size_t live_objects() const { return mallocs() - frees(); }
/// Total free memory (in bytes)
size_t free_memory() const { return _free_memory; }
/// Total allocated memory (in bytes)
size_t allocated_memory() const { return _total_memory - _free_memory; }
/// Total memory (in bytes)
size_t total_memory() const { return _total_memory; }
/// Number of reclaims performed due to low memory
uint64_t reclaims() const { return _reclaims; }
friend statistics stats();
};
struct memory_layout {
uintptr_t start;
uintptr_t end;
};
// Discover virtual address range used by the allocator on current shard.
// Supported only when seastar allocator is enabled.
memory::memory_layout get_memory_layout();
/// Returns the value of free memory low water mark in bytes.
/// When free memory is below this value, reclaimers are invoked until it goes above again.
size_t min_free_memory();
/// Sets the value of free memory low water mark in memory::page_size units.
void set_min_free_pages(size_t pages);
/// Enable the large allocation warning threshold.
///
/// Warn when allocation above a given threshold are performed.
///
/// \param threshold size (in bytes) above which an allocation will be logged
void set_large_allocation_warning_threshold(size_t threshold);
/// Gets the current large allocation warning threshold.
size_t get_large_allocation_warning_threshold();
/// Disable large allocation warnings.
void disable_large_allocation_warning();
/// Set a different large allocation warning threshold for a scope.
class scoped_large_allocation_warning_threshold {
size_t _old_threshold;
public:
explicit scoped_large_allocation_warning_threshold(size_t threshold)
: _old_threshold(get_large_allocation_warning_threshold()) {
set_large_allocation_warning_threshold(threshold);
}
scoped_large_allocation_warning_threshold(const scoped_large_allocation_warning_threshold&) = delete;
scoped_large_allocation_warning_threshold(scoped_large_allocation_warning_threshold&& x) = delete;
~scoped_large_allocation_warning_threshold() {
if (_old_threshold) {
set_large_allocation_warning_threshold(_old_threshold);
}
}
void operator=(const scoped_large_allocation_warning_threshold&) const = delete;
void operator=(scoped_large_allocation_warning_threshold&&) = delete;
};
/// Disable large allocation warnings for a scope.
class scoped_large_allocation_warning_disable {
size_t _old_threshold;
public:
scoped_large_allocation_warning_disable()
: _old_threshold(get_large_allocation_warning_threshold()) {
disable_large_allocation_warning();
}
scoped_large_allocation_warning_disable(const scoped_large_allocation_warning_disable&) = delete;
scoped_large_allocation_warning_disable(scoped_large_allocation_warning_disable&& x) = delete;
~scoped_large_allocation_warning_disable() {
if (_old_threshold) {
set_large_allocation_warning_threshold(_old_threshold);
}
}
void operator=(const scoped_large_allocation_warning_disable&) const = delete;
void operator=(scoped_large_allocation_warning_disable&&) = delete;
};
}
class with_alignment {
size_t _align;
public:
with_alignment(size_t align) : _align(align) {}
size_t alignment() const { return _align; }
};
}
void* operator new(size_t size, seastar::with_alignment wa);
void* operator new[](size_t size, seastar::with_alignment wa);
void operator delete(void* ptr, seastar::with_alignment wa);
void operator delete[](void* ptr, seastar::with_alignment wa);
#endif /* MEMORY_HH_ */
<commit_msg>memory: define huge page size for ARM<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef MEMORY_HH_
#define MEMORY_HH_
#include "resource.hh"
#include "bitops.hh"
#include <new>
#include <functional>
#include <vector>
namespace seastar {
/// \defgroup memory-module Memory management
///
/// Functions and classes for managing memory.
///
/// Memory management in seastar consists of the following:
///
/// - Low-level memory management in the \ref memory namespace.
/// - Various smart pointers: \ref shared_ptr, \ref lw_shared_ptr,
/// and \ref foreign_ptr.
/// - zero-copy support: \ref temporary_buffer and \ref deleter.
/// Low-level memory management support
///
/// The \c memory namespace provides functions and classes for interfacing
/// with the seastar memory allocator.
///
/// The seastar memory allocator splits system memory into a pool per
/// logical core (lcore). Memory allocated one an lcore should be freed
/// on the same lcore; failing to do so carries a severe performance
/// penalty. It is possible to share memory with another core, but this
/// should be limited to avoid cache coherency traffic.
namespace memory {
/// \cond internal
#ifdef SEASTAR_OVERRIDE_ALLOCATOR_PAGE_SIZE
#define SEASTAR_INTERNAL_ALLOCATOR_PAGE_SIZE (SEASTAR_OVERRIDE_ALLOCATOR_PAGE_SIZE)
#else
#define SEASTAR_INTERNAL_ALLOCATOR_PAGE_SIZE 4096
#endif
static constexpr size_t page_size = SEASTAR_INTERNAL_ALLOCATOR_PAGE_SIZE;
static constexpr size_t page_bits = log2ceil(page_size);
static constexpr size_t huge_page_size =
#if defined(__x86_64__) || defined(__i386__) || defined(__s390x__) || defined(__zarch__)
1 << 21; // 2M
#elif defined(__aarch64__)
1 << 21; // 2M
#elif defined(__PPC__)
1 << 24; // 16M
#else
#error "Huge page size is not defined for this architecture"
#endif
void configure(std::vector<resource::memory> m, bool mbind,
std::experimental::optional<std::string> hugetlbfs_path = {});
void enable_abort_on_allocation_failure();
class disable_abort_on_alloc_failure_temporarily {
public:
disable_abort_on_alloc_failure_temporarily();
~disable_abort_on_alloc_failure_temporarily() noexcept;
};
void set_heap_profiling_enabled(bool);
enum class reclaiming_result {
reclaimed_nothing,
reclaimed_something
};
// Determines when reclaimer can be invoked
enum class reclaimer_scope {
//
// Reclaimer is only invoked in its own fiber. That fiber will be
// given higher priority than regular application fibers.
//
async,
//
// Reclaimer may be invoked synchronously with allocation.
// It may also be invoked in async scope.
//
// Reclaimer may invoke allocation, though it is discouraged because
// the system may be low on memory and such allocations may fail.
// Reclaimers which allocate should be prepared for re-entry.
//
sync
};
class reclaimer {
public:
using reclaim_fn = std::function<reclaiming_result ()>;
private:
reclaim_fn _reclaim;
reclaimer_scope _scope;
public:
// Installs new reclaimer which will be invoked when system is falling
// low on memory. 'scope' determines when reclaimer can be executed.
reclaimer(reclaim_fn reclaim, reclaimer_scope scope = reclaimer_scope::async);
~reclaimer();
reclaiming_result do_reclaim() { return _reclaim(); }
reclaimer_scope scope() const { return _scope; }
};
// Call periodically to recycle objects that were freed
// on cpu other than the one they were allocated on.
//
// Returns @true if any work was actually performed.
bool drain_cross_cpu_freelist();
// We don't want the memory code calling back into the rest of
// the system, so allow the rest of the system to tell the memory
// code how to initiate reclaim.
//
// When memory is low, calling \c hook(fn) will result in fn being called
// in a safe place wrt. allocations.
void set_reclaim_hook(
std::function<void (std::function<void ()>)> hook);
using physical_address = uint64_t;
struct translation {
translation() = default;
translation(physical_address a, size_t s) : addr(a), size(s) {}
physical_address addr = 0;
size_t size = 0;
};
// Translate a virtual address range to a physical range.
//
// Can return a smaller range (in which case the reminder needs
// to be translated again), or a zero sized range in case the
// translation is not known.
translation translate(const void* addr, size_t size);
/// \endcond
class statistics;
/// Capture a snapshot of memory allocation statistics for this lcore.
statistics stats();
/// Memory allocation statistics.
class statistics {
uint64_t _mallocs;
uint64_t _frees;
uint64_t _cross_cpu_frees;
size_t _total_memory;
size_t _free_memory;
uint64_t _reclaims;
private:
statistics(uint64_t mallocs, uint64_t frees, uint64_t cross_cpu_frees,
uint64_t total_memory, uint64_t free_memory, uint64_t reclaims)
: _mallocs(mallocs), _frees(frees), _cross_cpu_frees(cross_cpu_frees)
, _total_memory(total_memory), _free_memory(free_memory), _reclaims(reclaims) {}
public:
/// Total number of memory allocations calls since the system was started.
uint64_t mallocs() const { return _mallocs; }
/// Total number of memory deallocations calls since the system was started.
uint64_t frees() const { return _frees; }
/// Total number of memory deallocations that occured on a different lcore
/// than the one on which they were allocated.
uint64_t cross_cpu_frees() const { return _cross_cpu_frees; }
/// Total number of objects which were allocated but not freed.
size_t live_objects() const { return mallocs() - frees(); }
/// Total free memory (in bytes)
size_t free_memory() const { return _free_memory; }
/// Total allocated memory (in bytes)
size_t allocated_memory() const { return _total_memory - _free_memory; }
/// Total memory (in bytes)
size_t total_memory() const { return _total_memory; }
/// Number of reclaims performed due to low memory
uint64_t reclaims() const { return _reclaims; }
friend statistics stats();
};
struct memory_layout {
uintptr_t start;
uintptr_t end;
};
// Discover virtual address range used by the allocator on current shard.
// Supported only when seastar allocator is enabled.
memory::memory_layout get_memory_layout();
/// Returns the value of free memory low water mark in bytes.
/// When free memory is below this value, reclaimers are invoked until it goes above again.
size_t min_free_memory();
/// Sets the value of free memory low water mark in memory::page_size units.
void set_min_free_pages(size_t pages);
/// Enable the large allocation warning threshold.
///
/// Warn when allocation above a given threshold are performed.
///
/// \param threshold size (in bytes) above which an allocation will be logged
void set_large_allocation_warning_threshold(size_t threshold);
/// Gets the current large allocation warning threshold.
size_t get_large_allocation_warning_threshold();
/// Disable large allocation warnings.
void disable_large_allocation_warning();
/// Set a different large allocation warning threshold for a scope.
class scoped_large_allocation_warning_threshold {
size_t _old_threshold;
public:
explicit scoped_large_allocation_warning_threshold(size_t threshold)
: _old_threshold(get_large_allocation_warning_threshold()) {
set_large_allocation_warning_threshold(threshold);
}
scoped_large_allocation_warning_threshold(const scoped_large_allocation_warning_threshold&) = delete;
scoped_large_allocation_warning_threshold(scoped_large_allocation_warning_threshold&& x) = delete;
~scoped_large_allocation_warning_threshold() {
if (_old_threshold) {
set_large_allocation_warning_threshold(_old_threshold);
}
}
void operator=(const scoped_large_allocation_warning_threshold&) const = delete;
void operator=(scoped_large_allocation_warning_threshold&&) = delete;
};
/// Disable large allocation warnings for a scope.
class scoped_large_allocation_warning_disable {
size_t _old_threshold;
public:
scoped_large_allocation_warning_disable()
: _old_threshold(get_large_allocation_warning_threshold()) {
disable_large_allocation_warning();
}
scoped_large_allocation_warning_disable(const scoped_large_allocation_warning_disable&) = delete;
scoped_large_allocation_warning_disable(scoped_large_allocation_warning_disable&& x) = delete;
~scoped_large_allocation_warning_disable() {
if (_old_threshold) {
set_large_allocation_warning_threshold(_old_threshold);
}
}
void operator=(const scoped_large_allocation_warning_disable&) const = delete;
void operator=(scoped_large_allocation_warning_disable&&) = delete;
};
}
class with_alignment {
size_t _align;
public:
with_alignment(size_t align) : _align(align) {}
size_t alignment() const { return _align; }
};
}
void* operator new(size_t size, seastar::with_alignment wa);
void* operator new[](size_t size, seastar::with_alignment wa);
void operator delete(void* ptr, seastar::with_alignment wa);
void operator delete[](void* ptr, seastar::with_alignment wa);
#endif /* MEMORY_HH_ */
<|endoftext|>
|
<commit_before>#include "domain_transition_graph.h"
#include "domain_transition_graph_symb.h"
#include "domain_transition_graph_func.h"
#include "domain_transition_graph_subterm.h"
#include "operator.h"
#include "axiom.h"
#include "variable.h"
#include <algorithm>
#include <cassert>
#include <iostream>
using namespace std;
void build_DTGs(const vector<Variable *> &var_order,
const vector<Operator> &operators,
const vector<Axiom_relational> &axioms_rel,
const vector<Axiom_functional> &axioms_func,
vector<DomainTransitionGraph *> &transition_graphs) {
for(int i = 0; i < var_order.size(); i++) {
Variable v = *var_order[i];
if(v.is_subterm() || v.is_comparison()) {
DomainTransitionGraphSubterm *dtg = new DomainTransitionGraphSubterm(v);
transition_graphs.push_back(dtg);
} else if(v.is_functional()) {
DomainTransitionGraphFunc *dtg = new DomainTransitionGraphFunc(v);
transition_graphs.push_back(dtg);
} else if(v.is_module()) {
cout << "module variable!" << endl;
DomainTransitionGraphModule *dtg = new DomainTransitionGraphModule();
transition_graphs.push_back(dtg);
} else {
DomainTransitionGraphSymb *dtg = new DomainTransitionGraphSymb(v);
transition_graphs.push_back(dtg);
}
}
for(int i = 0; i < operators.size(); i++) {
const Operator &op = operators[i];
const vector<Operator::PrePost> &pre_post_start = op.get_pre_post_start();
const vector<Operator::PrePost> &pre_post_end = op.get_pre_post_end();
vector<std::pair<Operator::PrePost,trans_type> > pre_posts_to_add;
for(int j = 0; j < pre_post_start.size(); ++j) {
pre_posts_to_add.push_back(make_pair(pre_post_start[j],start));
// pre_posts_to_add.push_back(make_pair(Operator::PrePost(
// pre_post_start[j].var, pre_post_start[j].post,
// pre_post_start[j].pre), DomainTransitionGraph::ax_rel));
}
// bool pre_post_overwritten = false;
// for(int j = 0; j < pre_post_end.size(); ++j) {
// for(int k = 0; k < pre_posts_to_add.size(); ++k) {
// if(pre_post_end[j].var == pre_posts_to_add[k].first.var) {
//// // and add additional end transition
//// pre_posts_to_add.push_back(make_pair(Operator::PrePost(
//// pre_posts_to_add[k].first.var, pre_posts_to_add[k].first.post,
//// pre_post_end[j].post), DomainTransitionGraph::ax_rel));
// // compress original transition!
// pre_posts_to_add[k].first.post = pre_post_end[j].post;
// pre_posts_to_add[k].second = end;
// pre_post_overwritten = true;
// break;
// }
// }
// if(!pre_post_overwritten) {
// pre_posts_to_add.push_back(make_pair(pre_post_end[j],end));
// }
// pre_post_overwritten = false;
// }
bool pre_post_overwritten = false;
for(int j = 0; j < pre_post_end.size(); ++j) {
for(int k = 0; k < pre_posts_to_add.size(); ++k) {
if(pre_post_end[j].var == pre_posts_to_add[k].first.var) {
int intermediate_value = pre_posts_to_add[k].first.post;
// compress original transition!
pre_posts_to_add[k].first.post = pre_post_end[j].post;
pre_posts_to_add[k].second = end;
pre_post_overwritten = true;
// If the intermediate value is something meaningful (i.e. unequal to
// <none_of_those>), we add an addtional start transition with the
// intermediate value as target.
if(intermediate_value < pre_posts_to_add[k].first.var->get_range() - 1) {
pre_posts_to_add.push_back(make_pair(Operator::PrePost(
pre_posts_to_add[k].first.var,
pre_posts_to_add[k].first.pre,
intermediate_value), end));
}
break;
}
}
if(!pre_post_overwritten) {
pre_posts_to_add.push_back(make_pair(pre_post_end[j],end));
}
pre_post_overwritten = false;
}
for(int j = 0; j < pre_posts_to_add.size(); j++) {
if(pre_posts_to_add[j].first.pre == pre_posts_to_add[j].first.post)
continue;
const Variable *var = pre_posts_to_add[j].first.var;
assert(var->get_layer() == -1);
int var_level = var->get_level();
if(var_level != -1) {
int pre = pre_posts_to_add[j].first.pre;
int post = pre_posts_to_add[j].first.post;
if(pre != -1) {
transition_graphs[var_level]->addTransition(pre, post, op, i,
pre_posts_to_add[j].second, var_order);
} else {
for(int pre = 0; pre < var->get_range(); pre++)
if(pre != post) {
transition_graphs[var_level]->addTransition(pre, post, op, i,
pre_posts_to_add[j].second, var_order);
}
}
}
}
const vector<Operator::NumericalEffect> &numerical_effs_start =
op.get_numerical_effs_start();
for(int j = 0; j < numerical_effs_start.size(); j++) {
const Variable *var = numerical_effs_start[j].var;
int var_level = var->get_level();
if(var_level != -1) {
int foperator = static_cast<int>(numerical_effs_start[j].fop);
int right_var = numerical_effs_start[j].foperand->get_level();
transition_graphs[var_level]->addTransition(foperator, right_var, op,
i, start, var_order);
}
}
const vector<Operator::NumericalEffect> &numerical_effs_end =
op.get_numerical_effs_end();
for(int j = 0; j < numerical_effs_end.size(); j++) {
const Variable *var = numerical_effs_end[j].var;
int var_level = var->get_level();
if(var_level != -1) {
int foperator = static_cast<int>(numerical_effs_end[j].fop);
int right_var = numerical_effs_end[j].foperand->get_level();
transition_graphs[var_level]->addTransition(foperator, right_var, op,
i, end, var_order);
}
}
}
for(int i = 0; i < axioms_rel.size(); i++) {
const Axiom_relational &ax = axioms_rel[i];
Variable *var = ax.get_effect_var();
int var_level = var->get_level();
assert(var->get_layer()> -1);
assert(var_level != -1);
int old_val = ax.get_old_val();
int new_val = ax.get_effect_val();
transition_graphs[var_level]->addAxRelTransition(old_val, new_val, ax, i);
}
for(int i = 0; i < axioms_func.size(); i++) {
const Axiom_functional &ax = axioms_func[i];
Variable *var = ax.get_effect_var();
if(!var->is_necessary()&&!var->is_used_in_duration_condition())
continue;
int var_level = var->get_level();
assert(var->get_layer()> -1);
Variable* left_var = ax.get_left_var();
Variable* right_var = ax.get_right_var();
DomainTransitionGraphSubterm *dtgs = dynamic_cast<DomainTransitionGraphSubterm*>(transition_graphs[var_level]);
assert(dtgs);
if(var->is_comparison()) {
dtgs->setRelation(left_var, ax.cop, right_var);
} else {
dtgs->setRelation(left_var, ax.fop, right_var);
}
}
for(int i = 0; i < transition_graphs.size(); i++)
transition_graphs[i]->finalize();
}
bool are_DTGs_strongly_connected(
const vector<DomainTransitionGraph*> &transition_graphs) {
bool connected = true;
// no need to test last variable's dtg (highest level variable)
for(int i = 0; i < transition_graphs.size() - 1; i++)
if(!transition_graphs[i]->is_strongly_connected())
connected = false;
return connected;
}
<commit_msg>removed spammy debug output<commit_after>#include "domain_transition_graph.h"
#include "domain_transition_graph_symb.h"
#include "domain_transition_graph_func.h"
#include "domain_transition_graph_subterm.h"
#include "operator.h"
#include "axiom.h"
#include "variable.h"
#include <algorithm>
#include <cassert>
#include <iostream>
using namespace std;
void build_DTGs(const vector<Variable *> &var_order,
const vector<Operator> &operators,
const vector<Axiom_relational> &axioms_rel,
const vector<Axiom_functional> &axioms_func,
vector<DomainTransitionGraph *> &transition_graphs) {
for(int i = 0; i < var_order.size(); i++) {
Variable v = *var_order[i];
if(v.is_subterm() || v.is_comparison()) {
DomainTransitionGraphSubterm *dtg = new DomainTransitionGraphSubterm(v);
transition_graphs.push_back(dtg);
} else if(v.is_functional()) {
DomainTransitionGraphFunc *dtg = new DomainTransitionGraphFunc(v);
transition_graphs.push_back(dtg);
} else if(v.is_module()) {
DomainTransitionGraphModule *dtg = new DomainTransitionGraphModule();
transition_graphs.push_back(dtg);
} else {
DomainTransitionGraphSymb *dtg = new DomainTransitionGraphSymb(v);
transition_graphs.push_back(dtg);
}
}
for(int i = 0; i < operators.size(); i++) {
const Operator &op = operators[i];
const vector<Operator::PrePost> &pre_post_start = op.get_pre_post_start();
const vector<Operator::PrePost> &pre_post_end = op.get_pre_post_end();
vector<std::pair<Operator::PrePost,trans_type> > pre_posts_to_add;
for(int j = 0; j < pre_post_start.size(); ++j) {
pre_posts_to_add.push_back(make_pair(pre_post_start[j],start));
// pre_posts_to_add.push_back(make_pair(Operator::PrePost(
// pre_post_start[j].var, pre_post_start[j].post,
// pre_post_start[j].pre), DomainTransitionGraph::ax_rel));
}
// bool pre_post_overwritten = false;
// for(int j = 0; j < pre_post_end.size(); ++j) {
// for(int k = 0; k < pre_posts_to_add.size(); ++k) {
// if(pre_post_end[j].var == pre_posts_to_add[k].first.var) {
//// // and add additional end transition
//// pre_posts_to_add.push_back(make_pair(Operator::PrePost(
//// pre_posts_to_add[k].first.var, pre_posts_to_add[k].first.post,
//// pre_post_end[j].post), DomainTransitionGraph::ax_rel));
// // compress original transition!
// pre_posts_to_add[k].first.post = pre_post_end[j].post;
// pre_posts_to_add[k].second = end;
// pre_post_overwritten = true;
// break;
// }
// }
// if(!pre_post_overwritten) {
// pre_posts_to_add.push_back(make_pair(pre_post_end[j],end));
// }
// pre_post_overwritten = false;
// }
bool pre_post_overwritten = false;
for(int j = 0; j < pre_post_end.size(); ++j) {
for(int k = 0; k < pre_posts_to_add.size(); ++k) {
if(pre_post_end[j].var == pre_posts_to_add[k].first.var) {
int intermediate_value = pre_posts_to_add[k].first.post;
// compress original transition!
pre_posts_to_add[k].first.post = pre_post_end[j].post;
pre_posts_to_add[k].second = end;
pre_post_overwritten = true;
// If the intermediate value is something meaningful (i.e. unequal to
// <none_of_those>), we add an addtional start transition with the
// intermediate value as target.
if(intermediate_value < pre_posts_to_add[k].first.var->get_range() - 1) {
pre_posts_to_add.push_back(make_pair(Operator::PrePost(
pre_posts_to_add[k].first.var,
pre_posts_to_add[k].first.pre,
intermediate_value), end));
}
break;
}
}
if(!pre_post_overwritten) {
pre_posts_to_add.push_back(make_pair(pre_post_end[j],end));
}
pre_post_overwritten = false;
}
for(int j = 0; j < pre_posts_to_add.size(); j++) {
if(pre_posts_to_add[j].first.pre == pre_posts_to_add[j].first.post)
continue;
const Variable *var = pre_posts_to_add[j].first.var;
assert(var->get_layer() == -1);
int var_level = var->get_level();
if(var_level != -1) {
int pre = pre_posts_to_add[j].first.pre;
int post = pre_posts_to_add[j].first.post;
if(pre != -1) {
transition_graphs[var_level]->addTransition(pre, post, op, i,
pre_posts_to_add[j].second, var_order);
} else {
for(int pre = 0; pre < var->get_range(); pre++)
if(pre != post) {
transition_graphs[var_level]->addTransition(pre, post, op, i,
pre_posts_to_add[j].second, var_order);
}
}
}
}
const vector<Operator::NumericalEffect> &numerical_effs_start =
op.get_numerical_effs_start();
for(int j = 0; j < numerical_effs_start.size(); j++) {
const Variable *var = numerical_effs_start[j].var;
int var_level = var->get_level();
if(var_level != -1) {
int foperator = static_cast<int>(numerical_effs_start[j].fop);
int right_var = numerical_effs_start[j].foperand->get_level();
transition_graphs[var_level]->addTransition(foperator, right_var, op,
i, start, var_order);
}
}
const vector<Operator::NumericalEffect> &numerical_effs_end =
op.get_numerical_effs_end();
for(int j = 0; j < numerical_effs_end.size(); j++) {
const Variable *var = numerical_effs_end[j].var;
int var_level = var->get_level();
if(var_level != -1) {
int foperator = static_cast<int>(numerical_effs_end[j].fop);
int right_var = numerical_effs_end[j].foperand->get_level();
transition_graphs[var_level]->addTransition(foperator, right_var, op,
i, end, var_order);
}
}
}
for(int i = 0; i < axioms_rel.size(); i++) {
const Axiom_relational &ax = axioms_rel[i];
Variable *var = ax.get_effect_var();
int var_level = var->get_level();
assert(var->get_layer()> -1);
assert(var_level != -1);
int old_val = ax.get_old_val();
int new_val = ax.get_effect_val();
transition_graphs[var_level]->addAxRelTransition(old_val, new_val, ax, i);
}
for(int i = 0; i < axioms_func.size(); i++) {
const Axiom_functional &ax = axioms_func[i];
Variable *var = ax.get_effect_var();
if(!var->is_necessary()&&!var->is_used_in_duration_condition())
continue;
int var_level = var->get_level();
assert(var->get_layer()> -1);
Variable* left_var = ax.get_left_var();
Variable* right_var = ax.get_right_var();
DomainTransitionGraphSubterm *dtgs = dynamic_cast<DomainTransitionGraphSubterm*>(transition_graphs[var_level]);
assert(dtgs);
if(var->is_comparison()) {
dtgs->setRelation(left_var, ax.cop, right_var);
} else {
dtgs->setRelation(left_var, ax.fop, right_var);
}
}
for(int i = 0; i < transition_graphs.size(); i++)
transition_graphs[i]->finalize();
}
bool are_DTGs_strongly_connected(
const vector<DomainTransitionGraph*> &transition_graphs) {
bool connected = true;
// no need to test last variable's dtg (highest level variable)
for(int i = 0; i < transition_graphs.size() - 1; i++)
if(!transition_graphs[i]->is_strongly_connected())
connected = false;
return connected;
}
<|endoftext|>
|
<commit_before>#include "UpdaterWindow.h"
#include "../3RVX/3RVX.h"
#include "../3RVX/Logger.h"
#include "../3RVX/CommCtl.h"
#include "../3RVX/NotifyIcon.h"
#include "../3RVX/Settings.h"
#include "resource.h"
#include "Updater.h"
UpdaterWindow::UpdaterWindow() :
Window(L"3RVX-UpdateWindow") {
HRESULT hr;
hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_SMALL,
&_smallIcon);
if (hr != S_OK) {
CLOG(L"Could not load notification icon");
}
hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_LARGE,
&_largeIcon);
if (hr != S_OK) {
CLOG(L"Could not load large notification icon");
}
_menu = CreatePopupMenu();
InsertMenu(_menu, -1, MF_ENABLED, MENU_INSTALL, L"Install");
InsertMenu(_menu, -1, MF_ENABLED, MENU_IGNORE, L"Ignore version");
InsertMenu(_menu, -1, MF_ENABLED, MENU_REMIND, L"Remind me later");
_menuFlags = TPM_RIGHTBUTTON;
if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {
_menuFlags |= TPM_RIGHTALIGN;
} else {
_menuFlags |= TPM_LEFTALIGN;
}
}
UpdaterWindow::~UpdaterWindow() {
delete _notifyIcon;
DestroyIcon(_smallIcon);
DestroyIcon(_largeIcon);
}
LRESULT UpdaterWindow::WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {
switch (wParam) {
case _3RVX::MSG_UPDATEICON:
_settings = Settings::Instance();
_settings->Load();
/* Set that we just checked for updates now */
_settings->LastUpdateCheckNow();
_settings->Save();
std::pair<int, int> newVersion = Updater::RemoteVersion();
_versionString = Updater::VersionToString(newVersion);
if (newVersion.first <= 0
|| _versionString == _settings->IgnoreUpdate()) {
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
}
CLOG(L"Creating update icon");
_notifyIcon = new NotifyIcon(
Window::Handle(),
L"Update Available",
_smallIcon);
CLOG(L"Launching balloon notification");
_notifyIcon->Balloon(L"Update Available",
L"3RVX " + _versionString, _largeIcon);
break;
}
} else if (message == MSG_NOTIFYICON) {
if (lParam == WM_LBUTTONUP
|| lParam == WM_RBUTTONUP
|| lParam == NIN_BALLOONUSERCLICK) {
POINT p;
GetCursorPos(&p);
SetForegroundWindow(hWnd);
TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y,
Window::Handle(), NULL);
PostMessage(hWnd, WM_NULL, 0, 0);
}
}
return Window::WndProc(hWnd, message, wParam, lParam);
}
void UpdaterWindow::DoModal() {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}<commit_msg>Implement menu actions<commit_after>#include "UpdaterWindow.h"
#include "../3RVX/3RVX.h"
#include "../3RVX/Logger.h"
#include "../3RVX/CommCtl.h"
#include "../3RVX/NotifyIcon.h"
#include "../3RVX/Settings.h"
#include "resource.h"
#include "Updater.h"
UpdaterWindow::UpdaterWindow() :
Window(L"3RVX-UpdateWindow") {
HRESULT hr;
hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_SMALL,
&_smallIcon);
if (hr != S_OK) {
CLOG(L"Could not load notification icon");
}
hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_LARGE,
&_largeIcon);
if (hr != S_OK) {
CLOG(L"Could not load large notification icon");
}
_menu = CreatePopupMenu();
InsertMenu(_menu, -1, MF_ENABLED, MENU_INSTALL, L"Install");
InsertMenu(_menu, -1, MF_ENABLED, MENU_IGNORE, L"Ignore version");
InsertMenu(_menu, -1, MF_ENABLED, MENU_REMIND, L"Remind me later");
_menuFlags = TPM_RIGHTBUTTON;
if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {
_menuFlags |= TPM_RIGHTALIGN;
} else {
_menuFlags |= TPM_LEFTALIGN;
}
}
UpdaterWindow::~UpdaterWindow() {
delete _notifyIcon;
DestroyIcon(_smallIcon);
DestroyIcon(_largeIcon);
}
LRESULT UpdaterWindow::WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {
switch (wParam) {
case _3RVX::MSG_UPDATEICON:
_settings = Settings::Instance();
_settings->Load();
/* Set that we just checked for updates now */
_settings->LastUpdateCheckNow();
_settings->Save();
std::pair<int, int> newVersion = Updater::RemoteVersion();
_versionString = Updater::VersionToString(newVersion);
if (newVersion.first <= 0
|| _versionString == _settings->IgnoreUpdate()) {
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
}
CLOG(L"Creating update icon");
_notifyIcon = new NotifyIcon(
Window::Handle(),
L"Update Available",
_smallIcon);
CLOG(L"Launching balloon notification");
_notifyIcon->Balloon(L"Update Available",
L"3RVX " + _versionString, _largeIcon);
break;
}
} else if (message == MSG_NOTIFYICON) {
if (lParam == WM_LBUTTONUP
|| lParam == WM_RBUTTONUP
|| lParam == NIN_BALLOONUSERCLICK) {
POINT p;
GetCursorPos(&p);
SetForegroundWindow(hWnd);
TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y,
Window::Handle(), NULL);
PostMessage(hWnd, WM_NULL, 0, 0);
}
} else if (message == WM_COMMAND) {
int menuItem = LOWORD(wParam);
switch (menuItem) {
case MENU_INSTALL:
break;
case MENU_IGNORE:
_settings->IgnoreUpdate(_versionString);
_settings->Save();
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
case MENU_REMIND:
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
}
} else if (message == WM_DESTROY) {
PostQuitMessage(0);
}
return Window::WndProc(hWnd, message, wParam, lParam);
}
void UpdaterWindow::DoModal() {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}<|endoftext|>
|
<commit_before>#ifndef ITER_COMBINATIONS_HPP_
#define ITER_COMBINATIONS_HPP_
#include "internal/iteratoriterator.hpp"
#include "internal/iterbase.hpp"
#include <iterator>
#include <type_traits>
#include <vector>
namespace iter {
namespace impl {
template <typename Container>
class Combinator;
using CombinationsFn = IterToolFnBindSizeTSecond<Combinator>;
}
constexpr impl::CombinationsFn combinations{};
}
template <typename Container>
class iter::impl::Combinator {
private:
Container container_;
std::size_t length_;
friend CombinationsFn;
Combinator(Container&& container, std::size_t length)
: container_(std::forward<Container>(container)), length_{length} {}
using IndexVector = std::vector<iterator_type<Container>>;
using CombIteratorDeref = IterIterWrapper<IndexVector>;
public:
Combinator(Combinator&&) = default;
class Iterator
: public std::iterator<std::input_iterator_tag, CombIteratorDeref> {
private:
constexpr static const int COMPLETE = -1;
std::remove_reference_t<Container>* container_p_;
CombIteratorDeref indices_;
int steps_{};
public:
Iterator(Container& container, std::size_t n)
: container_p_{&container}, indices_{n} {
if (n == 0) {
steps_ = COMPLETE;
return;
}
size_t inc = 0;
for (auto& iter : indices_.get()) {
auto it = get_begin(*container_p_);
dumb_advance(it, get_end(*container_p_), inc);
if (it != get_end(*container_p_)) {
iter = it;
++inc;
} else {
steps_ = COMPLETE;
break;
}
}
}
CombIteratorDeref& operator*() {
return indices_;
}
CombIteratorDeref* operator->() {
return &indices_;
}
Iterator& operator++() {
for (auto iter = indices_.get().rbegin(); iter != indices_.get().rend();
++iter) {
++(*iter);
// what we have to check here is if the distance between
// the index and the end of indices_ is >= the distance
// between the item and end of item
auto dist = std::distance(indices_.get().rbegin(), iter);
if (!(dumb_next(*iter, dist) != get_end(*container_p_))) {
if ((iter + 1) != indices_.get().rend()) {
size_t inc = 1;
for (auto down = iter; down != indices_.get().rbegin() - 1;
--down) {
(*down) = dumb_next(*(iter + 1), 1 + inc);
++inc;
}
} else {
steps_ = COMPLETE;
break;
}
} else {
break;
}
// we break because none of the rest of the items need
// to be incremented
}
if (steps_ != COMPLETE) {
++steps_;
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return steps_ == other.steps_;
}
};
Iterator begin() {
return {container_, length_};
}
Iterator end() {
return {container_, 0};
}
};
#endif
<commit_msg>Adds support for const iteration to combinations<commit_after>#ifndef ITER_COMBINATIONS_HPP_
#define ITER_COMBINATIONS_HPP_
#include "internal/iteratoriterator.hpp"
#include "internal/iterbase.hpp"
#include <iterator>
#include <type_traits>
#include <vector>
namespace iter {
namespace impl {
template <typename Container>
class Combinator;
using CombinationsFn = IterToolFnBindSizeTSecond<Combinator>;
}
constexpr impl::CombinationsFn combinations{};
}
template <typename Container>
class iter::impl::Combinator {
private:
Container container_;
std::size_t length_;
friend CombinationsFn;
Combinator(Container&& container, std::size_t length)
: container_(std::forward<Container>(container)), length_{length} {}
template <typename T>
using IndexVector = std::vector<iterator_type<T>>;
template <typename T>
using CombIteratorDeref = IterIterWrapper<IndexVector<T>>;
public:
Combinator(Combinator&&) = default;
template <typename ContainerT>
class Iterator : public std::iterator<std::input_iterator_tag,
CombIteratorDeref<ContainerT>> {
private:
template <typename>
friend class Iterator;
constexpr static const int COMPLETE = -1;
std::remove_reference_t<ContainerT>* container_p_;
CombIteratorDeref<ContainerT> indices_;
int steps_{};
public:
Iterator(ContainerT& container, std::size_t n)
: container_p_{&container}, indices_{n} {
if (n == 0) {
steps_ = COMPLETE;
return;
}
size_t inc = 0;
for (auto& iter : indices_.get()) {
auto it = get_begin(*container_p_);
dumb_advance(it, get_end(*container_p_), inc);
if (it != get_end(*container_p_)) {
iter = it;
++inc;
} else {
steps_ = COMPLETE;
break;
}
}
}
CombIteratorDeref<ContainerT>& operator*() {
return indices_;
}
CombIteratorDeref<ContainerT>* operator->() {
return &indices_;
}
Iterator& operator++() {
for (auto iter = indices_.get().rbegin(); iter != indices_.get().rend();
++iter) {
++(*iter);
// what we have to check here is if the distance between
// the index and the end of indices_ is >= the distance
// between the item and end of item
auto dist = std::distance(indices_.get().rbegin(), iter);
if (!(dumb_next(*iter, dist) != get_end(*container_p_))) {
if ((iter + 1) != indices_.get().rend()) {
size_t inc = 1;
for (auto down = iter; down != indices_.get().rbegin() - 1;
--down) {
(*down) = dumb_next(*(iter + 1), 1 + inc);
++inc;
}
} else {
steps_ = COMPLETE;
break;
}
} else {
break;
}
// we break because none of the rest of the items need
// to be incremented
}
if (steps_ != COMPLETE) {
++steps_;
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
template <typename T>
bool operator!=(const Iterator<T>& other) const {
return !(*this == other);
}
template <typename T>
bool operator==(const Iterator<T>& other) const {
return steps_ == other.steps_;
}
};
Iterator<Container> begin() {
return {container_, length_};
}
Iterator<Container> end() {
return {container_, 0};
}
Iterator<AsConst<Container>> begin() const {
return {as_const(container_), length_};
}
Iterator<AsConst<Container>> end() const {
return {as_const(container_), 0};
}
};
#endif
<|endoftext|>
|
<commit_before>///
/// \file TestEMCALSimulation.C
/// \ingroup EMCAL_TestSimRec
/// \brief Simple macro to test EMCAL simulation
///
/// Simple macro to test EMCAL simulation.
/// It will take the Config.C macro that is sitting in the same place as the execution is performed.
/// In order to execute this you can do
/// * Root5: aliroot -q -b -l $ALICE_ROOT/EMCAL/macros/TestSimuReco/TestEMCALSimulation.C
/// * Root6: aliroot -q -b -l $ALICE_ROOT/EMCAL/macros/TestSimuReco/LoadLibForConfig.C $ALICE_ROOT/EMCAL/macros/TestSimuReco/TestEMCALSimulation.C
///
/// Or directly in the root prompt
/// root [1] .x LoadLibForConfig.C //Root6
/// root [2] .x TestEMCALSimulation.C
///
/// In order to find all the included classes in the Config.C one should add to the rootlogon.C file some paths
/// gSystem->SetIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/ -I$ALICE_ROOT/include -I$ALICE_ROOT/ANALYSIS/macros -I$ALICE_ROOT/STEER -I$ALICE_ROOT/STEER/STEER -I$GEANT3DIR/include -I$GEANT3DIR/include/TGeant3");
/// or do it in the root prompt before execution.
///
/// \author : Jenn Klay, LLNL.
/// \author : Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS).
///
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TStopwatch.h>
#include <TSystem.h>
#include "AliSimulation.h"
#include "AliLog.h"
#endif
///
/// Main execution method
///
/// \param nev: number of events to be generated
/// \param raw: generate also raw data from digits?
///
void TestEMCALSimulation(Int_t nev =10, Bool_t raw = kFALSE)
{
AliSimulation simulator;
simulator.SetConfigFile("Config.C");
simulator.SetMakeSDigits("EMCAL");
simulator.SetMakeDigits ("EMCAL");
//simulator.SetRunGeneration(kFALSE); // Generate or not particles
//simulator.SetRunSimulation(kFALSE); // Generate or not HITS (detector response) or not, start from SDigits
if(raw) simulator.SetWriteRawData("EMCAL","raw.root",kTRUE);
//OCDB settings
simulator.SetDefaultStorage("local://$ALIROOT_OCDB_ROOT/OCDB");
simulator.SetSpecificStorage("GRP/GRP/Data",
Form("local://%s",gSystem->pwd()));
// In case of anchoring MC, comment previous OCDB lines
// select the appropriate year
//simulator.SetDefaultStorage("alien://Folder=/alice/data/2011/OCDB");
//simulator.UseVertexFromCDB();
//simulator.UseMagFieldFromGRP();
//Avoid the HLT to run
simulator.SetRunHLT("");
//Avoid QA
simulator.SetRunQA(":");
TStopwatch timer;
timer.Start();
// simulator.SetRunNumber(159582); // LHC11d run
simulator.Run(nev);
timer.Stop();
timer.Print();
}
<commit_msg>comment out the line disabling QA, it breaks simulation<commit_after>///
/// \file TestEMCALSimulation.C
/// \ingroup EMCAL_TestSimRec
/// \brief Simple macro to test EMCAL simulation
///
/// Simple macro to test EMCAL simulation.
/// It will take the Config.C macro that is sitting in the same place as the execution is performed.
/// In order to execute this you can do
/// * Root5: aliroot -q -b -l $ALICE_ROOT/EMCAL/macros/TestSimuReco/TestEMCALSimulation.C
/// * Root6: aliroot -q -b -l $ALICE_ROOT/EMCAL/macros/TestSimuReco/LoadLibForConfig.C $ALICE_ROOT/EMCAL/macros/TestSimuReco/TestEMCALSimulation.C
///
/// Or directly in the root prompt
/// root [1] .x LoadLibForConfig.C //Root6
/// root [2] .x TestEMCALSimulation.C
///
/// In order to find all the included classes in the Config.C one should add to the rootlogon.C file some paths
/// gSystem->SetIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/ -I$ALICE_ROOT/include -I$ALICE_ROOT/ANALYSIS/macros -I$ALICE_ROOT/STEER -I$ALICE_ROOT/STEER/STEER -I$GEANT3DIR/include -I$GEANT3DIR/include/TGeant3");
/// or do it in the root prompt before execution.
///
/// \author : Jenn Klay, LLNL.
/// \author : Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS).
///
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TStopwatch.h>
#include <TSystem.h>
#include "AliSimulation.h"
#include "AliLog.h"
#endif
///
/// Main execution method
///
/// \param nev: number of events to be generated
/// \param raw: generate also raw data from digits?
///
void TestEMCALSimulation(Int_t nev =10, Bool_t raw = kFALSE)
{
AliSimulation simulator;
simulator.SetConfigFile("Config.C");
simulator.SetMakeSDigits("EMCAL");
simulator.SetMakeDigits ("EMCAL");
//simulator.SetRunGeneration(kFALSE); // Generate or not particles
//simulator.SetRunSimulation(kFALSE); // Generate or not HITS (detector response) or not, start from SDigits
if(raw) simulator.SetWriteRawData("EMCAL","raw.root",kTRUE);
//OCDB settings
simulator.SetDefaultStorage("local://$ALIROOT_OCDB_ROOT/OCDB");
simulator.SetSpecificStorage("GRP/GRP/Data",
Form("local://%s",gSystem->pwd()));
// In case of anchoring MC, comment previous OCDB lines
// select the appropriate year
//simulator.SetDefaultStorage("alien://Folder=/alice/data/2011/OCDB");
//simulator.UseVertexFromCDB();
//simulator.UseMagFieldFromGRP();
//Avoid the HLT to run
simulator.SetRunHLT("");
//Avoid QA
//simulator.SetRunQA(":");
TStopwatch timer;
timer.Start();
// simulator.SetRunNumber(159582); // LHC11d run
simulator.Run(nev);
timer.Stop();
timer.Print();
}
<|endoftext|>
|
<commit_before>/* Copyright (C) 2009-2012, Stefan Hacker <dD0t@users.sourceforge.net>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Mumble Developers nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define _USE_MATH_DEFINES
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#include <QMessageBox>
#include <QPointer>
#include <math.h>
#include <float.h>
#include "manual.h"
#include "ui_manual.h"
#ifdef Q_OS_UNIX
#define __cdecl
typedef WId HWND;
#define DLL_PUBLIC __attribute__((visibility("default")))
#else
#define DLL_PUBLIC __declspec(dllexport)
#endif
#include "../mumble_plugin.h"
static QPointer<Manual> mDlg = NULL;
static bool bLinkable = false;
static bool bActive = true;
static int iAzimuth = 0;
static int iElevation = 0;
static struct {
float avatar_pos[3];
float avatar_front[3];
float avatar_top[3];
float camera_pos[3];
float camera_front[3];
float camera_top[3];
std::string context;
std::wstring identity;
} my = {{0,0,0}, {0,0,0}, {0,0,0},
{0,0,0}, {0,0,0}, {0,0,0},
std::string(), std::wstring()
};
Manual::Manual(QWidget *p) : QDialog(p) {
setupUi(this);
qgvPosition->viewport()->installEventFilter(this);
qgvPosition->scale(1.0f, 1.0f);
qgsScene = new QGraphicsScene(QRectF(-5.0f, -5.0f, 10.0f, 10.0f), this);
qgiPosition = qgsScene->addEllipse(QRectF(-0.5f, -0.5f, 1.0f, 1.0f), QPen(Qt::black), QBrush(Qt::red));
qgvPosition->setScene(qgsScene);
qgvPosition->fitInView(-5.0f, -5.0f, 10.0f, 10.0f, Qt::KeepAspectRatio);
qdsbX->setRange(-FLT_MAX, FLT_MAX);
qdsbY->setRange(-FLT_MAX, FLT_MAX);
qdsbZ->setRange(-FLT_MAX, FLT_MAX);
qdsbX->setValue(my.avatar_pos[0]);
qdsbY->setValue(my.avatar_pos[1]);
qdsbZ->setValue(my.avatar_pos[2]);
qpbActivated->setChecked(bActive);
qpbLinked->setChecked(bLinkable);
qsbAzimuth->setValue(iAzimuth);
qsbElevation->setValue(iElevation);
updateTopAndFront(iAzimuth, iElevation);
}
bool Manual::eventFilter(QObject *obj, QEvent *evt) {
if ((evt->type() == QEvent::MouseButtonPress) || (evt->type() == QEvent::MouseMove)) {
QMouseEvent *qme = dynamic_cast<QMouseEvent *>(evt);
if (qme) {
if (qme->buttons() & Qt::LeftButton) {
QPointF qpf = qgvPosition->mapToScene(qme->pos());
qdsbX->setValue(-qpf.x());
qdsbZ->setValue(-qpf.y());
qgiPosition->setPos(qpf);
}
}
}
return QDialog::eventFilter(obj, evt);
}
void Manual::changeEvent(QEvent *e) {
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
retranslateUi(this);
break;
default:
break;
}
}
void Manual::on_qpbUnhinge_pressed() {
qpbUnhinge->setEnabled(false);
mDlg->setParent(NULL);
mDlg->show();
}
void Manual::on_qpbLinked_clicked(bool b) {
bLinkable = b;
}
void Manual::on_qpbActivated_clicked(bool b) {
bActive = b;
}
void Manual::on_qdsbX_valueChanged(double d) {
my.avatar_pos[0] = my.camera_pos[0] = static_cast<float>(d);
qgiPosition->setPos(-my.avatar_pos[0], -my.avatar_pos[2]);
}
void Manual::on_qdsbY_valueChanged(double d) {
my.avatar_pos[1] = my.camera_pos[1] = static_cast<float>(d);
}
void Manual::on_qdsbZ_valueChanged(double d) {
my.avatar_pos[2] = my.camera_pos[2] = static_cast<float>(d);
qgiPosition->setPos(-my.avatar_pos[0], -my.avatar_pos[2]);
}
void Manual::on_qsbAzimuth_valueChanged(int i) {
if (i > 180)
qdAzimuth->setValue(-360 + i);
else
qdAzimuth->setValue(i);
updateTopAndFront(i, qsbElevation->value());
}
void Manual::on_qsbElevation_valueChanged(int i) {
qdElevation->setValue(90 - i);
updateTopAndFront(qsbAzimuth->value(), i);
}
void Manual::on_qdAzimuth_valueChanged(int i) {
if (i < 0)
qsbAzimuth->setValue(360 + i);
else
qsbAzimuth->setValue(i);
}
void Manual::on_qdElevation_valueChanged(int i) {
if (i < -90)
qdElevation->setValue(180);
else if (i < 0)
qdElevation->setValue(0);
else
qsbElevation->setValue(90 - i);
}
void Manual::on_qleContext_editingFinished() {
my.context = qleContext->text().toStdString();
}
void Manual::on_qleIdentity_editingFinished() {
my.identity = qleIdentity->text().toStdWString();
}
void Manual::on_buttonBox_clicked(QAbstractButton *button) {
if (buttonBox->buttonRole(button) == buttonBox->ResetRole) {
qpbLinked->setChecked(false);
qpbActivated->setChecked(true);
bLinkable = false;
bActive = true;
qdsbX->setValue(0);
qdsbY->setValue(0);
qdsbZ->setValue(0);
qleContext->clear();
qleIdentity->clear();
qsbElevation->setValue(0);
qsbAzimuth->setValue(0);
}
}
void Manual::updateTopAndFront(int azimuth, int elevation) {
iAzimuth = azimuth;
iElevation = elevation;
double azim = azimuth * M_PI / 180.;
double elev = elevation * M_PI / 180.;
my.avatar_front[0] = static_cast<float>(cos(elev) * sin(azim));
my.avatar_front[1] = static_cast<float>(sin(elev));
my.avatar_front[2] = static_cast<float>(cos(elev) * cos(azim));
my.avatar_top[0] = static_cast<float>(-sin(elev) * sin(azim));
my.avatar_top[1] = static_cast<float>(cos(elev));
my.avatar_top[2] = static_cast<float>(-sin(elev) * cos(azim));
memcpy(my.camera_top, my.avatar_top, sizeof(float) * 3);
memcpy(my.camera_front, my.avatar_front, sizeof(float) * 3);
}
static int trylock() {
return bLinkable;
}
static void unlock() {
if (mDlg) {
mDlg->qpbLinked->setChecked(false);
}
bLinkable = false;
}
static void config(HWND h) {
if (mDlg) {
mDlg->setParent(QWidget::find(h), Qt::Dialog);
mDlg->qpbUnhinge->setEnabled(true);
} else {
mDlg = new Manual(QWidget::find(h));
}
mDlg->show();
}
static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
if (!bLinkable)
return false;
if (!bActive) {
memset(avatar_pos, 0, sizeof(float)*3);
memset(camera_pos, 0, sizeof(float)*3);
return true;
}
memcpy(avatar_pos, my.avatar_pos, sizeof(float)*3);
memcpy(avatar_front, my.avatar_front, sizeof(float)*3);
memcpy(avatar_top, my.avatar_top, sizeof(float)*3);
memcpy(camera_pos, my.camera_pos, sizeof(float)*3);
memcpy(camera_front, my.camera_front, sizeof(float)*3);
memcpy(camera_top, my.camera_top, sizeof(float)*3);
context.assign(my.context);
identity.assign(my.identity);
return true;
}
static const std::wstring longdesc() {
return std::wstring(L"This is the manual placement plugin. It allows you to place yourself manually.");
}
static std::wstring description(L"Manual placement plugin");
static std::wstring shortname(L"Manual placement");
static void about(WId h) {
QMessageBox::about(QWidget::find(h), QString::fromStdWString(description), QString::fromStdWString(longdesc()));
}
static MumblePlugin manual = {
MUMBLE_PLUGIN_MAGIC,
description,
shortname,
about,
config,
trylock,
unlock,
longdesc,
fetch
};
extern "C" DLL_PUBLIC MumblePlugin *getMumblePlugin() {
return &manual;
}
<commit_msg>Manual positioning plugin had X-Axis backwards<commit_after>/* Copyright (C) 2009-2012, Stefan Hacker <dD0t@users.sourceforge.net>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Mumble Developers nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define _USE_MATH_DEFINES
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#include <QMessageBox>
#include <QPointer>
#include <math.h>
#include <float.h>
#include "manual.h"
#include "ui_manual.h"
#ifdef Q_OS_UNIX
#define __cdecl
typedef WId HWND;
#define DLL_PUBLIC __attribute__((visibility("default")))
#else
#define DLL_PUBLIC __declspec(dllexport)
#endif
#include "../mumble_plugin.h"
static QPointer<Manual> mDlg = NULL;
static bool bLinkable = false;
static bool bActive = true;
static int iAzimuth = 0;
static int iElevation = 0;
static struct {
float avatar_pos[3];
float avatar_front[3];
float avatar_top[3];
float camera_pos[3];
float camera_front[3];
float camera_top[3];
std::string context;
std::wstring identity;
} my = {{0,0,0}, {0,0,0}, {0,0,0},
{0,0,0}, {0,0,0}, {0,0,0},
std::string(), std::wstring()
};
Manual::Manual(QWidget *p) : QDialog(p) {
setupUi(this);
qgvPosition->viewport()->installEventFilter(this);
qgvPosition->scale(1.0f, 1.0f);
qgsScene = new QGraphicsScene(QRectF(-5.0f, -5.0f, 10.0f, 10.0f), this);
qgiPosition = qgsScene->addEllipse(QRectF(-0.5f, -0.5f, 1.0f, 1.0f), QPen(Qt::black), QBrush(Qt::red));
qgvPosition->setScene(qgsScene);
qgvPosition->fitInView(-5.0f, -5.0f, 10.0f, 10.0f, Qt::KeepAspectRatio);
qdsbX->setRange(-FLT_MAX, FLT_MAX);
qdsbY->setRange(-FLT_MAX, FLT_MAX);
qdsbZ->setRange(-FLT_MAX, FLT_MAX);
qdsbX->setValue(my.avatar_pos[0]);
qdsbY->setValue(my.avatar_pos[1]);
qdsbZ->setValue(my.avatar_pos[2]);
qpbActivated->setChecked(bActive);
qpbLinked->setChecked(bLinkable);
qsbAzimuth->setValue(iAzimuth);
qsbElevation->setValue(iElevation);
updateTopAndFront(iAzimuth, iElevation);
}
bool Manual::eventFilter(QObject *obj, QEvent *evt) {
if ((evt->type() == QEvent::MouseButtonPress) || (evt->type() == QEvent::MouseMove)) {
QMouseEvent *qme = dynamic_cast<QMouseEvent *>(evt);
if (qme) {
if (qme->buttons() & Qt::LeftButton) {
QPointF qpf = qgvPosition->mapToScene(qme->pos());
qdsbX->setValue(qpf.x());
qdsbZ->setValue(-qpf.y());
qgiPosition->setPos(qpf);
}
}
}
return QDialog::eventFilter(obj, evt);
}
void Manual::changeEvent(QEvent *e) {
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
retranslateUi(this);
break;
default:
break;
}
}
void Manual::on_qpbUnhinge_pressed() {
qpbUnhinge->setEnabled(false);
mDlg->setParent(NULL);
mDlg->show();
}
void Manual::on_qpbLinked_clicked(bool b) {
bLinkable = b;
}
void Manual::on_qpbActivated_clicked(bool b) {
bActive = b;
}
void Manual::on_qdsbX_valueChanged(double d) {
my.avatar_pos[0] = my.camera_pos[0] = static_cast<float>(d);
qgiPosition->setPos(my.avatar_pos[0], -my.avatar_pos[2]);
}
void Manual::on_qdsbY_valueChanged(double d) {
my.avatar_pos[1] = my.camera_pos[1] = static_cast<float>(d);
}
void Manual::on_qdsbZ_valueChanged(double d) {
my.avatar_pos[2] = my.camera_pos[2] = static_cast<float>(d);
qgiPosition->setPos(my.avatar_pos[0], -my.avatar_pos[2]);
}
void Manual::on_qsbAzimuth_valueChanged(int i) {
if (i > 180)
qdAzimuth->setValue(-360 + i);
else
qdAzimuth->setValue(i);
updateTopAndFront(i, qsbElevation->value());
}
void Manual::on_qsbElevation_valueChanged(int i) {
qdElevation->setValue(90 - i);
updateTopAndFront(qsbAzimuth->value(), i);
}
void Manual::on_qdAzimuth_valueChanged(int i) {
if (i < 0)
qsbAzimuth->setValue(360 + i);
else
qsbAzimuth->setValue(i);
}
void Manual::on_qdElevation_valueChanged(int i) {
if (i < -90)
qdElevation->setValue(180);
else if (i < 0)
qdElevation->setValue(0);
else
qsbElevation->setValue(90 - i);
}
void Manual::on_qleContext_editingFinished() {
my.context = qleContext->text().toStdString();
}
void Manual::on_qleIdentity_editingFinished() {
my.identity = qleIdentity->text().toStdWString();
}
void Manual::on_buttonBox_clicked(QAbstractButton *button) {
if (buttonBox->buttonRole(button) == buttonBox->ResetRole) {
qpbLinked->setChecked(false);
qpbActivated->setChecked(true);
bLinkable = false;
bActive = true;
qdsbX->setValue(0);
qdsbY->setValue(0);
qdsbZ->setValue(0);
qleContext->clear();
qleIdentity->clear();
qsbElevation->setValue(0);
qsbAzimuth->setValue(0);
}
}
void Manual::updateTopAndFront(int azimuth, int elevation) {
iAzimuth = azimuth;
iElevation = elevation;
double azim = azimuth * M_PI / 180.;
double elev = elevation * M_PI / 180.;
my.avatar_front[0] = static_cast<float>(cos(elev) * sin(azim));
my.avatar_front[1] = static_cast<float>(sin(elev));
my.avatar_front[2] = static_cast<float>(cos(elev) * cos(azim));
my.avatar_top[0] = static_cast<float>(-sin(elev) * sin(azim));
my.avatar_top[1] = static_cast<float>(cos(elev));
my.avatar_top[2] = static_cast<float>(-sin(elev) * cos(azim));
memcpy(my.camera_top, my.avatar_top, sizeof(float) * 3);
memcpy(my.camera_front, my.avatar_front, sizeof(float) * 3);
}
static int trylock() {
return bLinkable;
}
static void unlock() {
if (mDlg) {
mDlg->qpbLinked->setChecked(false);
}
bLinkable = false;
}
static void config(HWND h) {
if (mDlg) {
mDlg->setParent(QWidget::find(h), Qt::Dialog);
mDlg->qpbUnhinge->setEnabled(true);
} else {
mDlg = new Manual(QWidget::find(h));
}
mDlg->show();
}
static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
if (!bLinkable)
return false;
if (!bActive) {
memset(avatar_pos, 0, sizeof(float)*3);
memset(camera_pos, 0, sizeof(float)*3);
return true;
}
memcpy(avatar_pos, my.avatar_pos, sizeof(float)*3);
memcpy(avatar_front, my.avatar_front, sizeof(float)*3);
memcpy(avatar_top, my.avatar_top, sizeof(float)*3);
memcpy(camera_pos, my.camera_pos, sizeof(float)*3);
memcpy(camera_front, my.camera_front, sizeof(float)*3);
memcpy(camera_top, my.camera_top, sizeof(float)*3);
context.assign(my.context);
identity.assign(my.identity);
return true;
}
static const std::wstring longdesc() {
return std::wstring(L"This is the manual placement plugin. It allows you to place yourself manually.");
}
static std::wstring description(L"Manual placement plugin");
static std::wstring shortname(L"Manual placement");
static void about(WId h) {
QMessageBox::about(QWidget::find(h), QString::fromStdWString(description), QString::fromStdWString(longdesc()));
}
static MumblePlugin manual = {
MUMBLE_PLUGIN_MAGIC,
description,
shortname,
about,
config,
trylock,
unlock,
longdesc,
fetch
};
extern "C" DLL_PUBLIC MumblePlugin *getMumblePlugin() {
return &manual;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (C) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* Test code for the Velocity Smoothing library
* Run this test only using make tests TESTFILTER=VelocitySmoothing
*/
#include <gtest/gtest.h>
#include <matrix/matrix/math.hpp>
#include "VelocitySmoothing.hpp"
using namespace matrix;
class VelocitySmoothingTest : public ::testing::Test
{
public:
void SetUp() override
{
return;
}
void setConstraints(float j_max, float a_max, float v_max);
void setInitialConditions(Vector3f acc, Vector3f vel, Vector3f pos);
void updateTrajectories(Vector3f velocity_setpoints, float dt);
VelocitySmoothing _trajectories[3];
};
void VelocitySmoothingTest::setConstraints(float j_max, float a_max, float v_max)
{
for (int i = 0; i < 3; i++) {
_trajectories[i].setMaxJerk(j_max);
_trajectories[i].setMaxAccel(a_max);
_trajectories[i].setMaxVel(v_max);
}
}
void VelocitySmoothingTest::setInitialConditions(Vector3f a0, Vector3f v0, Vector3f x0)
{
for (int i = 0; i < 3; i++) {
_trajectories[i].setCurrentAcceleration(a0(i));
_trajectories[i].setCurrentVelocity(v0(i));
_trajectories[i].setCurrentPosition(x0(i));
}
}
void VelocitySmoothingTest::updateTrajectories(Vector3f velocity_setpoints, float dt)
{
for (int i = 0; i < 3; i++) {
_trajectories[i].updateDurations(dt, velocity_setpoints(i));
}
VelocitySmoothing::timeSynchronization(_trajectories, 2);
float dummy; // We don't care about the immediate result
for (int i = 0; i < 3; i++) {
_trajectories[i].integrate(dummy, dummy, dummy);
}
}
TEST_F(VelocitySmoothingTest, testConstantSetpoint)
{
// Set the constraints
const float j_max = 55.2f;
const float a_max = 6.f;
const float v_max = 6.f;
setConstraints(j_max, a_max, v_max);
// Set the initial conditions
Vector3f a0(0.22f, 0.f, 0.22f);
Vector3f v0(2.47f, -5.59e-6f, 2.47f);
Vector3f x0(0.f, 0.f, 0.f);
setInitialConditions(a0, v0, x0);
// Generate the trajectories with constant setpoints and dt
Vector3f velocity_setpoints(0.f, 1.f, 0.f);
float dt = 0.01f;
for (int i = 0; i < 60; i++) {
updateTrajectories(velocity_setpoints, dt);
}
// Check that all the trajectories reached their desired value
EXPECT_LE(fabsf(_trajectories[0].getCurrentVelocity() - velocity_setpoints(0)), 0.01f);
EXPECT_LE(fabsf(_trajectories[1].getCurrentVelocity() - velocity_setpoints(1)), 0.01f);
EXPECT_LE(fabsf(_trajectories[2].getCurrentVelocity() - velocity_setpoints(2)), 0.01f);
}
<commit_msg>VelocitySmoothing - add zero setpoint test<commit_after>/****************************************************************************
*
* Copyright (C) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* Test code for the Velocity Smoothing library
* Run this test only using make tests TESTFILTER=VelocitySmoothing
*/
#include <gtest/gtest.h>
#include <matrix/matrix/math.hpp>
#include "VelocitySmoothing.hpp"
using namespace matrix;
class VelocitySmoothingTest : public ::testing::Test
{
public:
void SetUp() override
{
return;
}
void setConstraints(float j_max, float a_max, float v_max);
void setInitialConditions(Vector3f acc, Vector3f vel, Vector3f pos);
void updateTrajectories(Vector3f velocity_setpoints, float dt);
VelocitySmoothing _trajectories[3];
};
void VelocitySmoothingTest::setConstraints(float j_max, float a_max, float v_max)
{
for (int i = 0; i < 3; i++) {
_trajectories[i].setMaxJerk(j_max);
_trajectories[i].setMaxAccel(a_max);
_trajectories[i].setMaxVel(v_max);
}
}
void VelocitySmoothingTest::setInitialConditions(Vector3f a0, Vector3f v0, Vector3f x0)
{
for (int i = 0; i < 3; i++) {
_trajectories[i].setCurrentAcceleration(a0(i));
_trajectories[i].setCurrentVelocity(v0(i));
_trajectories[i].setCurrentPosition(x0(i));
}
}
void VelocitySmoothingTest::updateTrajectories(Vector3f velocity_setpoints, float dt)
{
for (int i = 0; i < 3; i++) {
_trajectories[i].updateDurations(dt, velocity_setpoints(i));
}
VelocitySmoothing::timeSynchronization(_trajectories, 2);
float dummy; // We don't care about the immediate result
for (int i = 0; i < 3; i++) {
_trajectories[i].integrate(dummy, dummy, dummy);
}
}
TEST_F(VelocitySmoothingTest, testConstantSetpoint)
{
// Set the constraints
const float j_max = 55.2f;
const float a_max = 6.f;
const float v_max = 6.f;
setConstraints(j_max, a_max, v_max);
// Set the initial conditions
Vector3f a0(0.22f, 0.f, 0.22f);
Vector3f v0(2.47f, -5.59e-6f, 2.47f);
Vector3f x0(0.f, 0.f, 0.f);
setInitialConditions(a0, v0, x0);
// Generate the trajectories with constant setpoints and dt
Vector3f velocity_setpoints(0.f, 1.f, 0.f);
float dt = 0.01f;
for (int i = 0; i < 60; i++) {
updateTrajectories(velocity_setpoints, dt);
}
// Check that all the trajectories reached their desired value
EXPECT_LE(fabsf(_trajectories[0].getCurrentVelocity() - velocity_setpoints(0)), 0.01f);
EXPECT_LE(fabsf(_trajectories[1].getCurrentVelocity() - velocity_setpoints(1)), 0.01f);
EXPECT_LE(fabsf(_trajectories[2].getCurrentVelocity() - velocity_setpoints(2)), 0.01f);
}
TEST_F(VelocitySmoothingTest, testZeroSetpoint)
{
// Set the initial conditions to zero
Vector3f a0(0.f, 0.f, 0.f);
Vector3f v0(0.f, 0.f, 0.f);
Vector3f x0(0.f, 0.f, 0.f);
setInitialConditions(a0, v0, x0);
// Generate the trajectories with zero setpoints
Vector3f velocity_setpoints(0.f, 0.f, 0.f);
float dt = 0.01f;
// Run a few times the algorithm
updateTrajectories(velocity_setpoints, dt);
for (int i = 0; i < 60; i++) {
updateTrajectories(velocity_setpoints, dt);
}
// Check that all the trajectories are still at zero
for (int i = 0; i < 3; i++) {
EXPECT_EQ(_trajectories[i].getCurrentJerk(), 0.f);
EXPECT_EQ(_trajectories[i].getCurrentAcceleration(), 0.f);
EXPECT_EQ(_trajectories[i].getCurrentVelocity(), 0.f);
EXPECT_EQ(_trajectories[i].getCurrentPosition(), 0.f);
}
}
<|endoftext|>
|
<commit_before>// bdlt_date.cpp -*-C++-*-
#include <bdlt_date.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdlt_date_cpp,"$Id$ $CSID$")
#include <bslim_printer.h>
#include <bsls_performancehint.h>
#include <bsls_platform.h>
#include <bsl_ostream.h>
#include <bsl_c_stdio.h> // 'snprintf'
namespace BloombergLP {
namespace bdlt {
static const char *const months[] = {
0,
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
};
// ----------
// class Date
// ----------
// MANIPULATORS
int Date::addDaysIfValid(int numDays)
{
enum { k_SUCCESS = 0, k_FAILURE = -1 };
const int tmpSerialDate = d_serialDate + numDays;
if (!Date::isValidSerial(tmpSerialDate)) {
return k_FAILURE; // RETURN
}
d_serialDate = tmpSerialDate;
return k_SUCCESS;
}
// ACCESSORS
bsl::ostream& Date::print(bsl::ostream& stream,
int level,
int spacesPerLevel) const
{
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(stream.bad())) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
return stream; // RETURN
}
// Typical space usage (10 bytes): ddMMMyyyy nil. Reserve 128 bytes for
// possible BAD DATE result, which is sufficient space for the bad date
// verbose message even on a 64-bit system.
char buffer[128];
#if defined(BSLS_ASSERT_OPT_IS_ACTIVE)
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(
!Date::isValidSerial(d_serialDate))) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
#if defined(BSLS_PLATFORM_CMP_MSVC)
#define snprintf _snprintf
#endif
snprintf(buffer,
sizeof buffer,
"*BAD*DATE:%p->d_serialDate=%d",
this,
d_serialDate);
#if defined(BSLS_ASSERT_SAFE_IS_ACTIVE)
BSLS_LOG("'bdlt::Date' precondition violated: %s.", buffer);
#endif
BSLS_ASSERT_SAFE(
!"'bdlt::Date::print' attempted on date with invalid state.");
}
else {
#endif // defined(BSLS_ASSERT_OPT_IS_ACTIVE)
int y, m, d;
getYearMonthDay(&y, &m, &d);
const char *const month = months[m];
buffer[0] = static_cast<char>(d / 10 + '0');
buffer[1] = static_cast<char>(d % 10 + '0');
buffer[2] = month[0];
buffer[3] = month[1];
buffer[4] = month[2];
buffer[5] = static_cast<char>( y / 1000 + '0');
buffer[6] = static_cast<char>(((y % 1000) / 100) + '0');
buffer[7] = static_cast<char>(((y % 100) / 10) + '0');
buffer[8] = static_cast<char>( y % 10 + '0');
buffer[9] = 0;
#if defined(BSLS_ASSERT_OPT_IS_ACTIVE)
}
#endif // defined(BSLS_ASSERT_OPT_IS_ACTIVE)
bslim::Printer printer(&stream, level, spacesPerLevel);
printer.start(true); // 'true' -> suppress '['
stream << buffer;
printer.end(true); // 'true' -> suppress ']'
return stream;
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2014 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>[APPROVAL] INTERNAL pending/master/bdlt_date-safe-build-breakage-drqs-62149722 to master<commit_after>// bdlt_date.cpp -*-C++-*-
#include <bdlt_date.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdlt_date_cpp,"$Id$ $CSID$")
#include <bslim_printer.h>
#include <bsls_log.h>
#include <bsls_performancehint.h>
#include <bsls_platform.h>
#include <bsl_ostream.h>
#include <bsl_c_stdio.h> // 'snprintf'
namespace BloombergLP {
namespace bdlt {
static const char *const months[] = {
0,
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
};
// ----------
// class Date
// ----------
// MANIPULATORS
int Date::addDaysIfValid(int numDays)
{
enum { k_SUCCESS = 0, k_FAILURE = -1 };
const int tmpSerialDate = d_serialDate + numDays;
if (!Date::isValidSerial(tmpSerialDate)) {
return k_FAILURE; // RETURN
}
d_serialDate = tmpSerialDate;
return k_SUCCESS;
}
// ACCESSORS
bsl::ostream& Date::print(bsl::ostream& stream,
int level,
int spacesPerLevel) const
{
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(stream.bad())) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
return stream; // RETURN
}
// Typical space usage (10 bytes): ddMMMyyyy nil. Reserve 128 bytes for
// possible BAD DATE result, which is sufficient space for the bad date
// verbose message even on a 64-bit system.
char buffer[128];
#if defined(BSLS_ASSERT_OPT_IS_ACTIVE)
if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(
!Date::isValidSerial(d_serialDate))) {
BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
#if defined(BSLS_PLATFORM_CMP_MSVC)
#define snprintf _snprintf
#endif
snprintf(buffer,
sizeof buffer,
"*BAD*DATE:%p->d_serialDate=%d",
this,
d_serialDate);
#if defined(BSLS_ASSERT_SAFE_IS_ACTIVE)
BSLS_LOG("'bdlt::Date' precondition violated: %s.", buffer);
#endif
BSLS_ASSERT_SAFE(
!"'bdlt::Date::print' attempted on date with invalid state.");
}
else {
#endif // defined(BSLS_ASSERT_OPT_IS_ACTIVE)
int y, m, d;
getYearMonthDay(&y, &m, &d);
const char *const month = months[m];
buffer[0] = static_cast<char>(d / 10 + '0');
buffer[1] = static_cast<char>(d % 10 + '0');
buffer[2] = month[0];
buffer[3] = month[1];
buffer[4] = month[2];
buffer[5] = static_cast<char>( y / 1000 + '0');
buffer[6] = static_cast<char>(((y % 1000) / 100) + '0');
buffer[7] = static_cast<char>(((y % 100) / 10) + '0');
buffer[8] = static_cast<char>( y % 10 + '0');
buffer[9] = 0;
#if defined(BSLS_ASSERT_OPT_IS_ACTIVE)
}
#endif // defined(BSLS_ASSERT_OPT_IS_ACTIVE)
bslim::Printer printer(&stream, level, spacesPerLevel);
printer.start(true); // 'true' -> suppress '['
stream << buffer;
printer.end(true); // 'true' -> suppress ']'
return stream;
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2014 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>
|
<commit_before>#include "match.h"
#include "term.h"
#include "prompt.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
static const int MAXLINES = 20;
int main(void)
{
vector<wstr> input;
string line;
while (getline(cin, line)) input.emplace_back(line);
Term tty("/dev/tty");
Term::Size screen_size = tty.get_screen_size();
char ch;
int selection = 1;
Prompt prompt(tty, "> ");
tty.erase_display(Term::FORWARD);
for (;;) {
auto last = match(input.begin(), input.end(), prompt.query());
auto it = input.cbegin();
int i = 1;
for (; it != last; ++i, ++it) {
string str = (*it).str.substr(0, screen_size.columns);
if (i == selection) {
tty.puts_highlighted(str.c_str());
} else {
tty.puts(str.c_str());
}
if (i == MAXLINES)
break;
tty.putchar('\n');
}
tty.cursor_up(i);
tty.move_to_col(prompt.current_column());
ch = tty.getchar();
if (ch == Term::ESC || ch == Term::CTRL_C || ch == Term::ENTER) {
break;
} else if (ch == Term::CTRL_N) {
selection = min(selection + 1, i - 1);
} else if (ch == Term::CTRL_P) {
selection = max(selection - 1, 1);
} else {
if (prompt.handle_key(static_cast<Term::Key>(ch))) {
selection = 1;
}
}
tty.putchar('\n');
tty.erase_display(Term::FORWARD);
}
tty.move_to_col(1);
tty.erase_display(Term::FORWARD);
if (ch == Term::ENTER) {
cout << input[selection - 1].str.c_str() << endl;
return 0;
}
return 1;
}
<commit_msg>Handle arrow keys<commit_after>#include "match.h"
#include "term.h"
#include "prompt.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
static const int MAXLINES = 20;
static char handle_escape(Term &tty);
int main(void)
{
vector<wstr> input;
string line;
while (getline(cin, line)) input.emplace_back(line);
Term tty("/dev/tty");
Term::Size screen_size = tty.get_screen_size();
char ch;
int selection = 1;
Prompt prompt(tty, "> ");
tty.erase_display(Term::FORWARD);
for (;;) {
auto last = match(input.begin(), input.end(), prompt.query());
auto it = input.cbegin();
int i = 1;
for (; it != last; ++i, ++it) {
string str = (*it).str.substr(0, screen_size.columns);
if (i == selection) {
tty.puts_highlighted(str);
} else {
tty.puts(str);
}
if (i == MAXLINES)
break;
tty.putchar('\n');
}
tty.cursor_up(i);
tty.move_to_col(prompt.current_column());
ch = tty.getchar();
if (ch == Term::ESC) {
ch = handle_escape(tty);
}
if (ch == Term::CTRL_C || ch == Term::ENTER) {
break;
} else if (ch == Term::CTRL_N) {
selection = min(selection + 1, i - 1);
} else if (ch == Term::CTRL_P) {
selection = max(selection - 1, 1);
} else if (prompt.handle_key(static_cast<Term::Key>(ch))) {
selection = 1;
}
tty.putchar('\n');
tty.erase_display(Term::FORWARD);
}
tty.move_to_col(1);
tty.erase_display(Term::FORWARD);
if (ch == Term::ENTER) {
cout << input[selection - 1].str.c_str() << endl;
return 0;
}
return 1;
}
static char handle_escape(Term &tty)
{
char ch = tty.getchar();
if (ch != '[') {
return ch;
}
ch = tty.getchar();
if (ch == 'A' || ch == 'D') {
return Term::CTRL_P;
} else if (ch == 'B' || ch == 'C') {
return Term::CTRL_N;
} else {
return 0;
}
}
<|endoftext|>
|
<commit_before>#include "phInput.h"
#include <fstream>
#include <map>
#include "ph.h"
#include <cassert>
namespace ph {
static void setDefaults(Input& in)
{
in.outMeshFileName = "";
in.numSplit = 10;
in.tetrahedronize = 0;
in.localPtn = true;
in.recursivePtn = -1;
in.recursiveUR = 1;
in.parmaPtn = 0; // No Parma by default
in.displacementMigration = 0; // Do not migrate displacement field by default
in.dwalMigration = 0; // Do not migrate dwal field by default
in.buildMapping = 0; // Do not build the mapping field by default
in.elementsPerMigration = 1000*1000; // 100k elms per round
in.threaded = 1;
in.initBubbles = 0;
in.formElementGraph = 0;
in.restartFileName = "restart";
in.phastaIO = 1;
in.snap = 0;
in.splitAllLayerEdges = 0;
in.filterMatches = 0;
in.axisymmetry = 0;
}
Input::Input()
{
setDefaults(*this);
}
typedef std::map<std::string, std::string*> StringMap;
typedef std::map<std::string, int*> IntMap;
static void formMaps(Input& in, StringMap& stringMap, IntMap& intMap)
{
intMap["globalP"] = &in.globalP;
intMap["timeStepNumber"] = &in.timeStepNumber;
intMap["ensa_dof"] = &in.ensa_dof;
stringMap["restartFileName"] = &in.restartFileName;
stringMap["attributeFileName"] = &in.attributeFileName;
stringMap["meshFileName"] = &in.meshFileName;
stringMap["outMeshFileName"] = &in.outMeshFileName;
stringMap["modelFileName"] = &in.modelFileName;
stringMap["outputFormat"] = &in.outputFormat;
stringMap["partitionMethod"] = &in.partitionMethod;
intMap["adaptFlag"] = &in.adaptFlag;
intMap["rRead"] = &in.rRead;
intMap["rStart"] = &in.rStart;
intMap["AdaptStrategy"] = &in.adaptStrategy;
intMap["RecursiveUR"] = &in.recursiveUR;
intMap["Periodic"] = &in.periodic;
intMap["prCD"] = &in.prCD;
intMap["timing"] = &in.timing;
intMap["internalBCNodes"] = &in.internalBCNodes;
intMap["WRITEASC"] = &in.writeDebugFiles;
intMap["phastaIO"] = &in.phastaIO;
intMap["splitFactor"] = &in.splitFactor;
intMap["SolutionMigration"] = &in.solutionMigration;
intMap["DisplacementMigration"] = &in.displacementMigration;
intMap["isReorder"] = &in.isReorder;
intMap["numSplit"] = &in.numSplit;
intMap["Tetrahedronize"] = &in.tetrahedronize;
intMap["LocalPtn"] = &in.localPtn;
intMap["RecursivePtn"] = &in.recursivePtn;
intMap["ParmaPtn"] = &in.parmaPtn;
intMap["dwalMigration"] = &in.dwalMigration;
intMap["buildMapping"] = &in.buildMapping;
intMap["elementsPerMigration"] = &in.elementsPerMigration;
intMap["threaded"] = &in.threaded;
intMap["initBubbles"] = &in.initBubbles;
intMap["formElementGraph"] = &in.formElementGraph;
intMap["snap"] = &in.snap;
intMap["splitAllLayerEdges"] = &in.splitAllLayerEdges;
intMap["filterMatches"] = &in.filterMatches;
intMap["axisymmetry"] = &in.axisymmetry;
}
template <class T>
static bool tryReading(std::string const& name,
std::ifstream& f,
std::map<std::string, T*>& map)
{
typename std::map<std::string, T*>::iterator it = map.find(name);
if (it == map.end())
return false;
f >> *(it->second);
return true;
}
static void readInputFile(
Input& in,
const char* filename,
std::map<std::string, std::string*>& stringMap,
std::map<std::string, int*>& intMap)
{
std::ifstream f(filename);
if (!f)
fail("could not open \"%s\"", filename);
std::string name;
while (f >> name) {
if (name[0] == '#') {
std::getline(f, name, '\n');
continue;
}
if (tryReading(name, f, stringMap))
continue;
if (tryReading(name, f, intMap))
continue;
/* the WEIRD parameter ! */
if (name == "RecursivePtnStep") {
if (in.recursivePtn == -1)
fail("RecursivePtn needs to be set before RecursivePtnStep");
in.recursivePtnStep.allocate(in.recursivePtn);
for (int i = 0; i < in.recursivePtn; ++i)
f >> in.recursivePtnStep[i];
continue;
}
fail("unknown variable \"%s\" in %s\n", name.c_str(), filename);
}
}
static bool contains(std::string const& a, std::string const& b)
{
return a.find(b) != std::string::npos;
}
static void validate(Input& in)
{
assert(in.parmaPtn == 0 || in.parmaPtn == 1);
if (in.adaptFlag)
assert(contains(in.attributeFileName, "NOIC.spj"));
assert(in.threaded);
assert( ! (in.buildMapping && in.adaptFlag));
}
void Input::load(const char* filename)
{
setDefaults(*this);
std::map<std::string, std::string*> stringMap;
std::map<std::string, int*> intMap;
formMaps(*this, stringMap, intMap);
readInputFile(*this, filename, stringMap, intMap);
validate(*this);
}
/* see the comments in phBC.h and
phOutput.h for explanations about
these count*BCs functions */
int countNaturalBCs(Input& in)
{
return in.ensa_dof + 1;
}
int countEssentialBCs(Input& in)
{
return in.ensa_dof + 7;
}
int countScalarBCs(Input& in)
{
return in.ensa_dof - 5;
}
}
<commit_msg>remove old Chef asserts<commit_after>#include "phInput.h"
#include <fstream>
#include <map>
#include "ph.h"
#include <cassert>
namespace ph {
static void setDefaults(Input& in)
{
in.outMeshFileName = "";
in.numSplit = 10;
in.tetrahedronize = 0;
in.localPtn = true;
in.recursivePtn = -1;
in.recursiveUR = 1;
in.parmaPtn = 0; // No Parma by default
in.displacementMigration = 0; // Do not migrate displacement field by default
in.dwalMigration = 0; // Do not migrate dwal field by default
in.buildMapping = 0; // Do not build the mapping field by default
in.elementsPerMigration = 1000*1000; // 100k elms per round
in.threaded = 1;
in.initBubbles = 0;
in.formElementGraph = 0;
in.restartFileName = "restart";
in.phastaIO = 1;
in.snap = 0;
in.splitAllLayerEdges = 0;
in.filterMatches = 0;
in.axisymmetry = 0;
}
Input::Input()
{
setDefaults(*this);
}
typedef std::map<std::string, std::string*> StringMap;
typedef std::map<std::string, int*> IntMap;
static void formMaps(Input& in, StringMap& stringMap, IntMap& intMap)
{
intMap["globalP"] = &in.globalP;
intMap["timeStepNumber"] = &in.timeStepNumber;
intMap["ensa_dof"] = &in.ensa_dof;
stringMap["restartFileName"] = &in.restartFileName;
stringMap["attributeFileName"] = &in.attributeFileName;
stringMap["meshFileName"] = &in.meshFileName;
stringMap["outMeshFileName"] = &in.outMeshFileName;
stringMap["modelFileName"] = &in.modelFileName;
stringMap["outputFormat"] = &in.outputFormat;
stringMap["partitionMethod"] = &in.partitionMethod;
intMap["adaptFlag"] = &in.adaptFlag;
intMap["rRead"] = &in.rRead;
intMap["rStart"] = &in.rStart;
intMap["AdaptStrategy"] = &in.adaptStrategy;
intMap["RecursiveUR"] = &in.recursiveUR;
intMap["Periodic"] = &in.periodic;
intMap["prCD"] = &in.prCD;
intMap["timing"] = &in.timing;
intMap["internalBCNodes"] = &in.internalBCNodes;
intMap["WRITEASC"] = &in.writeDebugFiles;
intMap["phastaIO"] = &in.phastaIO;
intMap["splitFactor"] = &in.splitFactor;
intMap["SolutionMigration"] = &in.solutionMigration;
intMap["DisplacementMigration"] = &in.displacementMigration;
intMap["isReorder"] = &in.isReorder;
intMap["numSplit"] = &in.numSplit;
intMap["Tetrahedronize"] = &in.tetrahedronize;
intMap["LocalPtn"] = &in.localPtn;
intMap["RecursivePtn"] = &in.recursivePtn;
intMap["ParmaPtn"] = &in.parmaPtn;
intMap["dwalMigration"] = &in.dwalMigration;
intMap["buildMapping"] = &in.buildMapping;
intMap["elementsPerMigration"] = &in.elementsPerMigration;
intMap["threaded"] = &in.threaded;
intMap["initBubbles"] = &in.initBubbles;
intMap["formElementGraph"] = &in.formElementGraph;
intMap["snap"] = &in.snap;
intMap["splitAllLayerEdges"] = &in.splitAllLayerEdges;
intMap["filterMatches"] = &in.filterMatches;
intMap["axisymmetry"] = &in.axisymmetry;
}
template <class T>
static bool tryReading(std::string const& name,
std::ifstream& f,
std::map<std::string, T*>& map)
{
typename std::map<std::string, T*>::iterator it = map.find(name);
if (it == map.end())
return false;
f >> *(it->second);
return true;
}
static void readInputFile(
Input& in,
const char* filename,
std::map<std::string, std::string*>& stringMap,
std::map<std::string, int*>& intMap)
{
std::ifstream f(filename);
if (!f)
fail("could not open \"%s\"", filename);
std::string name;
while (f >> name) {
if (name[0] == '#') {
std::getline(f, name, '\n');
continue;
}
if (tryReading(name, f, stringMap))
continue;
if (tryReading(name, f, intMap))
continue;
/* the WEIRD parameter ! */
if (name == "RecursivePtnStep") {
if (in.recursivePtn == -1)
fail("RecursivePtn needs to be set before RecursivePtnStep");
in.recursivePtnStep.allocate(in.recursivePtn);
for (int i = 0; i < in.recursivePtn; ++i)
f >> in.recursivePtnStep[i];
continue;
}
fail("unknown variable \"%s\" in %s\n", name.c_str(), filename);
}
}
static bool contains(std::string const& a, std::string const& b)
{
return a.find(b) != std::string::npos;
}
static void validate(Input& in)
{
assert(in.parmaPtn == 0 || in.parmaPtn == 1);
assert( ! (in.buildMapping && in.adaptFlag));
}
void Input::load(const char* filename)
{
setDefaults(*this);
std::map<std::string, std::string*> stringMap;
std::map<std::string, int*> intMap;
formMaps(*this, stringMap, intMap);
readInputFile(*this, filename, stringMap, intMap);
validate(*this);
}
/* see the comments in phBC.h and
phOutput.h for explanations about
these count*BCs functions */
int countNaturalBCs(Input& in)
{
return in.ensa_dof + 1;
}
int countEssentialBCs(Input& in)
{
return in.ensa_dof + 7;
}
int countScalarBCs(Input& in)
{
return in.ensa_dof - 5;
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin
Copyright (C) 1998, 1999 by Jorrit Tyberghein
Written by Nathaniel 'NooTe' Saint Martin
Linux sound driver by Gert Steenssens <gsteenss@eps.agfa.be>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#if defined(OS_BSD)
# include <machine/soundcard.h>
#else
# include <sys/soundcard.h>
#endif
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <signal.h>
#include "sysdef.h"
#include "csutil/scf.h"
#include "cssnddrv/oss/ossdrv.h"
#include "iplugin.h"
#include "isystem.h"
#include "isndlstn.h"
#include "isndsrc.h"
IMPLEMENT_FACTORY(csSoundDriverOSS)
EXPORT_CLASS_TABLE(ossdrv)
EXPORT_CLASS(csSoundDriverOSS, "crystalspace.sound.driver.oss", "OSS Sounddriver for Crystal Space")
EXPORT_CLASS_TABLE_END;
IMPLEMENT_IBASE(csSoundDriverOSS)
IMPLEMENTS_INTERFACE(iPlugIn)
IMPLEMENTS_INTERFACE(iSoundDriver)
IMPLEMENT_IBASE_END;
int lasterr=0;
int gaudio;
bool inUse=false;
char *err[]={ "no error", "get semaphore", "dec semaphore", "inc semaphore",
"malloc shmptr", "shmget soundmem", "mark shared mem as removable",
"mapping shared mem", "detaching shared mem", "msgsnd",
"semget", "semctl", "get audio queue", "opening audio device",
"setting samplesize", "setting mono/stereo",
"setting frequence", "reading blocksize",
"setting signalhandler", "setting timer", "set fragment size",
"alloc soundbuffer" };
#define err_alloc_soundbuffer 21
#define err_set_fragment_size 20
#define err_set_timer 19
#define err_set_handler 18
#define err_get_blocksize 17
#define err_set_frequence 16
#define err_set_stereo 15
#define err_set_samplesize 14
#define err_open_dsp 13
#define err_create_queue 12
#define err_semctl 11
#define err_semget 10
#define err_msgsnd 9
#define err_shm_unmap 8
#define err_shm_map 7
#define err_shmctl_remove 6
#define err_shmget_soundmem 5
#define err_malloc_shmptr 4
#define err_inc_sem 3
#define err_dec_sem 2
#define err_get_sem 1
#define err_no_err 0
bool AudioDeviceBlocked()
{
// are there free fragments to fill in the soundbuffer ?
audio_buf_info info;
ioctl(gaudio, SNDCTL_DSP_GETOSPACE, &info);
/* Thats what the OSS-specification has to say:
Number of full fragments that can be read or written without
blocking.Note that this field is reliable only when the
application reads/writes full fragments at time.
*/
return info.fragments == 0;
}
AudioDevice::AudioDevice()
{
audio = -1;
}
bool AudioDevice::Open(int& frequency, bool& bit16, bool& stereo, int& fragments, int& block_size)
{
int dsp_sample,dsp_stereo,dsp_speed;
bool succ;
dsp_speed = frequency;
dsp_stereo = stereo;
dsp_sample = ( bit16 ? 16 : 8 );
lasterr=err_open_dsp;
audio = open( SOUND_DEVICE, O_WRONLY, 0);
succ = audio != -1;
if ( succ ) lasterr=err_set_samplesize;
succ = succ && ioctl(audio, SNDCTL_DSP_SAMPLESIZE, &dsp_sample) != -1;
if ( succ ) lasterr=err_set_stereo;
succ = succ && ioctl (audio, SNDCTL_DSP_STEREO, &dsp_stereo) != -1;
if ( succ ) lasterr=err_set_frequence;
succ = succ && ioctl (audio, SNDCTL_DSP_SPEED, &dsp_speed) != -1;
if ( succ ){
unsigned int bytes_per_second;
int frag_size; // fragment size
int num_frag=0; // number of fragments
int hlp;
// ok, now we know what our soundcard is capable of :)
// we close it, reopen it and setting the blocksize appropriate for our needs
close( audio );
lasterr=err_open_dsp;
audio = open( SOUND_DEVICE, O_WRONLY, 0);
succ = audio != -1;
gaudio = audio;
// this amount of bytes we pump per second through the audio-device
bytes_per_second = dsp_speed * (dsp_sample/8) * ( dsp_stereo ? 2 : 1 );
// the OSS-specification adivises to use relativly small fragment-sizes
// ( the smallest possible is 256 byte )
// lets use a fragmentsize of 8192 bytes
frag_size = 13; // ( 2^13=8192 );
hlp = bytes_per_second >> frag_size;
while ( hlp ){
num_frag++;
hlp = hlp >> 1;
}
// num_frag++;
fragments = 1 << num_frag;
hlp = ( num_frag << 16 ) | frag_size;
if ( succ ) lasterr=err_set_fragment_size;
succ = succ && ioctl (audio, SNDCTL_DSP_SETFRAGMENT, &hlp) != -1;
if ( succ ) lasterr=err_set_samplesize;
succ = succ && ioctl(audio, SNDCTL_DSP_SAMPLESIZE, &dsp_sample) != -1;
if ( succ ) lasterr=err_set_stereo;
succ = succ && ioctl (audio, SNDCTL_DSP_STEREO, &dsp_stereo) != -1;
if ( succ ) lasterr=err_set_frequence;
succ = succ && ioctl (audio, SNDCTL_DSP_SPEED, &dsp_speed) != -1;
if ( succ ){
block_size=8192;
fprintf( stderr, "block_size: %d\n", block_size );
frequency = dsp_speed;
stereo = dsp_stereo;
bit16 = ( dsp_sample == 16 ? true : false );
}
}
return succ;
}
void AudioDevice::Close()
{
if ( audio != -1 ){
// close audio device
close(audio);
audio = -1;
}
}
void AudioDevice::Play( unsigned char *snddata, int len )
{
write( audio, snddata, len );
}
static void* soundptr;
void isTime(int)
{
iSoundRender *mysound=(iSoundRender*)soundptr;
if (!AudioDeviceBlocked())
mysound->MixingFunction();
}
bool csSoundDriverOSS::SetupTimer( int nTimesPerSecond )
{
struct itimerval itime;
struct timeval val;
struct sigaction act;
val.tv_usec= 1000 / nTimesPerSecond;
val.tv_sec=0;
itime.it_value=val;
itime.it_interval=val;
act.sa_handler = isTime;
sigemptyset( &act.sa_mask );
sigaddset( &act.sa_mask, SIGVTALRM );
act.sa_flags = SA_NOCLDSTOP | SA_RESTART;
// set static ptr because the timer handler needs it...
soundptr=(void*)m_piSoundRender;
// set signal handling function
/*
* LINUX-behavior: Dont use signal coz it resets after execution of handlerfunction.
* sigaction is a way to make it BSD-like.
* NOTE: its not POSIX setting sa_flags to SA_RESTART ( from the man page )
*/
lasterr=err_set_handler;
bSignalInstalled = (sigaction (SIGVTALRM, &act, &oldact) == 0);
if ( bSignalInstalled ) lasterr=err_set_timer;
// set timer
bTimerInstalled = bSignalInstalled && setitimer (ITIMER_VIRTUAL,&itime,&otime) != -1;
return bTimerInstalled;
}
csSoundDriverOSS::csSoundDriverOSS(iBase *piBase)
{
CONSTRUCT_IBASE(piBase);
m_piSystem = NULL;
m_piSoundRender = NULL;
memorysize = 0;
memory = NULL;
volume = 1.0;
block_size=0;
block = 0;
fragments = 0;
soundbuffer = NULL;
bSignalInstalled = false;
bTimerInstalled = false;
}
csSoundDriverOSS::~csSoundDriverOSS()
{
// if(memory) delete [] memory;
}
bool csSoundDriverOSS::Initialize(iSystem *iSys)
{
m_piSystem = iSys;
return true;
}
bool csSoundDriverOSS::Open(iSoundRender *render, int frequency, bool bit16, bool stereo)
{
SysPrintf (MSG_INITIALIZATION, "\nSoundDriver OSS selected\n");
m_piSoundRender = render;
m_bStereo = stereo;
m_b16Bits = bit16;
m_nFrequency = frequency;
bool Active = device.Open(frequency,bit16,stereo, fragments, block_size);
if ( Active ){
lasterr = err_alloc_soundbuffer;
soundbuffer = new unsigned char[ fragments * block_size ];
Active = (soundbuffer != NULL ) && SetupTimer( fragments );
}
if ( !Active )
{
perror( err[ lasterr ] );
return false;
}
SysPrintf (MSG_INITIALIZATION, "Sound initialized to %d Hz %d bits %s\n", m_nFrequency, (m_b16Bits)?16:8, (m_bStereo)?"Stereo":"Mono");
return true;
}
void csSoundDriverOSS::Close()
{
if (bTimerInstalled) setitimer (ITIMER_VIRTUAL, &otime, NULL);
if (bSignalInstalled) sigaction (SIGVTALRM, &oldact, NULL);
if ( soundbuffer ) { delete soundbuffer; soundbuffer=NULL; }
device.Close();
memory=NULL;
memorysize=0;
}
void csSoundDriverOSS::SetVolume(float vol) { volume = vol; }
float csSoundDriverOSS::GetVolume() { return volume; }
void csSoundDriverOSS::LockMemory(void **mem, int *memsize)
{
*mem = &soundbuffer[ block * block_size ];
*memsize = block_size;
}
void csSoundDriverOSS::UnlockMemory()
{
// tell device to play this soundblock
device.Play( &soundbuffer[ block * block_size], block_size );
block = (block+1) % fragments;
}
bool csSoundDriverOSS::IsHandleVoidSound() { return true; }
bool csSoundDriverOSS::IsBackground() { return true; }
bool csSoundDriverOSS::Is16Bits() { return m_b16Bits; }
bool csSoundDriverOSS::IsStereo() { return m_bStereo; }
int csSoundDriverOSS::GetFrequency() { return m_nFrequency; }
void csSoundDriverOSS::SysPrintf(int mode, char* szMsg, ...)
{
char buf[1024];
va_list arg;
va_start (arg, szMsg);
vsprintf (buf, szMsg, arg);
va_end (arg);
m_piSystem->Print(mode, buf);
}
<commit_msg><commit_after>/*
Copyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin
Copyright (C) 1998, 1999 by Jorrit Tyberghein
Written by Nathaniel 'NooTe' Saint Martin
Linux sound driver by Gert Steenssens <gsteenss@eps.agfa.be>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#if defined(OS_BSD)
# include <machine/soundcard.h>
#else
# include <sys/soundcard.h>
#endif
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <signal.h>
#include "sysdef.h"
#include "csutil/scf.h"
#include "cssnddrv/oss/ossdrv.h"
#include "iplugin.h"
#include "isystem.h"
#include "isndlstn.h"
#include "isndsrc.h"
IMPLEMENT_FACTORY(csSoundDriverOSS)
EXPORT_CLASS_TABLE(ossdrv)
EXPORT_CLASS(csSoundDriverOSS, "crystalspace.sound.driver.oss", "OSS Sounddriver for Crystal Space")
EXPORT_CLASS_TABLE_END;
IMPLEMENT_IBASE(csSoundDriverOSS)
IMPLEMENTS_INTERFACE(iPlugIn)
IMPLEMENTS_INTERFACE(iSoundDriver)
IMPLEMENT_IBASE_END;
int lasterr=0;
int gaudio;
bool inUse=false;
char *err[]={ "no error", "get semaphore", "dec semaphore", "inc semaphore",
"malloc shmptr", "shmget soundmem", "mark shared mem as removable",
"mapping shared mem", "detaching shared mem", "msgsnd",
"semget", "semctl", "get audio queue", "opening audio device",
"setting samplesize", "setting mono/stereo",
"setting frequence", "reading blocksize",
"setting signalhandler", "setting timer", "set fragment size",
"alloc soundbuffer" };
#define err_alloc_soundbuffer 21
#define err_set_fragment_size 20
#define err_set_timer 19
#define err_set_handler 18
#define err_get_blocksize 17
#define err_set_frequence 16
#define err_set_stereo 15
#define err_set_samplesize 14
#define err_open_dsp 13
#define err_create_queue 12
#define err_semctl 11
#define err_semget 10
#define err_msgsnd 9
#define err_shm_unmap 8
#define err_shm_map 7
#define err_shmctl_remove 6
#define err_shmget_soundmem 5
#define err_malloc_shmptr 4
#define err_inc_sem 3
#define err_dec_sem 2
#define err_get_sem 1
#define err_no_err 0
bool AudioDeviceBlocked()
{
// are there free fragments to fill in the soundbuffer ?
audio_buf_info info;
ioctl(gaudio, SNDCTL_DSP_GETOSPACE, &info);
/* Thats what the OSS-specification has to say:
Number of full fragments that can be read or written without
blocking.Note that this field is reliable only when the
application reads/writes full fragments at time.
*/
return info.fragments == 0;
}
AudioDevice::AudioDevice()
{
audio = -1;
}
bool AudioDevice::Open(int& frequency, bool& bit16, bool& stereo, int& fragments, int& block_size)
{
int dsp_sample,dsp_stereo,dsp_speed;
bool succ;
dsp_speed = frequency;
dsp_stereo = stereo;
dsp_sample = ( bit16 ? 16 : 8 );
lasterr=err_open_dsp;
audio = open( SOUND_DEVICE, O_WRONLY, 0);
succ = audio != -1;
if ( succ ) lasterr=err_set_samplesize;
succ = succ && ioctl(audio, SNDCTL_DSP_SAMPLESIZE, &dsp_sample) != -1;
if ( succ ) lasterr=err_set_stereo;
succ = succ && ioctl (audio, SNDCTL_DSP_STEREO, &dsp_stereo) != -1;
if ( succ ) lasterr=err_set_frequence;
succ = succ && ioctl (audio, SNDCTL_DSP_SPEED, &dsp_speed) != -1;
if ( succ ){
unsigned int bytes_per_second;
int frag_size; // fragment size
int num_frag=0; // number of fragments
int hlp;
// ok, now we know what our soundcard is capable of :)
// we close it, reopen it and setting the blocksize appropriate for our needs
close( audio );
lasterr=err_open_dsp;
audio = open( SOUND_DEVICE, O_WRONLY, 0);
succ = audio != -1;
gaudio = audio;
// this amount of bytes we pump per second through the audio-device
bytes_per_second = dsp_speed * (dsp_sample/8) * ( dsp_stereo ? 2 : 1 );
// the OSS-specification adivises to use relativly small fragment-sizes
// ( the smallest possible is 256 byte )
// lets use a fragmentsize of 8192 bytes
frag_size = 13; // ( 2^13=8192 );
hlp = bytes_per_second >> frag_size;
while ( hlp ){
num_frag++;
hlp = hlp >> 1;
}
// num_frag++;
fragments = 1 << num_frag;
hlp = ( num_frag << 16 ) | frag_size;
if ( succ ) lasterr=err_set_fragment_size;
succ = succ && ioctl (audio, SNDCTL_DSP_SETFRAGMENT, &hlp) != -1;
if ( succ ) lasterr=err_set_samplesize;
succ = succ && ioctl(audio, SNDCTL_DSP_SAMPLESIZE, &dsp_sample) != -1;
if ( succ ) lasterr=err_set_stereo;
succ = succ && ioctl (audio, SNDCTL_DSP_STEREO, &dsp_stereo) != -1;
if ( succ ) lasterr=err_set_frequence;
succ = succ && ioctl (audio, SNDCTL_DSP_SPEED, &dsp_speed) != -1;
if ( succ ){
block_size=8192;
fprintf( stderr, "block_size: %d\n", block_size );
frequency = dsp_speed;
stereo = dsp_stereo;
bit16 = ( dsp_sample == 16 ? true : false );
}
}
return succ;
}
void AudioDevice::Close()
{
if ( audio != -1 ){
// close audio device
close(audio);
audio = -1;
}
}
void AudioDevice::Play( unsigned char *snddata, int len )
{
write( audio, snddata, len );
}
static void* soundptr;
void isTime(int)
{
iSoundRender *mysound=(iSoundRender*)soundptr;
if (!AudioDeviceBlocked())
mysound->MixingFunction();
}
bool csSoundDriverOSS::SetupTimer( int nTimesPerSecond )
{
struct itimerval itime;
struct timeval val;
struct sigaction act;
val.tv_usec= 1000 / nTimesPerSecond;
val.tv_sec=0;
itime.it_value=val;
itime.it_interval=val;
act.sa_handler = isTime;
sigemptyset( &act.sa_mask );
sigaddset( &act.sa_mask, SIGVTALRM );
act.sa_flags = SA_NOCLDSTOP | SA_RESTART;
// set static ptr because the timer handler needs it...
soundptr=(void*)m_piSoundRender;
// set signal handling function
/*
* LINUX-behavior: Dont use signal coz it resets after execution of handlerfunction.
* sigaction is a way to make it BSD-like.
* NOTE: its not POSIX setting sa_flags to SA_RESTART ( from the man page )
*/
lasterr=err_set_handler;
bSignalInstalled = (sigaction (SIGVTALRM, &act, &oldact) == 0);
if ( bSignalInstalled ) lasterr=err_set_timer;
// set timer
bTimerInstalled = bSignalInstalled && setitimer (ITIMER_VIRTUAL,&itime,&otime) != -1;
return bTimerInstalled;
}
csSoundDriverOSS::csSoundDriverOSS(iBase *piBase)
{
CONSTRUCT_IBASE(piBase);
m_piSystem = NULL;
m_piSoundRender = NULL;
memorysize = 0;
memory = NULL;
volume = 1.0;
block_size=0;
block = 0;
fragments = 0;
soundbuffer = NULL;
bSignalInstalled = false;
bTimerInstalled = false;
}
csSoundDriverOSS::~csSoundDriverOSS()
{
// if(memory) delete [] memory;
}
bool csSoundDriverOSS::Initialize(iSystem *iSys)
{
m_piSystem = iSys;
return true;
}
bool csSoundDriverOSS::Open(iSoundRender *render, int frequency, bool bit16, bool stereo)
{
SysPrintf (MSG_INITIALIZATION, "\nSoundDriver OSS selected\n");
m_piSoundRender = render;
m_bStereo = stereo;
m_b16Bits = bit16;
m_nFrequency = frequency;
bool Active = device.Open(frequency,bit16,stereo, fragments, block_size);
if ( Active ){
lasterr = err_alloc_soundbuffer;
soundbuffer = new unsigned char[ fragments * block_size ];
Active = (soundbuffer != NULL ) && SetupTimer( fragments );
}
if ( !Active )
{
perror( err[ lasterr ] );
return false;
}
SysPrintf (MSG_INITIALIZATION, "Sound initialized to %d Hz %d bits %s\n", m_nFrequency, (m_b16Bits)?16:8, (m_bStereo)?"Stereo":"Mono");
return true;
}
void csSoundDriverOSS::Close()
{
if (bTimerInstalled) setitimer (ITIMER_VIRTUAL, &otime, NULL);
if (bSignalInstalled) sigaction (SIGVTALRM, &oldact, NULL);
if ( soundbuffer ) { delete soundbuffer; soundbuffer=NULL; }
device.Close();
memory=NULL;
memorysize=0;
}
void csSoundDriverOSS::SetVolume(float vol) { volume = vol; }
float csSoundDriverOSS::GetVolume() { return volume; }
void csSoundDriverOSS::LockMemory(void **mem, int *memsize)
{
*mem = &soundbuffer[ block * block_size ];
*memsize = block_size;
}
void csSoundDriverOSS::UnlockMemory()
{
// tell device to play this soundblock
device.Play( &soundbuffer[ block * block_size], block_size );
block = (block+1) % fragments;
}
bool csSoundDriverOSS::IsHandleVoidSound() { return true; }
bool csSoundDriverOSS::IsBackground() { return true; }
bool csSoundDriverOSS::Is16Bits() { return m_b16Bits; }
bool csSoundDriverOSS::IsStereo() { return m_bStereo; }
int csSoundDriverOSS::GetFrequency() { return m_nFrequency; }
void csSoundDriverOSS::SysPrintf(int mode, char* szMsg, ...)
{
char buf[1024];
va_list arg;
va_start (arg, szMsg);
vsprintf (buf, szMsg, arg);
va_end (arg);
m_piSystem->Printf(mode, buf);
}
<|endoftext|>
|
<commit_before>#include "rainbow.h"
//Constructor
Rainbow::Rainbow(CRGB *Leds, int iLeds) : Animation(Leds, iLeds)
{
iGlobalPos = 0;
}
//animate next step
void Rainbow::doNextStep()
{
iGlobalPos++;
if(iGlobalPos >= iLedCount)
{
iGlobalPos = 0;
}
const int iSectorSize = iLedCount / 6;
int iRest = iLedCount % 6;
int iMaxColor = 120; //set maxColor lower than 255 to allow adding lighting waves.
//set the curent color of each LED
for(int iSector = 0; iSector < 6; iSector++)
{
//add one step as long as rest is available. This may make the first gradients one longer than the last.
int iCurSectorSize = iSectorSize;
if(iRest > 0)
{
iRest--;
iCurSectorSize++;
}
int iStepSize = iMaxColor / iCurSectorSize;
for(int iCurPos = 0; iCurPos < iCurSectorSize; iCurPos++)
{
int r = 0, g = 0, b = 0;
int iColor = iStepSize * iCurPos;
switch(iSector)
{
case 0: //red to yellow
r = iMaxColor;
g = iColor;
break;
case 1: //yellow to green
r = iMaxColor - iColor;
g = iMaxColor;
break;
case 2: //green to cyan
g = iMaxColor;
b = iColor;
break;
case 3: //cyan to blue
g = iMaxColor - iColor;
b = iMaxColor;
break;
case 4: //blue to magenta
r = iColor;
b = iMaxColor;
break;
case 5: //magenta to red
r = iMaxColor;
b = iMaxColor - iColor;
break;
}
// set Position in relation to current rotation offset
int iPos = iGlobalPos + (iCurPos + iSectorSize * iSector);
if(iPos >= iLedCount)
{
iPos -= iLedCount;
}
pLEDS[iPos] = CRGB(r,g,b);
}
}
//set the lighting waves
for(int iWave = 0; iWave < 3; iWave++)
{
int iWavePos = (iGlobalPos * -1) + (iLedCount - 1) + iWave * (iLedCount / 3);
for(int iWavePart = -4; iWavePart <= 4; iWavePart++)
{
int iPos = iWavePos + iWavePart;
if(iPos >= iLedCount)
{
iPos -= iLedCount;
}
else if(iPos < 0)
{
iPos += iLedCount;
}
CRGB Led = pLEDS[iPos];
int iFactor = iWavePart;
if(iFactor < 0)
{
iFactor *= -1;
}
int iDiff = 255 - iMaxColor;
int iStep = iDiff / 4;
Led += iDiff - (iFactor * iStep);
pLEDS[iPos] = Led;
}
}
}
<commit_msg>debugging rainbow started<commit_after>#include "rainbow.h"
//Constructor
Rainbow::Rainbow(CRGB *Leds, int iLeds) : Animation(Leds, iLeds)
{
iGlobalPos = 0;
}
//animate next step
void Rainbow::doNextStep()
{
iGlobalPos++;
if(iGlobalPos >= iLedCount)
{
iGlobalPos = 0;
}
const int iSectorSize = iLedCount / 6;
int iRest = iLedCount % 6;
int iMaxColor = 120; //set maxColor lower than 255 to allow adding lighting waves.
memset(pLEDS, 0, iLedCount * sizeof(struct CRGB)); //set all LEDs to black (for debugging reasons)
//set the curent color of each LED
for(int iSector = 0; iSector < 6; iSector++)
{
//add one step as long as rest is available. This may make the first gradients one longer than the last.
int iCurSectorSize = iSectorSize;
if(iRest > 0)
{
iRest--;
iCurSectorSize++;
}
int iStepSize = iMaxColor / iCurSectorSize;
for(int iCurPos = 0; iCurPos < iCurSectorSize; iCurPos++)
{
int r = 0, g = 0, b = 0;
int iColor = iStepSize * iCurPos;
switch(iSector)
{
case 0: //red to yellow
r = iMaxColor;
g = iColor;
break;
case 1: //yellow to green
r = iMaxColor - iColor;
g = iMaxColor;
break;
case 2: //green to cyan
g = iMaxColor;
b = iColor;
break;
case 3: //cyan to blue
g = iMaxColor - iColor;
b = iMaxColor;
break;
case 4: //blue to magenta
r = iColor;
b = iMaxColor;
break;
case 5: //magenta to red
r = iMaxColor;
b = iMaxColor - iColor;
break;
}
// set position in relation to current rotation offset
int iPos = iGlobalPos + (iCurPos + iCurSectorSize * iSector);
if(iPos >= iLedCount)
{
iPos -= iLedCount;
}
pLEDS[iPos] = CRGB(r,g,b);
}
}
//set the lighting waves
for(int iWave = 0; iWave < 3; iWave++)
{
int iWavePos = (iGlobalPos * -1) + (iLedCount - 1) + iWave * (iLedCount / 3);
for(int iWavePart = -3; iWavePart <= 3; iWavePart++)
{
int iPos = iWavePos + iWavePart;
if(iPos >= iLedCount)
{
iPos -= iLedCount;
}
else if(iPos < 0)
{
iPos += iLedCount;
}
CRGB Led = pLEDS[iPos];
int iFactor = iWavePart;
if(iFactor < 0)
{
iFactor *= -1;
}
int iDiff = 255 - iMaxColor;
int iStep = iDiff / 4;
Led += iDiff - (iFactor * iStep);
pLEDS[iPos] = Led;
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2009 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 "printing/page_overlays.h"
#include "app/gfx/text_elider.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "printing/printed_document.h"
#include "printing/printed_page.h"
namespace {
// Replaces a subpart of a string by other value, and returns the position right
// after the new value.
size_t ReplaceKey(std::wstring* string,
size_t offset,
size_t old_string_len,
const std::wstring& new_string) {
string->replace(offset, old_string_len, new_string);
return offset + new_string.size();
}
} // namespace
namespace printing {
const wchar_t* const PageOverlays::kTitle = L"{title}";
const wchar_t* const PageOverlays::kTime = L"{time}";
const wchar_t* const PageOverlays::kDate = L"{date}";
const wchar_t* const PageOverlays::kPage = L"{page}";
const wchar_t* const PageOverlays::kPageCount = L"{pagecount}";
const wchar_t* const PageOverlays::kPageOnTotal = L"{pageontotal}";
const wchar_t* const PageOverlays::kUrl = L"{url}";
PageOverlays::PageOverlays()
: top_left(kDate),
top_center(kTitle),
top_right(),
bottom_left(kUrl),
bottom_center(),
bottom_right(kPageOnTotal) {
}
bool PageOverlays::Equals(const PageOverlays& rhs) const {
return top_left == rhs.top_left &&
top_center == rhs.top_center &&
top_right == rhs.top_right &&
bottom_left == rhs.bottom_left &&
bottom_center == rhs.bottom_center &&
bottom_right == rhs.bottom_right;
}
const std::wstring& PageOverlays::GetOverlay(HorizontalPosition x,
VerticalPosition y) const {
switch (x) {
case LEFT:
switch (y) {
case TOP:
return top_left;
case BOTTOM:
return bottom_left;
}
break;
case CENTER:
switch (y) {
case TOP:
return top_center;
case BOTTOM:
return bottom_center;
}
break;
case RIGHT:
switch (y) {
case TOP:
return top_right;
case BOTTOM:
return bottom_right;
}
break;
}
NOTREACHED();
return EmptyWString();
}
void PageOverlays::SetOverlay(HorizontalPosition x, VerticalPosition y,
std::wstring& input) {
switch (x) {
case LEFT:
switch (y) {
case TOP:
top_left = input;
break;
case BOTTOM:
bottom_left = input;
break;
default:
NOTREACHED();
break;
}
break;
case CENTER:
switch (y) {
case TOP:
top_center = input;
break;
case BOTTOM:
bottom_center = input;
break;
default:
NOTREACHED();
break;
}
break;
case RIGHT:
switch (y) {
case TOP:
top_right = input;
break;
case BOTTOM:
bottom_right = input;
break;
default:
NOTREACHED();
break;
}
break;
default:
NOTREACHED();
break;
}
}
//static
std::wstring PageOverlays::ReplaceVariables(const std::wstring& input,
const PrintedDocument& document,
const PrintedPage& page) {
std::wstring output(input);
for (size_t offset = output.find(L'{', 0);
offset != std::wstring::npos;
offset = output.find(L'{', offset)) {
if (0 == output.compare(offset,
wcslen(kTitle),
kTitle)) {
offset = ReplaceKey(&output,
offset,
wcslen(kTitle),
document.name());
} else if (0 == output.compare(offset,
wcslen(kTime),
kTime)) {
offset = ReplaceKey(&output,
offset,
wcslen(kTime),
document.time());
} else if (0 == output.compare(offset,
wcslen(kDate),
kDate)) {
offset = ReplaceKey(&output,
offset,
wcslen(kDate),
document.date());
} else if (0 == output.compare(offset,
wcslen(kPage),
kPage)) {
offset = ReplaceKey(&output,
offset,
wcslen(kPage),
IntToWString(page.page_number()));
} else if (0 == output.compare(offset,
wcslen(kPageCount),
kPageCount)) {
offset = ReplaceKey(&output,
offset,
wcslen(kPageCount),
IntToWString(document.page_count()));
} else if (0 == output.compare(offset,
wcslen(kPageOnTotal),
kPageOnTotal)) {
std::wstring replacement;
replacement = IntToWString(page.page_number());
replacement += L"/";
replacement += IntToWString(document.page_count());
offset = ReplaceKey(&output,
offset,
wcslen(kPageOnTotal),
replacement);
} else if (0 == output.compare(offset,
wcslen(kUrl),
kUrl)) {
// TODO(maruel): http://b/1126373 gfx::ElideUrl(document.url(), ...)
offset = ReplaceKey(&output,
offset,
wcslen(kUrl),
UTF8ToWide(document.url().spec()));
} else {
// There is just a { in the string.
++offset;
}
}
return output;
}
} // namespace printing
<commit_msg>Quick fix for linux shared build.<commit_after>// Copyright (c) 2006-2009 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 "printing/page_overlays.h"
#include "app/gfx/text_elider.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "printing/printed_document.h"
#include "printing/printed_page.h"
namespace {
// Replaces a subpart of a string by other value, and returns the position right
// after the new value.
size_t ReplaceKey(std::wstring* string,
size_t offset,
size_t old_string_len,
const std::wstring& new_string) {
string->replace(offset, old_string_len, new_string);
return offset + new_string.size();
}
} // namespace
namespace printing {
const wchar_t* const PageOverlays::kTitle = L"{title}";
const wchar_t* const PageOverlays::kTime = L"{time}";
const wchar_t* const PageOverlays::kDate = L"{date}";
const wchar_t* const PageOverlays::kPage = L"{page}";
const wchar_t* const PageOverlays::kPageCount = L"{pagecount}";
const wchar_t* const PageOverlays::kPageOnTotal = L"{pageontotal}";
const wchar_t* const PageOverlays::kUrl = L"{url}";
PageOverlays::PageOverlays()
: top_left(kDate),
top_center(kTitle),
top_right(),
bottom_left(kUrl),
bottom_center(),
bottom_right(kPageOnTotal) {
}
bool PageOverlays::Equals(const PageOverlays& rhs) const {
return top_left == rhs.top_left &&
top_center == rhs.top_center &&
top_right == rhs.top_right &&
bottom_left == rhs.bottom_left &&
bottom_center == rhs.bottom_center &&
bottom_right == rhs.bottom_right;
}
const std::wstring& PageOverlays::GetOverlay(HorizontalPosition x,
VerticalPosition y) const {
switch (x) {
case LEFT:
switch (y) {
case TOP:
return top_left;
case BOTTOM:
return bottom_left;
}
break;
case CENTER:
switch (y) {
case TOP:
return top_center;
case BOTTOM:
return bottom_center;
}
break;
case RIGHT:
switch (y) {
case TOP:
return top_right;
case BOTTOM:
return bottom_right;
}
break;
}
NOTREACHED();
return EmptyWString();
}
void PageOverlays::SetOverlay(HorizontalPosition x, VerticalPosition y,
std::wstring& input) {
switch (x) {
case LEFT:
switch (y) {
case TOP:
top_left = input;
break;
case BOTTOM:
bottom_left = input;
break;
default:
NOTREACHED();
break;
}
break;
case CENTER:
switch (y) {
case TOP:
top_center = input;
break;
case BOTTOM:
bottom_center = input;
break;
default:
NOTREACHED();
break;
}
break;
case RIGHT:
switch (y) {
case TOP:
top_right = input;
break;
case BOTTOM:
bottom_right = input;
break;
default:
NOTREACHED();
break;
}
break;
default:
NOTREACHED();
break;
}
}
//static
std::wstring PageOverlays::ReplaceVariables(const std::wstring& input,
const PrintedDocument& document,
const PrintedPage& page) {
std::wstring output(input);
// Prevent references to document.page_count() on Linux until
// printed_document.cc is included in printing.gyp.
#if !defined(OS_LINUX)
for (size_t offset = output.find(L'{', 0);
offset != std::wstring::npos;
offset = output.find(L'{', offset)) {
if (0 == output.compare(offset,
wcslen(kTitle),
kTitle)) {
offset = ReplaceKey(&output,
offset,
wcslen(kTitle),
document.name());
} else if (0 == output.compare(offset,
wcslen(kTime),
kTime)) {
offset = ReplaceKey(&output,
offset,
wcslen(kTime),
document.time());
} else if (0 == output.compare(offset,
wcslen(kDate),
kDate)) {
offset = ReplaceKey(&output,
offset,
wcslen(kDate),
document.date());
} else if (0 == output.compare(offset,
wcslen(kPage),
kPage)) {
offset = ReplaceKey(&output,
offset,
wcslen(kPage),
IntToWString(page.page_number()));
} else if (0 == output.compare(offset,
wcslen(kPageCount),
kPageCount)) {
offset = ReplaceKey(&output,
offset,
wcslen(kPageCount),
IntToWString(document.page_count()));
} else if (0 == output.compare(offset,
wcslen(kPageOnTotal),
kPageOnTotal)) {
std::wstring replacement;
replacement = IntToWString(page.page_number());
replacement += L"/";
replacement += IntToWString(document.page_count());
offset = ReplaceKey(&output,
offset,
wcslen(kPageOnTotal),
replacement);
} else if (0 == output.compare(offset,
wcslen(kUrl),
kUrl)) {
// TODO(maruel): http://b/1126373 gfx::ElideUrl(document.url(), ...)
offset = ReplaceKey(&output,
offset,
wcslen(kUrl),
UTF8ToWide(document.url().spec()));
} else {
// There is just a { in the string.
++offset;
}
}
#endif // !defined(OS_LINUX)
return output;
}
} // namespace printing
<|endoftext|>
|
<commit_before>#include "player.hpp"
#include "lvl.hpp"
#include <vector>
#include <string>
#include <cstdio>
void fatal(const char*, ...);
extern "C" unsigned long hashbytes(unsigned char[], unsigned int);
struct Plat2d {
static const unsigned int Ops[];
static const unsigned int Nops;
enum { UnitCost = true };
typedef double Cost;
static const double InfCost = -1;
typedef int Oper;
static const int Nop = -1;
Plat2d(FILE*);
struct State {
State(void) { }
State(unsigned int x, unsigned int y, unsigned int z,
unsigned int w, unsigned int h) : player(x, y, w, h) { }
Player player;
};
struct PackedState {
unsigned long hash(void) {
static const unsigned int sz = sizeof(x) +
sizeof(y) + sizeof(dy) + sizeof(jframes);
unsigned char bytes[sz];
unsigned int i = 0;
char *p = (char*) &x;
for (unsigned int j = 0; j < sizeof(x); j++)
bytes[i++] = p[j];
p = (char*) &y;
for (unsigned int j = 0; j < sizeof(y); j++)
bytes[i++] = p[j];
p = (char*) &dy;
for (unsigned int j = 0; j < sizeof(dy); j++)
bytes[i++] = p[j];
bytes[i++] = jframes;
assert (i <= sz);
return hashbytes(bytes, i);
}
bool eq(PackedState &o) const {
return jframes == o.jframes &&
doubleeq(x, o.x) &&
doubleeq(y, o.y) &&
doubleeq(dy, o.dy);
}
double x, y, dy;
// The body's fall flag is packed as the high-order bit
// of jframes.
unsigned char jframes;
};
struct Undo {
Undo(State&, Oper) { }
};
State initialstate(void);
Cost h(State &s) {
return heuclidean(s);
}
Cost d(State &s) {
return 0;
}
bool isgoal(State &s) {
Lvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);
return bi.x == gx && bi.y == gy;
}
unsigned int nops(State &s) {
// If jumping will have no effect then allow left, right and jump.
// This is a bit of a hack, but the 'jump' action that is allowed
// here will end up being a 'do nothing' and just fall action.
// Effectively, we prune off the jump/left and jump/right actions
// since they are the same as just doing left and right in this case.
if (!s.player.canjump())
return 3;
return Nops;
}
Oper nthop(State &s, unsigned int n) {
return Ops[n];
}
Oper revop(State &s, Oper op) {
return Nop;
}
void undo(State &s, Undo &u) { }
State &apply(State &buf, State &s, Cost &c, Oper op) {
assert (op != Nop);
buf = s;
buf.player.act(lvl, (unsigned int) op);
c = Point::distance(s.player.body.bbox.min,
buf.player.body.bbox.min);
return buf;
}
void pack(PackedState &dst, State &src) {
dst.x = src.player.body.bbox.min.x;
dst.y = src.player.body.bbox.min.y;
dst.dy = src.player.body.dy;
dst.jframes = src.player.jframes;
if (src.player.body.fall)
dst.jframes |= 1 << 7;
}
State &unpack(State &buf, PackedState &pkd) {
buf.player.jframes = pkd.jframes & 0x7F;
buf.player.body.fall = pkd.jframes & (1 << 7);
buf.player.body.dy = pkd.dy;
buf.player.body.bbox.min.x = pkd.x;
buf.player.body.bbox.min.y = pkd.y;
buf.player.body.bbox.max.x = pkd.x + Player::Width;
buf.player.body.bbox.max.y = pkd.y + Player::Height;
return buf;
}
static void dumpstate(FILE *out, State &s) {
fprintf(out, "%g, %g\n", s.player.loc().x, s.player.loc().y);
}
unsigned int gx, gy; // goal tile location
Lvl lvl;
private:
// heuclidean computes the Euclidean distance of the center
// point of the player to the goal. That is, if the player is level
// with the goal tile in the y direction or is level with it in the
// x direction and above it then the Euclidean distance to the
// nearest side is returned. Otherwise, the minimum of the
// Euclidean distances from the player's center point to the four
// corners of the goal block is returned.
Cost heuclidean(State &s) {
static const double W = Tile::Width;
static const double H = Tile::Height;
const Lvl::Blkinfo &bi = lvl.majorblk(s.player.body.bbox);
if (bi.x == gx && bi.y == gy)
return 0;
const Point &loc = s.player.body.bbox.center();
if (bi.y == gy) {
if (bi.x < gy)
return Point::distance(loc, Point(gx * W, loc.y));
return Point::distance(loc, Point((gx + 1) * W, loc.y));
}
if (bi.x == gx && bi.y < gy)
return Point::distance(loc, Point(loc.x, (gy - 1) * H));
Point topleft(gx * W, (gy-1) * H);
double min = Point::distance(loc, topleft);
Point botleft(gx * W, gy * H);
double d = Point::distance(loc, botleft);
if (d < min)
min = d;
Point topright((gx+1) * W, (gy-1) * H);
d = Point::distance(loc, topright);
if (d < min)
min = d;
Point botright((gx+1) * W, gy * H);
d = Point::distance(loc, botright);
if (d < min)
min = d;
return min;
}
};
// controlstr converts a vector of controls to an ASCII string.
std::string controlstr(const std::vector<unsigned int>&);
// controlvec converts a string of controls back into a vector.
std::vector<unsigned int> controlvec(const std::string&);
<commit_msg>plat2d: faster and more accurate heuristic.<commit_after>#include "player.hpp"
#include "lvl.hpp"
#include <vector>
#include <string>
#include <cstdio>
void fatal(const char*, ...);
extern "C" unsigned long hashbytes(unsigned char[], unsigned int);
struct Plat2d {
static const unsigned int Ops[];
static const unsigned int Nops;
enum { UnitCost = true };
typedef double Cost;
static const double InfCost = -1;
typedef int Oper;
static const int Nop = -1;
Plat2d(FILE*);
struct State {
State(void) { }
State(unsigned int x, unsigned int y, unsigned int z,
unsigned int w, unsigned int h) : player(x, y, w, h) { }
Player player;
};
struct PackedState {
unsigned long hash(void) {
static const unsigned int sz = sizeof(x) +
sizeof(y) + sizeof(dy) + sizeof(jframes);
unsigned char bytes[sz];
unsigned int i = 0;
char *p = (char*) &x;
for (unsigned int j = 0; j < sizeof(x); j++)
bytes[i++] = p[j];
p = (char*) &y;
for (unsigned int j = 0; j < sizeof(y); j++)
bytes[i++] = p[j];
p = (char*) &dy;
for (unsigned int j = 0; j < sizeof(dy); j++)
bytes[i++] = p[j];
bytes[i++] = jframes;
assert (i <= sz);
return hashbytes(bytes, i);
}
bool eq(PackedState &o) const {
return jframes == o.jframes &&
doubleeq(x, o.x) &&
doubleeq(y, o.y) &&
doubleeq(dy, o.dy);
}
double x, y, dy;
// The body's fall flag is packed as the high-order bit
// of jframes.
unsigned char jframes;
};
struct Undo {
Undo(State&, Oper) { }
};
State initialstate(void);
Cost h(State &s) {
return heuclidean(s);
}
Cost d(State &s) {
return 0;
}
bool isgoal(State &s) {
Lvl::Blkinfo bi = lvl.majorblk(s.player.body.bbox);
return bi.x == gx && bi.y == gy;
}
unsigned int nops(State &s) {
// If jumping will have no effect then allow left, right and jump.
// This is a bit of a hack, but the 'jump' action that is allowed
// here will end up being a 'do nothing' and just fall action.
// Effectively, we prune off the jump/left and jump/right actions
// since they are the same as just doing left and right in this case.
if (!s.player.canjump())
return 3;
return Nops;
}
Oper nthop(State &s, unsigned int n) {
return Ops[n];
}
Oper revop(State &s, Oper op) {
return Nop;
}
void undo(State &s, Undo &u) { }
State &apply(State &buf, State &s, Cost &c, Oper op) {
assert (op != Nop);
buf = s;
buf.player.act(lvl, (unsigned int) op);
c = Point::distance(s.player.body.bbox.min,
buf.player.body.bbox.min);
return buf;
}
void pack(PackedState &dst, State &src) {
dst.x = src.player.body.bbox.min.x;
dst.y = src.player.body.bbox.min.y;
dst.dy = src.player.body.dy;
dst.jframes = src.player.jframes;
if (src.player.body.fall)
dst.jframes |= 1 << 7;
}
State &unpack(State &buf, PackedState &pkd) {
buf.player.jframes = pkd.jframes & 0x7F;
buf.player.body.fall = pkd.jframes & (1 << 7);
buf.player.body.dy = pkd.dy;
buf.player.body.bbox.min.x = pkd.x;
buf.player.body.bbox.min.y = pkd.y;
buf.player.body.bbox.max.x = pkd.x + Player::Width;
buf.player.body.bbox.max.y = pkd.y + Player::Height;
return buf;
}
static void dumpstate(FILE *out, State &s) {
fprintf(out, "%g, %g\n", s.player.loc().x, s.player.loc().y);
}
unsigned int gx, gy; // goal tile location
Lvl lvl;
private:
// heuclidean computes the Euclidean distance of the center
// point of the player to the goal. That is, if the player is level
// with the goal tile in the y direction or is level with it in the
// x direction and above it then the Euclidean distance to the
// nearest side is returned. Otherwise, the minimum of the
// Euclidean distances from the player's center point to the four
// corners of the goal block is returned.
Cost heuclidean(State &s) {
static const double W = Tile::Width;
static const double H = Tile::Height;
const Lvl::Blkinfo &bi = lvl.majorblk(s.player.body.bbox);
if (bi.x == gx && bi.y == gy)
return 0;
const Point &loc = s.player.body.bbox.center();
Point goal;
if (bi.y == gy)
goal.y = loc.y;
else if (bi.y < gy)
goal.y = (gy - 1) * H;
else
goal.y = gy * H;
if (bi.x == gx)
goal.x = loc.x;
else if (bi.x < gx)
goal.x = gx * W;
else
goal.x = (gx + 1) * W;
return Point::distance(loc, goal);
}
};
// controlstr converts a vector of controls to an ASCII string.
std::string controlstr(const std::vector<unsigned int>&);
// controlvec converts a string of controls back into a vector.
std::vector<unsigned int> controlvec(const std::string&);
<|endoftext|>
|
<commit_before>#include "..\header\Player.h"
Player::Player(game_state* GameState){
LogManager& l = LogManager::getInstance();
ResourceManager& r = ResourceManager::getInstance();
WorldManager& w = WorldManager::getInstance();
if (!l.isStarted() || !r.isStarted() || !w.isStarted()){
l.writeLog("[Player] Manager was not started. Order by: %s %s %s", BoolToString(l.isStarted()), BoolToString(r.isStarted()), BoolToString(w.isStarted()));
w.markForDelete(this);
return;
}
//No need for a sprite. A simple character will do.
setType(TYPE_PLAYER);
setTransparency();
setSolidness(Solidness::HARD);
Position pos(GameState->PlayerState.initialX, GameState->PlayerState.initialY);
setPosition(pos);
registerInterest(DF_KEYBOARD_EVENT);
registerInterest(DF_STEP_EVENT);
this->GameState = GameState;
setVisible(true);
l.writeLog("[Player] Successfully loaded Player entity.");
}
int Player::eventHandler(Event* e){
LogManager& l = LogManager::getInstance();
if (e->getType() == DF_KEYBOARD_EVENT){
if (this->GameState->Board.isRotating){
return 1;
}
EventKeyboard* keyboard = dynamic_cast<EventKeyboard*>(e);
int key = keyboard->getKey();
int x = this->getPosition().getX();
int y = this->getPosition().getY();
int layoutY = (y - this->GameState->PlayerState.minY - 1);
int layoutX = (x - this->GameState->PlayerState.minX - 1);
int* layout = this->GameState->Stage1.layout;
int width = this->GameState->Stage1.width;
switch (key){
case 'a':{
switch (this->GameState->Board.arrayOrder){
case 0:{
if (layoutX - 1 >= 0){
if (layout[layoutY * width + (layoutX - 1)] == 0){
x--;
this->GameState->PlayerState.x = x;
}
}
break;
}
case 1:{
if (layoutY + 1 < this->GameState->Stage1.height){
if (layout[(layoutY + 1)*width + layoutX] == 0){
y++;
this->GameState->PlayerState.y = y;
}
}
break;
}
case 2:{
if (layoutX + 1 < this->GameState->Stage1.width){
if (layout[layoutY * width + (layoutX + 1)] == 0){
x++;
this->GameState->PlayerState.x = x;
}
}
break;
}
case 3:{
if (layoutY - 1 >= 0){
if (layout[(layoutY - 1)*width + layoutX] == 0){
y--;
this->GameState->PlayerState.y = y;
}
}
break;
}
}
this->setPosition(Position(x, y));
break;
}
case 'd':{
switch (this->GameState->Board.arrayOrder){
case 0:{
if (layoutX + 1 < this->GameState->Stage1.width){
if (layout[layoutY * width + (layoutX + 1)] == 0){
x++;
this->GameState->PlayerState.x = x;
}
}
break;
}
case 1:{
if (layoutY - 1 >= 0){
if (layout[(layoutY - 1)*width + layoutX] == 0){
y--;
this->GameState->PlayerState.y = y;
}
}
break;
}
case 2:{
if (layoutX - 1 >= 0){
if (layout[layoutY*width + (layoutX - 1)] == 0){
x--;
this->GameState->PlayerState.x = x;
}
}
break;
}
case 3:{
if (layoutY + 1 < this->GameState->Stage1.height){
if (layout[(layoutY + 1)* width + layoutX] == 0){
y++;
this->GameState->PlayerState.y = y;
}
}
break;
}
}
this->setPosition(Position(x, y));
break;
}
case 'q':{
l.writeLog("This is Q. Rotates the arena counterclockwise. ");
this->GameState->Board.rotateCCW = true;
this->GameState->Board.rotateCW = false;
this->GameState->Stage1.layout[this->GameState->PlayerState.y * this->GameState->Stage1.width + this->GameState->PlayerState.x] = 999;
break;
}
case 'e': {
l.writeLog("This is E. Rotates the arena clockwise. ");
this->GameState->Board.rotateCW = true;
this->GameState->Board.rotateCCW = false;
this->GameState->Stage1.layout[this->GameState->PlayerState.y * this->GameState->Stage1.width + this->GameState->PlayerState.x] = 999;
break;
}
default:{
return 0;
}
}
return 1;
}
else if (e->getType() == DF_STEP_EVENT){
if (this->GameState->Board.isRotating){
return 1;
}
//Current location
int x = this->getPosition().getX();
int y = this->getPosition().getY();
int layoutY = (y - this->GameState->PlayerState.minY - 1);
int layoutX = (x - this->GameState->PlayerState.minX - 1);
int* layout = this->GameState->Stage1.layout;
if (this->GameState && this->GameState->Stage1.layout){
//Gravity affected movement.
switch (this->GameState->Board.arrayOrder){
case 0:{
if (layoutY + 1 < this->GameState->Stage1.height){
if (layout[(layoutY + 1)*this->GameState->Stage1.width + layoutX] == 0){
y++;
}
}
break;
}
case 1:{
if (layoutX + 1 < this->GameState->Stage1.width){
if (layout[layoutY*this->GameState->Stage1.width + (layoutX + 1)] == 0){
x++;
}
}
break;
}
case 2:{
if (layoutY - 1 >= 0){
if (layout[(layoutY - 1)*this->GameState->Stage1.width + layoutX] == 0){
y--;
}
}
break;
}
case 3:{
if (layoutX - 1 >= 0){
if (layout[layoutY * this->GameState->Stage1.width + (layoutX - 1)] == 0){
x--;
}
}
break;
}
}
}
//Checks to see if the location is within bounds.
if (x <= this->GameState->PlayerState.minX){
x = this->GameState->PlayerState.minX + 1;
}
if (y <= this->GameState->PlayerState.minY){
y = this->GameState->PlayerState.minY + 1;
}
if (x > this->GameState->PlayerState.maxX){
x = this->GameState->PlayerState.maxX;
}
if (y > this->GameState->PlayerState.maxY){
y = this->GameState->PlayerState.maxY;
}
//Set new position.
this->GameState->PlayerState.x = x;
this->GameState->PlayerState.y = y;
this->setPosition(Position(x, y));
return 1;
}
return 0;
}
void Player::draw(){
if (this->GameState->Board.isRotating){
return;
}
LogManager& l = LogManager::getInstance();
GraphicsManager& g = GraphicsManager::getInstance();
int width = this->GameState->Stage1.width;
int height = this->GameState->Stage1.height;
Position pos = this->getPosition();
switch (this->GameState->Board.arrayOrder){
case 0:{
g.drawCh(pos, '@', 0);
break;
}
case 1:{
int x = this->GameState->PlayerState.x;
int newY = this->GameState->PlayerState.minY + (x - this->GameState->PlayerState.minX);
int y = this->GameState->PlayerState.y;
int newX = this->GameState->PlayerState.minX + (this->GameState->PlayerState.maxY - y + 1);
Position newPos(newX, newY);
g.drawCh(newPos, '@', 0);
break;
}
case 2:{
int x = this->GameState->PlayerState.x;
int newX = this->GameState->PlayerState.maxX - (x - this->GameState->PlayerState.minX - 1);
int y = this->GameState->PlayerState.y;
int newY = this->GameState->PlayerState.minY + (this->GameState->PlayerState.maxY - y + 1);
Position newPos(newX, newY);
g.drawCh(newPos, '@', 0);
break;
}
case 3:{
int x = this->GameState->PlayerState.x;
int newY = this->GameState->PlayerState.maxY - (x - this->GameState->PlayerState.minX - 1);
int y = this->GameState->PlayerState.y;
int newX = this->GameState->PlayerState.maxX - (this->GameState->PlayerState.maxY - y);
Position newPos(newX, newY);
g.drawCh(newPos, '@', 0);
break;
}
default:{
l.writeLog("[Player] Wrong array order: %d", (int)(this->GameState->Board.arrayOrder));
break;
}
}
return;
}
void Player::initializeState(game_state* GameState){
this->GameState = GameState;
this->setPosition(Position(GameState->PlayerState.x, GameState->PlayerState.y));
return;
}
void Player::setGameBounds(int x, int y, int w, int h){
if (this->GameState){
this->GameState->PlayerState.minX = x;
this->GameState->PlayerState.minY = y;
this->GameState->PlayerState.maxX = w;
this->GameState->PlayerState.maxY = h;
LogManager& l = LogManager::getInstance();
l.writeLog("[Player] Setting game boundaries for left, top, width, and height: %d, %d, %d, %d", x, y, w, h);
}
}<commit_msg>Removed ResourceManager variable. It isn't used.<commit_after>#include "..\header\Player.h"
Player::Player(game_state* GameState){
LogManager& l = LogManager::getInstance();
WorldManager& w = WorldManager::getInstance();
if (!l.isStarted() || !w.isStarted()){
l.writeLog("[Player] Manager was not started. Order by: %s %s %s", BoolToString(l.isStarted()), BoolToString(w.isStarted()));
w.markForDelete(this);
return;
}
//No need for a sprite. A simple character will do.
setType(TYPE_PLAYER);
setTransparency();
setSolidness(Solidness::HARD);
Position pos(GameState->PlayerState.initialX, GameState->PlayerState.initialY);
setPosition(pos);
registerInterest(DF_KEYBOARD_EVENT);
registerInterest(DF_STEP_EVENT);
this->GameState = GameState;
setVisible(true);
l.writeLog("[Player] Successfully loaded Player entity.");
}
int Player::eventHandler(Event* e){
LogManager& l = LogManager::getInstance();
if (e->getType() == DF_KEYBOARD_EVENT){
if (this->GameState->Board.isRotating){
return 1;
}
EventKeyboard* keyboard = dynamic_cast<EventKeyboard*>(e);
int key = keyboard->getKey();
int x = this->getPosition().getX();
int y = this->getPosition().getY();
int layoutY = (y - this->GameState->PlayerState.minY - 1);
int layoutX = (x - this->GameState->PlayerState.minX - 1);
int* layout = this->GameState->Stage1.layout;
int width = this->GameState->Stage1.width;
switch (key){
case 'a':{
switch (this->GameState->Board.arrayOrder){
case 0:{
if (layoutX - 1 >= 0){
if (layout[layoutY * width + (layoutX - 1)] == 0){
x--;
this->GameState->PlayerState.x = x;
}
}
break;
}
case 1:{
if (layoutY + 1 < this->GameState->Stage1.height){
if (layout[(layoutY + 1)*width + layoutX] == 0){
y++;
this->GameState->PlayerState.y = y;
}
}
break;
}
case 2:{
if (layoutX + 1 < this->GameState->Stage1.width){
if (layout[layoutY * width + (layoutX + 1)] == 0){
x++;
this->GameState->PlayerState.x = x;
}
}
break;
}
case 3:{
if (layoutY - 1 >= 0){
if (layout[(layoutY - 1)*width + layoutX] == 0){
y--;
this->GameState->PlayerState.y = y;
}
}
break;
}
}
this->setPosition(Position(x, y));
break;
}
case 'd':{
switch (this->GameState->Board.arrayOrder){
case 0:{
if (layoutX + 1 < this->GameState->Stage1.width){
if (layout[layoutY * width + (layoutX + 1)] == 0){
x++;
this->GameState->PlayerState.x = x;
}
}
break;
}
case 1:{
if (layoutY - 1 >= 0){
if (layout[(layoutY - 1)*width + layoutX] == 0){
y--;
this->GameState->PlayerState.y = y;
}
}
break;
}
case 2:{
if (layoutX - 1 >= 0){
if (layout[layoutY*width + (layoutX - 1)] == 0){
x--;
this->GameState->PlayerState.x = x;
}
}
break;
}
case 3:{
if (layoutY + 1 < this->GameState->Stage1.height){
if (layout[(layoutY + 1)* width + layoutX] == 0){
y++;
this->GameState->PlayerState.y = y;
}
}
break;
}
}
this->setPosition(Position(x, y));
break;
}
case 'q':{
l.writeLog("This is Q. Rotates the arena counterclockwise. ");
this->GameState->Board.rotateCCW = true;
this->GameState->Board.rotateCW = false;
this->GameState->Stage1.layout[this->GameState->PlayerState.y * this->GameState->Stage1.width + this->GameState->PlayerState.x] = 999;
break;
}
case 'e': {
l.writeLog("This is E. Rotates the arena clockwise. ");
this->GameState->Board.rotateCW = true;
this->GameState->Board.rotateCCW = false;
this->GameState->Stage1.layout[this->GameState->PlayerState.y * this->GameState->Stage1.width + this->GameState->PlayerState.x] = 999;
break;
}
default:{
return 0;
}
}
return 1;
}
else if (e->getType() == DF_STEP_EVENT){
if (this->GameState->Board.isRotating){
return 1;
}
//Current location
int x = this->getPosition().getX();
int y = this->getPosition().getY();
int layoutY = (y - this->GameState->PlayerState.minY - 1);
int layoutX = (x - this->GameState->PlayerState.minX - 1);
int* layout = this->GameState->Stage1.layout;
if (this->GameState && this->GameState->Stage1.layout){
//Gravity affected movement.
switch (this->GameState->Board.arrayOrder){
case 0:{
if (layoutY + 1 < this->GameState->Stage1.height){
if (layout[(layoutY + 1)*this->GameState->Stage1.width + layoutX] == 0){
y++;
}
}
break;
}
case 1:{
if (layoutX + 1 < this->GameState->Stage1.width){
if (layout[layoutY*this->GameState->Stage1.width + (layoutX + 1)] == 0){
x++;
}
}
break;
}
case 2:{
if (layoutY - 1 >= 0){
if (layout[(layoutY - 1)*this->GameState->Stage1.width + layoutX] == 0){
y--;
}
}
break;
}
case 3:{
if (layoutX - 1 >= 0){
if (layout[layoutY * this->GameState->Stage1.width + (layoutX - 1)] == 0){
x--;
}
}
break;
}
}
}
//Checks to see if the location is within bounds.
if (x <= this->GameState->PlayerState.minX){
x = this->GameState->PlayerState.minX + 1;
}
if (y <= this->GameState->PlayerState.minY){
y = this->GameState->PlayerState.minY + 1;
}
if (x > this->GameState->PlayerState.maxX){
x = this->GameState->PlayerState.maxX;
}
if (y > this->GameState->PlayerState.maxY){
y = this->GameState->PlayerState.maxY;
}
//Set new position.
this->GameState->PlayerState.x = x;
this->GameState->PlayerState.y = y;
this->setPosition(Position(x, y));
return 1;
}
return 0;
}
void Player::draw(){
if (this->GameState->Board.isRotating){
return;
}
LogManager& l = LogManager::getInstance();
GraphicsManager& g = GraphicsManager::getInstance();
int width = this->GameState->Stage1.width;
int height = this->GameState->Stage1.height;
Position pos = this->getPosition();
switch (this->GameState->Board.arrayOrder){
case 0:{
g.drawCh(pos, '@', 0);
break;
}
case 1:{
int x = this->GameState->PlayerState.x;
int newY = this->GameState->PlayerState.minY + (x - this->GameState->PlayerState.minX);
int y = this->GameState->PlayerState.y;
int newX = this->GameState->PlayerState.minX + (this->GameState->PlayerState.maxY - y + 1);
Position newPos(newX, newY);
g.drawCh(newPos, '@', 0);
break;
}
case 2:{
int x = this->GameState->PlayerState.x;
int newX = this->GameState->PlayerState.maxX - (x - this->GameState->PlayerState.minX - 1);
int y = this->GameState->PlayerState.y;
int newY = this->GameState->PlayerState.minY + (this->GameState->PlayerState.maxY - y + 1);
Position newPos(newX, newY);
g.drawCh(newPos, '@', 0);
break;
}
case 3:{
int x = this->GameState->PlayerState.x;
int newY = this->GameState->PlayerState.maxY - (x - this->GameState->PlayerState.minX - 1);
int y = this->GameState->PlayerState.y;
int newX = this->GameState->PlayerState.maxX - (this->GameState->PlayerState.maxY - y);
Position newPos(newX, newY);
g.drawCh(newPos, '@', 0);
break;
}
default:{
l.writeLog("[Player] Wrong array order: %d", (int)(this->GameState->Board.arrayOrder));
break;
}
}
return;
}
void Player::initializeState(game_state* GameState){
this->GameState = GameState;
this->setPosition(Position(GameState->PlayerState.x, GameState->PlayerState.y));
return;
}
void Player::setGameBounds(int x, int y, int w, int h){
if (this->GameState){
this->GameState->PlayerState.minX = x;
this->GameState->PlayerState.minY = y;
this->GameState->PlayerState.maxX = w;
this->GameState->PlayerState.maxY = h;
LogManager& l = LogManager::getInstance();
l.writeLog("[Player] Setting game boundaries for left, top, width, and height: %d, %d, %d, %d", x, y, w, h);
}
}<|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 "base/process.h"
#include <errno.h>
#include <sys/resource.h>
#include "base/logging.h"
namespace base {
bool Process::IsProcessBackgrounded() const {
DCHECK(process_);
return saved_priority_ == kUnsetProcessPriority;
}
bool Process::SetProcessBackgrounded(bool background) {
DCHECK(process_);
if (background) {
// We won't be able to raise the priority if we don't have the right rlimit.
// The limit may be adjusted in /etc/security/limits.conf for PAM systems.
struct rlimit rlim;
if (getrlimit(RLIMIT_NICE, &rlim) != 0) {
// Call to getrlimit failed, don't background.
return false;
}
errno = 0;
int current_priority = GetPriority();
if (errno) {
// Couldn't get priority.
return false;
}
// {set,get}priority values are in the range -20 to 19, where -1 is higher
// priority than 0. But rlimit's are in the range from 0 to 39 where
// 1 is higher than 0.
if ((20 - current_priority) > static_cast<int>(rlim.rlim_cur)) {
// User is not allowed to raise the priority back to where it is now.
return false;
}
int result = setpriority(PRIO_PROCESS, process_, current_priority + 1);
if (result == -1) {
// Failed to lower priority.
return false;
}
saved_priority_ = current_priority;
return true;
} else {
if (saved_priority_ == kUnsetProcessPriority) {
// Can't restore if we were never backgrounded.
return false;
}
int result = setpriority(PRIO_PROCESS, process_, saved_priority_);
// If we can't restore something has gone terribly wrong.
DPCHECK(result == 0);
saved_priority_ = kUnsetProcessPriority;
return true;
}
}
} // namespace base
<commit_msg>Adjust the priority of background tabs more aggresively. This will continue to only affect users who have their nice rlimit set so that process priorities can be raised back to 0. That may be the default on later versions of Ubuntu.<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 "base/process.h"
#include <errno.h>
#include <sys/resource.h>
#include "base/logging.h"
namespace base {
const int kPriorityAdjustment = 5;
bool Process::IsProcessBackgrounded() const {
DCHECK(process_);
return saved_priority_ == kUnsetProcessPriority;
}
bool Process::SetProcessBackgrounded(bool background) {
DCHECK(process_);
if (background) {
// We won't be able to raise the priority if we don't have the right rlimit.
// The limit may be adjusted in /etc/security/limits.conf for PAM systems.
struct rlimit rlim;
if (getrlimit(RLIMIT_NICE, &rlim) != 0) {
// Call to getrlimit failed, don't background.
return false;
}
errno = 0;
int current_priority = GetPriority();
if (errno) {
// Couldn't get priority.
return false;
}
// {set,get}priority values are in the range -20 to 19, where -1 is higher
// priority than 0. But rlimit's are in the range from 0 to 39 where
// 1 is higher than 0.
if ((20 - current_priority) > static_cast<int>(rlim.rlim_cur)) {
// User is not allowed to raise the priority back to where it is now.
return false;
}
int result =
setpriority(
PRIO_PROCESS, process_, current_priority + kPriorityAdjustment);
if (result == -1) {
LOG(ERROR) << "Failed to lower priority, errno: " << errno;
return false;
}
saved_priority_ = current_priority;
return true;
} else {
if (saved_priority_ == kUnsetProcessPriority) {
// Can't restore if we were never backgrounded.
return false;
}
int result = setpriority(PRIO_PROCESS, process_, saved_priority_);
// If we can't restore something has gone terribly wrong.
DPCHECK(result == 0);
saved_priority_ = kUnsetProcessPriority;
return true;
}
}
} // namespace base
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-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 <time.h>
#include "base/platform_thread.h"
#include "base/time.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
// Test conversions to/from time_t and exploding/unexploding.
TEST(Time, TimeT) {
// C library time and exploded time.
time_t now_t_1 = time(NULL);
struct tm tms;
#if defined(OS_WIN)
localtime_s(&tms, &now_t_1);
#elif defined(OS_POSIX)
localtime_r(&now_t_1, &tms);
#endif
// Convert to ours.
Time our_time_1 = Time::FromTimeT(now_t_1);
Time::Exploded exploded;
our_time_1.LocalExplode(&exploded);
// This will test both our exploding and our time_t -> Time conversion.
EXPECT_EQ(tms.tm_year + 1900, exploded.year);
EXPECT_EQ(tms.tm_mon + 1, exploded.month);
EXPECT_EQ(tms.tm_mday, exploded.day_of_month);
EXPECT_EQ(tms.tm_hour, exploded.hour);
EXPECT_EQ(tms.tm_min, exploded.minute);
EXPECT_EQ(tms.tm_sec, exploded.second);
// Convert exploded back to the time struct.
Time our_time_2 = Time::FromLocalExploded(exploded);
EXPECT_TRUE(our_time_1 == our_time_2);
time_t now_t_2 = our_time_2.ToTimeT();
EXPECT_EQ(now_t_1, now_t_2);
EXPECT_EQ(10, Time().FromTimeT(10).ToTimeT());
EXPECT_EQ(10.0, Time().FromTimeT(10).ToDoubleT());
// Conversions of 0 should stay 0.
EXPECT_EQ(0, Time().ToTimeT());
EXPECT_EQ(0, Time::FromTimeT(0).ToInternalValue());
}
TEST(Time, ZeroIsSymmetric) {
Time zero_time(Time::FromTimeT(0));
EXPECT_EQ(0, zero_time.ToTimeT());
EXPECT_EQ(0.0, zero_time.ToDoubleT());
}
TEST(Time, LocalExplode) {
Time a = Time::Now();
Time::Exploded exploded;
a.LocalExplode(&exploded);
Time b = Time::FromLocalExploded(exploded);
// The exploded structure doesn't have microseconds, so the result will be
// rounded to the nearest millisecond.
EXPECT_TRUE((a - b) < TimeDelta::FromMilliseconds(1));
}
TEST(Time, UTCExplode) {
Time a = Time::Now();
Time::Exploded exploded;
a.UTCExplode(&exploded);
Time b = Time::FromUTCExploded(exploded);
EXPECT_TRUE((a - b) < TimeDelta::FromMilliseconds(1));
}
TEST(Time, LocalMidnight) {
Time::Exploded exploded;
Time::Now().LocalMidnight().LocalExplode(&exploded);
EXPECT_EQ(0, exploded.hour);
EXPECT_EQ(0, exploded.minute);
EXPECT_EQ(0, exploded.second);
EXPECT_EQ(0, exploded.millisecond);
}
TEST(TimeTicks, Deltas) {
TimeTicks ticks_start = TimeTicks::Now();
PlatformThread::Sleep(10);
TimeTicks ticks_stop = TimeTicks::Now();
TimeDelta delta = ticks_stop - ticks_start;
EXPECT_GE(delta.InMilliseconds(), 10);
EXPECT_GE(delta.InMicroseconds(), 10000);
EXPECT_EQ(delta.InSeconds(), 0);
}
TEST(TimeDelta, FromAndIn) {
EXPECT_TRUE(TimeDelta::FromDays(2) == TimeDelta::FromHours(48));
EXPECT_TRUE(TimeDelta::FromHours(3) == TimeDelta::FromMinutes(180));
EXPECT_TRUE(TimeDelta::FromMinutes(2) == TimeDelta::FromSeconds(120));
EXPECT_TRUE(TimeDelta::FromSeconds(2) == TimeDelta::FromMilliseconds(2000));
EXPECT_TRUE(TimeDelta::FromMilliseconds(2) ==
TimeDelta::FromMicroseconds(2000));
EXPECT_EQ(13, TimeDelta::FromDays(13).InDays());
EXPECT_EQ(13, TimeDelta::FromHours(13).InHours());
EXPECT_EQ(13, TimeDelta::FromMinutes(13).InMinutes());
EXPECT_EQ(13, TimeDelta::FromSeconds(13).InSeconds());
EXPECT_EQ(13.0, TimeDelta::FromSeconds(13).InSecondsF());
EXPECT_EQ(13, TimeDelta::FromMilliseconds(13).InMilliseconds());
EXPECT_EQ(13.0, TimeDelta::FromMilliseconds(13).InMillisecondsF());
EXPECT_EQ(13, TimeDelta::FromMicroseconds(13).InMicroseconds());
}
<commit_msg>Add at least some code that tests UnreliableHighResNow. I realize it can be broken, but we should test it if we're going to have the code.<commit_after>// Copyright (c) 2006-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 <time.h>
#include "base/platform_thread.h"
#include "base/time.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
// Test conversions to/from time_t and exploding/unexploding.
TEST(Time, TimeT) {
// C library time and exploded time.
time_t now_t_1 = time(NULL);
struct tm tms;
#if defined(OS_WIN)
localtime_s(&tms, &now_t_1);
#elif defined(OS_POSIX)
localtime_r(&now_t_1, &tms);
#endif
// Convert to ours.
Time our_time_1 = Time::FromTimeT(now_t_1);
Time::Exploded exploded;
our_time_1.LocalExplode(&exploded);
// This will test both our exploding and our time_t -> Time conversion.
EXPECT_EQ(tms.tm_year + 1900, exploded.year);
EXPECT_EQ(tms.tm_mon + 1, exploded.month);
EXPECT_EQ(tms.tm_mday, exploded.day_of_month);
EXPECT_EQ(tms.tm_hour, exploded.hour);
EXPECT_EQ(tms.tm_min, exploded.minute);
EXPECT_EQ(tms.tm_sec, exploded.second);
// Convert exploded back to the time struct.
Time our_time_2 = Time::FromLocalExploded(exploded);
EXPECT_TRUE(our_time_1 == our_time_2);
time_t now_t_2 = our_time_2.ToTimeT();
EXPECT_EQ(now_t_1, now_t_2);
EXPECT_EQ(10, Time().FromTimeT(10).ToTimeT());
EXPECT_EQ(10.0, Time().FromTimeT(10).ToDoubleT());
// Conversions of 0 should stay 0.
EXPECT_EQ(0, Time().ToTimeT());
EXPECT_EQ(0, Time::FromTimeT(0).ToInternalValue());
}
TEST(Time, ZeroIsSymmetric) {
Time zero_time(Time::FromTimeT(0));
EXPECT_EQ(0, zero_time.ToTimeT());
EXPECT_EQ(0.0, zero_time.ToDoubleT());
}
TEST(Time, LocalExplode) {
Time a = Time::Now();
Time::Exploded exploded;
a.LocalExplode(&exploded);
Time b = Time::FromLocalExploded(exploded);
// The exploded structure doesn't have microseconds, so the result will be
// rounded to the nearest millisecond.
EXPECT_TRUE((a - b) < TimeDelta::FromMilliseconds(1));
}
TEST(Time, UTCExplode) {
Time a = Time::Now();
Time::Exploded exploded;
a.UTCExplode(&exploded);
Time b = Time::FromUTCExploded(exploded);
EXPECT_TRUE((a - b) < TimeDelta::FromMilliseconds(1));
}
TEST(Time, LocalMidnight) {
Time::Exploded exploded;
Time::Now().LocalMidnight().LocalExplode(&exploded);
EXPECT_EQ(0, exploded.hour);
EXPECT_EQ(0, exploded.minute);
EXPECT_EQ(0, exploded.second);
EXPECT_EQ(0, exploded.millisecond);
}
TEST(TimeTicks, Deltas) {
TimeTicks ticks_start = TimeTicks::Now();
PlatformThread::Sleep(10);
TimeTicks ticks_stop = TimeTicks::Now();
TimeDelta delta = ticks_stop - ticks_start;
EXPECT_GE(delta.InMilliseconds(), 10);
EXPECT_GE(delta.InMicroseconds(), 10000);
EXPECT_EQ(delta.InSeconds(), 0);
}
TEST(TimeTicks, UnreliableHighResNow) {
TimeTicks ticks_start = TimeTicks::UnreliableHighResNow();
PlatformThread::Sleep(10);
TimeTicks ticks_stop = TimeTicks::UnreliableHighResNow();
TimeDelta delta = ticks_stop - ticks_start;
EXPECT_GE(delta.InMilliseconds(), 10);
}
TEST(TimeDelta, FromAndIn) {
EXPECT_TRUE(TimeDelta::FromDays(2) == TimeDelta::FromHours(48));
EXPECT_TRUE(TimeDelta::FromHours(3) == TimeDelta::FromMinutes(180));
EXPECT_TRUE(TimeDelta::FromMinutes(2) == TimeDelta::FromSeconds(120));
EXPECT_TRUE(TimeDelta::FromSeconds(2) == TimeDelta::FromMilliseconds(2000));
EXPECT_TRUE(TimeDelta::FromMilliseconds(2) ==
TimeDelta::FromMicroseconds(2000));
EXPECT_EQ(13, TimeDelta::FromDays(13).InDays());
EXPECT_EQ(13, TimeDelta::FromHours(13).InHours());
EXPECT_EQ(13, TimeDelta::FromMinutes(13).InMinutes());
EXPECT_EQ(13, TimeDelta::FromSeconds(13).InSeconds());
EXPECT_EQ(13.0, TimeDelta::FromSeconds(13).InSecondsF());
EXPECT_EQ(13, TimeDelta::FromMilliseconds(13).InMilliseconds());
EXPECT_EQ(13.0, TimeDelta::FromMilliseconds(13).InMillisecondsF());
EXPECT_EQ(13, TimeDelta::FromMicroseconds(13).InMicroseconds());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-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 <time.h>
#include "base/platform_thread.h"
#include "base/time.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
using base::TimeTicks;
// Test conversions to/from time_t and exploding/unexploding.
TEST(Time, TimeT) {
// C library time and exploded time.
time_t now_t_1 = time(NULL);
struct tm tms;
#if defined(OS_WIN)
localtime_s(&tms, &now_t_1);
#elif defined(OS_POSIX)
localtime_r(&now_t_1, &tms);
#endif
// Convert to ours.
Time our_time_1 = Time::FromTimeT(now_t_1);
Time::Exploded exploded;
our_time_1.LocalExplode(&exploded);
// This will test both our exploding and our time_t -> Time conversion.
EXPECT_EQ(tms.tm_year + 1900, exploded.year);
EXPECT_EQ(tms.tm_mon + 1, exploded.month);
EXPECT_EQ(tms.tm_mday, exploded.day_of_month);
EXPECT_EQ(tms.tm_hour, exploded.hour);
EXPECT_EQ(tms.tm_min, exploded.minute);
EXPECT_EQ(tms.tm_sec, exploded.second);
// Convert exploded back to the time struct.
Time our_time_2 = Time::FromLocalExploded(exploded);
EXPECT_TRUE(our_time_1 == our_time_2);
time_t now_t_2 = our_time_2.ToTimeT();
EXPECT_EQ(now_t_1, now_t_2);
EXPECT_EQ(10, Time().FromTimeT(10).ToTimeT());
EXPECT_EQ(10.0, Time().FromTimeT(10).ToDoubleT());
// Conversions of 0 should stay 0.
EXPECT_EQ(0, Time().ToTimeT());
EXPECT_EQ(0, Time::FromTimeT(0).ToInternalValue());
}
TEST(Time, ZeroIsSymmetric) {
Time zero_time(Time::FromTimeT(0));
EXPECT_EQ(0, zero_time.ToTimeT());
EXPECT_EQ(0.0, zero_time.ToDoubleT());
}
TEST(Time, LocalExplode) {
Time a = Time::Now();
Time::Exploded exploded;
a.LocalExplode(&exploded);
Time b = Time::FromLocalExploded(exploded);
// The exploded structure doesn't have microseconds, and on Mac & Linux, the
// internal OS conversion uses seconds, which will cause truncation. So we
// can only make sure that the delta is within one second.
EXPECT_TRUE((a - b) < TimeDelta::FromSeconds(1));
}
TEST(Time, UTCExplode) {
Time a = Time::Now();
Time::Exploded exploded;
a.UTCExplode(&exploded);
Time b = Time::FromUTCExploded(exploded);
EXPECT_TRUE((a - b) < TimeDelta::FromSeconds(1));
}
TEST(Time, LocalMidnight) {
Time::Exploded exploded;
Time::Now().LocalMidnight().LocalExplode(&exploded);
EXPECT_EQ(0, exploded.hour);
EXPECT_EQ(0, exploded.minute);
EXPECT_EQ(0, exploded.second);
EXPECT_EQ(0, exploded.millisecond);
}
TEST(TimeTicks, Deltas) {
for (int index = 0; index < 50; index++) {
TimeTicks ticks_start = TimeTicks::Now();
PlatformThread::Sleep(10);
TimeTicks ticks_stop = TimeTicks::Now();
TimeDelta delta = ticks_stop - ticks_start;
// Note: Although we asked for a 10ms sleep, if the
// time clock has a finer granularity than the Sleep()
// clock, it is quite possible to wakeup early. Here
// is how that works:
// Time(ms timer) Time(us timer)
// 5 5010
// 6 6010
// 7 7010
// 8 8010
// 9 9000
// Elapsed 4ms 3990us
//
// Unfortunately, our InMilliseconds() function truncates
// rather than rounds. We should consider fixing this
// so that our averages come out better.
EXPECT_GE(delta.InMilliseconds(), 9);
EXPECT_GE(delta.InMicroseconds(), 9000);
EXPECT_EQ(delta.InSeconds(), 0);
}
}
TEST(TimeTicks, FLAKY_HighResNow) {
#if defined(OS_WIN)
Time::ActivateHighResolutionTimer(true);
#endif
TimeTicks ticks_start = TimeTicks::HighResNow();
PlatformThread::Sleep(10);
TimeTicks ticks_stop = TimeTicks::HighResNow();
TimeDelta delta = ticks_stop - ticks_start;
// In high res mode, we should be accurate to within 1.5x our
// best granularity. On windows, that is 1ms, so use 1.5ms.
EXPECT_GE(delta.InMicroseconds(), 8500);
}
TEST(TimeDelta, FromAndIn) {
EXPECT_TRUE(TimeDelta::FromDays(2) == TimeDelta::FromHours(48));
EXPECT_TRUE(TimeDelta::FromHours(3) == TimeDelta::FromMinutes(180));
EXPECT_TRUE(TimeDelta::FromMinutes(2) == TimeDelta::FromSeconds(120));
EXPECT_TRUE(TimeDelta::FromSeconds(2) == TimeDelta::FromMilliseconds(2000));
EXPECT_TRUE(TimeDelta::FromMilliseconds(2) ==
TimeDelta::FromMicroseconds(2000));
EXPECT_EQ(13, TimeDelta::FromDays(13).InDays());
EXPECT_EQ(13, TimeDelta::FromHours(13).InHours());
EXPECT_EQ(13, TimeDelta::FromMinutes(13).InMinutes());
EXPECT_EQ(13, TimeDelta::FromSeconds(13).InSeconds());
EXPECT_EQ(13.0, TimeDelta::FromSeconds(13).InSecondsF());
EXPECT_EQ(13, TimeDelta::FromMilliseconds(13).InMilliseconds());
EXPECT_EQ(13.0, TimeDelta::FromMilliseconds(13).InMillisecondsF());
EXPECT_EQ(13, TimeDelta::FromMicroseconds(13).InMicroseconds());
}
#if defined(OS_POSIX)
TEST(TimeDelta, TimeSpecConversion) {
struct timespec result = TimeDelta::FromSeconds(0).ToTimeSpec();
EXPECT_EQ(result.tv_sec, 0);
EXPECT_EQ(result.tv_nsec, 0);
result = TimeDelta::FromSeconds(1).ToTimeSpec();
EXPECT_EQ(result.tv_sec, 1);
EXPECT_EQ(result.tv_nsec, 0);
result = TimeDelta::FromMicroseconds(1).ToTimeSpec();
EXPECT_EQ(result.tv_sec, 0);
EXPECT_EQ(result.tv_nsec, 1000);
result = TimeDelta::FromMicroseconds(
Time::kMicrosecondsPerSecond + 1).ToTimeSpec();
EXPECT_EQ(result.tv_sec, 1);
EXPECT_EQ(result.tv_nsec, 1000);
}
#endif // OS_POSIX
// Our internal time format is serialized in things like databases, so it's
// important that it's consistent across all our platforms. We use the 1601
// Windows epoch as the internal format across all platforms.
TEST(TimeDelta, WindowsEpoch) {
Time::Exploded exploded;
exploded.year = 1970;
exploded.month = 1;
exploded.day_of_week = 0; // Should be unusued.
exploded.day_of_month = 1;
exploded.hour = 0;
exploded.minute = 0;
exploded.second = 0;
exploded.millisecond = 0;
Time t = Time::FromUTCExploded(exploded);
// Unix 1970 epoch.
EXPECT_EQ(GG_INT64_C(11644473600000000), t.ToInternalValue());
// We can't test 1601 epoch, since the system time functions on Linux
// only compute years starting from 1900.
}
<commit_msg>Fix flakey timer test.<commit_after>// Copyright (c) 2006-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 <time.h>
#include "base/platform_thread.h"
#include "base/time.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
using base::TimeTicks;
// Test conversions to/from time_t and exploding/unexploding.
TEST(Time, TimeT) {
// C library time and exploded time.
time_t now_t_1 = time(NULL);
struct tm tms;
#if defined(OS_WIN)
localtime_s(&tms, &now_t_1);
#elif defined(OS_POSIX)
localtime_r(&now_t_1, &tms);
#endif
// Convert to ours.
Time our_time_1 = Time::FromTimeT(now_t_1);
Time::Exploded exploded;
our_time_1.LocalExplode(&exploded);
// This will test both our exploding and our time_t -> Time conversion.
EXPECT_EQ(tms.tm_year + 1900, exploded.year);
EXPECT_EQ(tms.tm_mon + 1, exploded.month);
EXPECT_EQ(tms.tm_mday, exploded.day_of_month);
EXPECT_EQ(tms.tm_hour, exploded.hour);
EXPECT_EQ(tms.tm_min, exploded.minute);
EXPECT_EQ(tms.tm_sec, exploded.second);
// Convert exploded back to the time struct.
Time our_time_2 = Time::FromLocalExploded(exploded);
EXPECT_TRUE(our_time_1 == our_time_2);
time_t now_t_2 = our_time_2.ToTimeT();
EXPECT_EQ(now_t_1, now_t_2);
EXPECT_EQ(10, Time().FromTimeT(10).ToTimeT());
EXPECT_EQ(10.0, Time().FromTimeT(10).ToDoubleT());
// Conversions of 0 should stay 0.
EXPECT_EQ(0, Time().ToTimeT());
EXPECT_EQ(0, Time::FromTimeT(0).ToInternalValue());
}
TEST(Time, ZeroIsSymmetric) {
Time zero_time(Time::FromTimeT(0));
EXPECT_EQ(0, zero_time.ToTimeT());
EXPECT_EQ(0.0, zero_time.ToDoubleT());
}
TEST(Time, LocalExplode) {
Time a = Time::Now();
Time::Exploded exploded;
a.LocalExplode(&exploded);
Time b = Time::FromLocalExploded(exploded);
// The exploded structure doesn't have microseconds, and on Mac & Linux, the
// internal OS conversion uses seconds, which will cause truncation. So we
// can only make sure that the delta is within one second.
EXPECT_TRUE((a - b) < TimeDelta::FromSeconds(1));
}
TEST(Time, UTCExplode) {
Time a = Time::Now();
Time::Exploded exploded;
a.UTCExplode(&exploded);
Time b = Time::FromUTCExploded(exploded);
EXPECT_TRUE((a - b) < TimeDelta::FromSeconds(1));
}
TEST(Time, LocalMidnight) {
Time::Exploded exploded;
Time::Now().LocalMidnight().LocalExplode(&exploded);
EXPECT_EQ(0, exploded.hour);
EXPECT_EQ(0, exploded.minute);
EXPECT_EQ(0, exploded.second);
EXPECT_EQ(0, exploded.millisecond);
}
TEST(TimeTicks, Deltas) {
for (int index = 0; index < 50; index++) {
TimeTicks ticks_start = TimeTicks::Now();
PlatformThread::Sleep(10);
TimeTicks ticks_stop = TimeTicks::Now();
TimeDelta delta = ticks_stop - ticks_start;
// Note: Although we asked for a 10ms sleep, if the
// time clock has a finer granularity than the Sleep()
// clock, it is quite possible to wakeup early. Here
// is how that works:
// Time(ms timer) Time(us timer)
// 5 5010
// 6 6010
// 7 7010
// 8 8010
// 9 9000
// Elapsed 4ms 3990us
//
// Unfortunately, our InMilliseconds() function truncates
// rather than rounds. We should consider fixing this
// so that our averages come out better.
EXPECT_GE(delta.InMilliseconds(), 9);
EXPECT_GE(delta.InMicroseconds(), 9000);
EXPECT_EQ(delta.InSeconds(), 0);
}
}
TEST(TimeTicks, HighResNow) {
#if defined(OS_WIN)
// HighResNow doesn't work on some systems. Since the product still works
// even if it doesn't work, it makes this entire test questionable.
if (!TimeTicks::IsHighResClockWorking())
return;
#endif
TimeTicks ticks_start = TimeTicks::HighResNow();
TimeDelta delta;
// Loop until we can detect that the clock has changed. Non-HighRes timers
// will increment in chunks, e.g. 15ms. By spinning until we see a clock
// change, we detect the minimum time between measurements.
do {
delta = TimeTicks::HighResNow() - ticks_start;
} while (delta.InMilliseconds() == 0);
// In high resolution mode, we expect to see the clock increment
// in intervals less than 15ms.
EXPECT_LT(delta.InMicroseconds(), 15000);
}
TEST(TimeDelta, FromAndIn) {
EXPECT_TRUE(TimeDelta::FromDays(2) == TimeDelta::FromHours(48));
EXPECT_TRUE(TimeDelta::FromHours(3) == TimeDelta::FromMinutes(180));
EXPECT_TRUE(TimeDelta::FromMinutes(2) == TimeDelta::FromSeconds(120));
EXPECT_TRUE(TimeDelta::FromSeconds(2) == TimeDelta::FromMilliseconds(2000));
EXPECT_TRUE(TimeDelta::FromMilliseconds(2) ==
TimeDelta::FromMicroseconds(2000));
EXPECT_EQ(13, TimeDelta::FromDays(13).InDays());
EXPECT_EQ(13, TimeDelta::FromHours(13).InHours());
EXPECT_EQ(13, TimeDelta::FromMinutes(13).InMinutes());
EXPECT_EQ(13, TimeDelta::FromSeconds(13).InSeconds());
EXPECT_EQ(13.0, TimeDelta::FromSeconds(13).InSecondsF());
EXPECT_EQ(13, TimeDelta::FromMilliseconds(13).InMilliseconds());
EXPECT_EQ(13.0, TimeDelta::FromMilliseconds(13).InMillisecondsF());
EXPECT_EQ(13, TimeDelta::FromMicroseconds(13).InMicroseconds());
}
#if defined(OS_POSIX)
TEST(TimeDelta, TimeSpecConversion) {
struct timespec result = TimeDelta::FromSeconds(0).ToTimeSpec();
EXPECT_EQ(result.tv_sec, 0);
EXPECT_EQ(result.tv_nsec, 0);
result = TimeDelta::FromSeconds(1).ToTimeSpec();
EXPECT_EQ(result.tv_sec, 1);
EXPECT_EQ(result.tv_nsec, 0);
result = TimeDelta::FromMicroseconds(1).ToTimeSpec();
EXPECT_EQ(result.tv_sec, 0);
EXPECT_EQ(result.tv_nsec, 1000);
result = TimeDelta::FromMicroseconds(
Time::kMicrosecondsPerSecond + 1).ToTimeSpec();
EXPECT_EQ(result.tv_sec, 1);
EXPECT_EQ(result.tv_nsec, 1000);
}
#endif // OS_POSIX
// Our internal time format is serialized in things like databases, so it's
// important that it's consistent across all our platforms. We use the 1601
// Windows epoch as the internal format across all platforms.
TEST(TimeDelta, WindowsEpoch) {
Time::Exploded exploded;
exploded.year = 1970;
exploded.month = 1;
exploded.day_of_week = 0; // Should be unusued.
exploded.day_of_month = 1;
exploded.hour = 0;
exploded.minute = 0;
exploded.second = 0;
exploded.millisecond = 0;
Time t = Time::FromUTCExploded(exploded);
// Unix 1970 epoch.
EXPECT_EQ(GG_INT64_C(11644473600000000), t.ToInternalValue());
// We can't test 1601 epoch, since the system time functions on Linux
// only compute years starting from 1900.
}
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* plan_transformer.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/bridge/plan_transformer.cpp
*
*-------------------------------------------------------------------------
*/
#include "nodes/pprint.h"
#include "utils/rel.h"
#include "bridge/bridge.h"
#include "executor/executor.h"
#include "backend/bridge/plan_transformer.h"
#include "backend/bridge/tuple_transformer.h"
#include "backend/expression/abstract_expression.h"
#include "backend/storage/data_table.h"
#include "backend/planner/delete_node.h"
#include "backend/planner/insert_node.h"
#include "backend/planner/seq_scan_node.h"
void printPlanStateTree(const PlanState * planstate);
namespace peloton {
namespace bridge {
/**
* @brief Pretty print the plan state tree.
* @return none.
*/
void PlanTransformer::PrintPlanState(const PlanState *plan_state) {
printPlanStateTree(plan_state);
}
/**
* @brief Convert Postgres PlanState into AbstractPlanNode.
* @return Pointer to the constructed AbstractPlanNode.
*/
planner::AbstractPlanNode *PlanTransformer::TransformPlan(const PlanState *plan_state) {
Plan *plan = plan_state->plan;
planner::AbstractPlanNode *plan_node;
switch (nodeTag(plan)) {
case T_ModifyTable:
plan_node = PlanTransformer::TransformModifyTable(reinterpret_cast<const ModifyTableState *>(plan_state));
break;
case T_SeqScan:
plan_node = PlanTransformer::TransformSeqScan(reinterpret_cast<const SeqScanState*>(plan_state));
break;
default:
plan_node = nullptr;
break;
}
return plan_node;
}
/**
* @brief Convert ModifyTableState into AbstractPlanNode.
* @return Pointer to the constructed AbstractPlanNode.
*
* Basically, it multiplexes into helper methods based on operation type.
*/
planner::AbstractPlanNode *PlanTransformer::TransformModifyTable(
const ModifyTableState *mt_plan_state) {
/* TODO: Add logging */
ModifyTable *plan = (ModifyTable *) mt_plan_state->ps.plan;
switch (plan->operation) {
case CMD_INSERT:
return PlanTransformer::TransformInsert(mt_plan_state);
break;
case CMD_UPDATE:
return PlanTransformer::TransformUpdate(mt_plan_state);
break;
case CMD_DELETE:
return PlanTransformer::TransformDelete(mt_plan_state);
break;
default:
break;
}
return nullptr;
}
/**
* @brief Convert ModifyTableState Insert case into AbstractPlanNode.
* @return Pointer to the constructed AbstractPlanNode.
*/
planner::AbstractPlanNode *PlanTransformer::TransformInsert(
const ModifyTableState *mt_plan_state) {
/* Resolve result table */
ResultRelInfo *result_rel_info = mt_plan_state->resultRelInfo;
Relation result_relation_desc = result_rel_info->ri_RelationDesc;
/* Currently, we only support plain insert statement.
* So, the number of subplan must be exactly 1.
* TODO: can it be 0? */
assert(mt_plan_state->mt_nplans == 1);
Oid database_oid = GetCurrentDatabaseOid();
Oid table_oid = result_relation_desc->rd_id;
/* Get the target table */
storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
GetLocation(database_oid, table_oid));
/* Get the tuple schema */
auto schema = target_table->GetSchema();
/* Should be only one which is a Result Plan */
PlanState *subplan_state = mt_plan_state->mt_plans[0];
TupleTableSlot *plan_slot;
std::vector<storage::Tuple *> tuples;
/*
plan_slot = ExecProcNode(subplan_state);
assert(!TupIsNull(plan_slot)); // The tuple should not be null
auto tuple = TupleTransformer(plan_slot, schema);
tuples.push_back(tuple);
*/
auto plan_node = new planner::InsertNode(target_table, tuples);
return plan_node;
}
planner::AbstractPlanNode* PlanTransformer::TransformUpdate(
const ModifyTableState* mt_plan_state) {
return nullptr;
}
/**
* @brief Convert a Postgres ModifyTableState with DELETE operation
* into a Peloton DeleteNode.
* @return Pointer to the constructed AbstractPlanNode.
*
* Just like Peloton,
* the delete plan state in Postgres simply deletes tuples
* returned by a subplan.
* So we don't need to handle predicates locally .
*/
planner::AbstractPlanNode* PlanTransformer::TransformDelete(
const ModifyTableState* mt_plan_state) {
// Grab Database ID and Table ID
assert(mt_plan_state->resultRelInfo); // Input must come from a subplan
assert(mt_plan_state->mt_nplans == 1); // Maybe relax later. I don't know when they can have >1 subplans.
Oid database_oid = GetCurrentDatabaseOid();
Oid table_oid = mt_plan_state->resultRelInfo[0].ri_RelationDesc->rd_id;
/* Grab the target table */
storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
GetLocation(database_oid, table_oid));
/* Grab the subplan -> child plan node */
assert(mt_plan_state->mt_nplans == 1);
PlanState *sub_planstate = mt_plan_state->mt_plans[0];
bool truncate = false;
// Create the peloton plan node
auto plan_node = new planner::DeleteNode(target_table, truncate);
// Add child plan node(s)
plan_node->AddChild(TransformPlan(sub_planstate));
return plan_node;
}
/**
* @brief Convert a Postgres SeqScanState into a Peloton SeqScanNode.
* @return Pointer to the constructed AbstractPlanNode.
*
* TODO: Can we also scan result from a child operator? (Non-base-table scan?)
* We can't for now, but Postgres can.
*/
planner::AbstractPlanNode* PlanTransformer::TransformSeqScan(
const SeqScanState* ss_plan_state) {
assert(nodeTag(ss_plan_state) == T_SeqScanState);
// Grab Database ID and Table ID
assert(ss_plan_state->ss_currentRelation); // Null if not a base table scan
Oid database_oid = GetCurrentDatabaseOid();
Oid table_oid = ss_plan_state->ss_currentRelation->rd_id;
/* Grab the target table */
storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
GetLocation(database_oid, table_oid));
/*
* Grab and transform the predicate.
*
* TODO:
* The qualifying predicate should be extracted from:
* ss_plan_state->ps.qual (null if no predicate)
*
* Let's just use a null predicate for now.
*/
expression::AbstractExpression* predicate = nullptr;
/*
* Grab and transform the output column Id's.
*
* TODO:
* The output columns should be extracted from:
* ss_plan_state->ps.ps_ProjInfo (null if no projection)
*
* Let's just select all columns for now
*/
auto schema = target_table->GetSchema();
std::vector<oid_t> column_ids(schema->GetColumnCount());
std::iota(column_ids.begin(), column_ids.end(), 0);
assert(column_ids.size() > 0);
/* Construct and return the Peloton plan node */
auto plan_node = new planner::SeqScanNode(target_table, predicate, column_ids);
return plan_node;
}
} // namespace bridge
} // namespace peloton
<commit_msg>minor fix<commit_after>/*-------------------------------------------------------------------------
*
* plan_transformer.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /n-store/src/bridge/plan_transformer.cpp
*
*-------------------------------------------------------------------------
*/
#include "nodes/pprint.h"
#include "utils/rel.h"
#include "bridge/bridge.h"
#include "executor/executor.h"
#include "backend/bridge/plan_transformer.h"
#include "backend/bridge/tuple_transformer.h"
#include "backend/expression/abstract_expression.h"
#include "backend/storage/data_table.h"
#include "backend/planner/delete_node.h"
#include "backend/planner/insert_node.h"
#include "backend/planner/seq_scan_node.h"
void printPlanStateTree(const PlanState * planstate);
namespace peloton {
namespace bridge {
/**
* @brief Pretty print the plan state tree.
* @return none.
*/
void PlanTransformer::PrintPlanState(const PlanState *plan_state) {
printPlanStateTree(plan_state);
}
/**
* @brief Convert Postgres PlanState into AbstractPlanNode.
* @return Pointer to the constructed AbstractPlanNode.
*/
planner::AbstractPlanNode *PlanTransformer::TransformPlan(const PlanState *plan_state) {
Plan *plan = plan_state->plan;
planner::AbstractPlanNode *plan_node;
switch (nodeTag(plan)) {
case T_ModifyTable:
plan_node = PlanTransformer::TransformModifyTable(reinterpret_cast<const ModifyTableState *>(plan_state));
break;
case T_SeqScan:
plan_node = PlanTransformer::TransformSeqScan(reinterpret_cast<const SeqScanState*>(plan_state));
break;
default:
plan_node = nullptr;
break;
}
return plan_node;
}
/**
* @brief Convert ModifyTableState into AbstractPlanNode.
* @return Pointer to the constructed AbstractPlanNode.
*
* Basically, it multiplexes into helper methods based on operation type.
*/
planner::AbstractPlanNode *PlanTransformer::TransformModifyTable(
const ModifyTableState *mt_plan_state) {
/* TODO: Add logging */
ModifyTable *plan = (ModifyTable *) mt_plan_state->ps.plan;
switch (plan->operation) {
case CMD_INSERT:
return PlanTransformer::TransformInsert(mt_plan_state);
break;
case CMD_UPDATE:
return PlanTransformer::TransformUpdate(mt_plan_state);
break;
case CMD_DELETE:
return PlanTransformer::TransformDelete(mt_plan_state);
break;
default:
break;
}
return nullptr;
}
/**
* @brief Convert ModifyTableState Insert case into AbstractPlanNode.
* @return Pointer to the constructed AbstractPlanNode.
*/
planner::AbstractPlanNode *PlanTransformer::TransformInsert(
const ModifyTableState *mt_plan_state) {
/* Resolve result table */
ResultRelInfo *result_rel_info = mt_plan_state->resultRelInfo;
Relation result_relation_desc = result_rel_info->ri_RelationDesc;
/* Currently, we only support plain insert statement.
* So, the number of subplan must be exactly 1.
* TODO: can it be 0? */
assert(mt_plan_state->mt_nplans == 1);
Oid database_oid = GetCurrentDatabaseOid();
Oid table_oid = result_relation_desc->rd_id;
/* Get the target table */
storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
GetLocation(database_oid, table_oid));
/* Get the tuple schema */
auto schema = target_table->GetSchema();
/* Should be only one which is a Result Plan */
PlanState *subplan_state = mt_plan_state->mt_plans[0];
TupleTableSlot *plan_slot;
std::vector<storage::Tuple *> tuples;
/*
* We are only making the plan,
* so we should definitely not call ExecProcNode() here.
* In Postgres, tuple-to-insert is retrieved from a child plan
* called "Result".
* Shall we make something similar in Peloton?
plan_slot = ExecProcNode(subplan_state);
assert(!TupIsNull(plan_slot)); // The tuple should not be null
auto tuple = TupleTransformer(plan_slot, schema);
tuples.push_back(tuple);
*/
auto plan_node = new planner::InsertNode(target_table, tuples);
return plan_node;
}
planner::AbstractPlanNode* PlanTransformer::TransformUpdate(
const ModifyTableState* mt_plan_state) {
return nullptr;
}
/**
* @brief Convert a Postgres ModifyTableState with DELETE operation
* into a Peloton DeleteNode.
* @return Pointer to the constructed AbstractPlanNode.
*
* Just like Peloton,
* the delete plan state in Postgres simply deletes tuples
* returned by a subplan.
* So we don't need to handle predicates locally .
*/
planner::AbstractPlanNode* PlanTransformer::TransformDelete(
const ModifyTableState* mt_plan_state) {
// Grab Database ID and Table ID
assert(mt_plan_state->resultRelInfo); // Input must come from a subplan
assert(mt_plan_state->mt_nplans == 1); // Maybe relax later. I don't know when they can have >1 subplans.
Oid database_oid = GetCurrentDatabaseOid();
Oid table_oid = mt_plan_state->resultRelInfo[0].ri_RelationDesc->rd_id;
/* Grab the target table */
storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
GetLocation(database_oid, table_oid));
/* Grab the subplan -> child plan node */
assert(mt_plan_state->mt_nplans == 1);
PlanState *sub_planstate = mt_plan_state->mt_plans[0];
bool truncate = false;
// Create the peloton plan node
auto plan_node = new planner::DeleteNode(target_table, truncate);
// Add child plan node(s)
plan_node->AddChild(TransformPlan(sub_planstate));
return plan_node;
}
/**
* @brief Convert a Postgres SeqScanState into a Peloton SeqScanNode.
* @return Pointer to the constructed AbstractPlanNode.
*
* TODO: Can we also scan result from a child operator? (Non-base-table scan?)
* We can't for now, but Postgres can.
*/
planner::AbstractPlanNode* PlanTransformer::TransformSeqScan(
const SeqScanState* ss_plan_state) {
assert(nodeTag(ss_plan_state) == T_SeqScanState);
// Grab Database ID and Table ID
assert(ss_plan_state->ss_currentRelation); // Null if not a base table scan
Oid database_oid = GetCurrentDatabaseOid();
Oid table_oid = ss_plan_state->ss_currentRelation->rd_id;
/* Grab the target table */
storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
GetLocation(database_oid, table_oid));
/*
* Grab and transform the predicate.
*
* TODO:
* The qualifying predicate should be extracted from:
* ss_plan_state->ps.qual (null if no predicate)
*
* Let's just use a null predicate for now.
*/
expression::AbstractExpression* predicate = nullptr;
/*
* Grab and transform the output column Id's.
*
* TODO:
* The output columns should be extracted from:
* ss_plan_state->ps.ps_ProjInfo (null if no projection)
*
* Let's just select all columns for now
*/
auto schema = target_table->GetSchema();
std::vector<oid_t> column_ids(schema->GetColumnCount());
std::iota(column_ids.begin(), column_ids.end(), 0);
assert(column_ids.size() > 0);
/* Construct and return the Peloton plan node */
auto plan_node = new planner::SeqScanNode(target_table, predicate, column_ids);
return plan_node;
}
} // namespace bridge
} // namespace peloton
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//-------------------------------------
//
// Icon Button Control
// Draws the bitmap within a special button control. Only a single bitmap is used and the
// button will be drawn in a highlighted mode when the mouse hovers over it or when it
// has been clicked.
//
// Use mTextLocation to choose where within the button the text will be drawn, if at all.
// Use mTextMargin to set the text away from the button sides or from the bitmap.
// Use mButtonMargin to set everything away from the button sides.
// Use mErrorBitmapName to set the name of a bitmap to draw if the main bitmap cannot be found.
// Use mFitBitmapToButton to force the bitmap to fill the entire button extent. Usually used
// with no button text defined.
//
//
#include "platform/platform.h"
#include "gui/buttons/guiIconButtonCtrl.h"
#include "console/console.h"
#include "gfx/gfxDevice.h"
#include "gfx/gfxDrawUtil.h"
#include "console/consoleTypes.h"
#include "gui/core/guiCanvas.h"
#include "gui/core/guiDefaultControlRender.h"
#include "console/engineAPI.h"
static const ColorI colorWhite(255,255,255);
static const ColorI colorBlack(0,0,0);
IMPLEMENT_CONOBJECT(GuiIconButtonCtrl);
ConsoleDocClass( GuiIconButtonCtrl,
"@brief Draws the bitmap within a special button control. Only a single bitmap is used and the\n"
"button will be drawn in a highlighted mode when the mouse hovers over it or when it\n"
"has been clicked.\n\n"
"@tsexample\n"
"new GuiIconButtonCtrl(TestIconButton)\n"
"{\n"
" buttonMargin = \"4 4\";\n"
" iconBitmap = \"art/gui/lagIcon.png\";\n"
" iconLocation = \"Center\";\n"
" sizeIconToButton = \"0\";\n"
" makeIconSquare = \"1\";\n"
" textLocation = \"Bottom\";\n"
" textMargin = \"-2\";\n"
" autoSize = \"0\";\n"
" text = \"Lag Icon\";\n"
" textID = \"\"STR_LAG\"\";\n"
" buttonType = \"PushButton\";\n"
" profile = \"GuiIconButtonProfile\";\n"
"};\n"
"@endtsexample\n\n"
"@see GuiControl\n"
"@see GuiButtonCtrl\n\n"
"@ingroup GuiCore\n"
);
GuiIconButtonCtrl::GuiIconButtonCtrl()
{
mBitmapName = StringTable->insert("");
mTextLocation = TextLocLeft;
mIconLocation = IconLocLeft;
mTextMargin = 4;
mButtonMargin.set(4,4);
mFitBitmapToButton = false;
mMakeIconSquare = false;
mErrorBitmapName = StringTable->insert("");
mErrorTextureHandle = NULL;
mAutoSize = false;
setExtent(140, 30);
}
ImplementEnumType( GuiIconButtonTextLocation,
"\n\n"
"@ingroup GuiImages" )
{ GuiIconButtonCtrl::TextLocNone, "None" },
{ GuiIconButtonCtrl::TextLocBottom, "Bottom" },
{ GuiIconButtonCtrl::TextLocRight, "Right" },
{ GuiIconButtonCtrl::TextLocTop, "Top" },
{ GuiIconButtonCtrl::TextLocLeft, "Left" },
{ GuiIconButtonCtrl::TextLocCenter, "Center" },
EndImplementEnumType;
ImplementEnumType( GuiIconButtonIconLocation,
"\n\n"
"@ingroup GuiImages" )
{ GuiIconButtonCtrl::IconLocNone, "None" },
{ GuiIconButtonCtrl::IconLocLeft, "Left" },
{ GuiIconButtonCtrl::IconLocRight, "Right" },
{ GuiIconButtonCtrl::IconLocCenter, "Center" }
EndImplementEnumType;
void GuiIconButtonCtrl::initPersistFields()
{
addField( "buttonMargin", TypePoint2I, Offset( mButtonMargin, GuiIconButtonCtrl ),"Margin area around the button.\n");
addField( "iconBitmap", TypeFilename, Offset( mBitmapName, GuiIconButtonCtrl ),"Bitmap file for the icon to display on the button.\n");
addField( "iconLocation", TYPEID< IconLocation >(), Offset( mIconLocation, GuiIconButtonCtrl ),"Where to place the icon on the control. Options are 0 (None), 1 (Left), 2 (Right), 3 (Center).\n");
addField( "sizeIconToButton", TypeBool, Offset( mFitBitmapToButton, GuiIconButtonCtrl ),"If true, the icon will be scaled to be the same size as the button.\n");
addField( "makeIconSquare", TypeBool, Offset( mMakeIconSquare, GuiIconButtonCtrl ),"If true, will make sure the icon is square.\n");
addField( "textLocation", TYPEID< TextLocation >(), Offset( mTextLocation, GuiIconButtonCtrl ),"Where to place the text on the control.\n"
"Options are 0 (None), 1 (Bottom), 2 (Right), 3 (Top), 4 (Left), 5 (Center).\n");
addField( "textMargin", TypeS32, Offset( mTextMargin, GuiIconButtonCtrl ),"Margin between the icon and the text.\n");
addField( "autoSize", TypeBool, Offset( mAutoSize, GuiIconButtonCtrl ),"If true, the text and icon will be automatically sized to the size of the control.\n");
Parent::initPersistFields();
}
bool GuiIconButtonCtrl::onWake()
{
if (! Parent::onWake())
return false;
setActive(true);
setBitmap(mBitmapName);
if( mProfile )
mProfile->constructBitmapArray();
return true;
}
void GuiIconButtonCtrl::onSleep()
{
mTextureNormal = NULL;
Parent::onSleep();
}
void GuiIconButtonCtrl::inspectPostApply()
{
Parent::inspectPostApply();
}
void GuiIconButtonCtrl::onStaticModified(const char* slotName, const char* newValue)
{
if ( isProperlyAdded() && !dStricmp(slotName, "autoSize") )
resize( getPosition(), getExtent() );
}
bool GuiIconButtonCtrl::resize(const Point2I &newPosition, const Point2I &newExtent)
{
if ( !mAutoSize || !mProfile->mFont )
return Parent::resize( newPosition, newExtent );
Point2I autoExtent( mMinExtent );
if ( mIconLocation != IconLocNone )
{
autoExtent.y = mTextureNormal.getHeight() + mButtonMargin.y * 2;
autoExtent.x = mTextureNormal.getWidth() + mButtonMargin.x * 2;
}
if ( mTextLocation != TextLocNone && mButtonText && mButtonText[0] )
{
U32 strWidth = mProfile->mFont->getStrWidthPrecise( mButtonText );
if ( mTextLocation == TextLocLeft || mTextLocation == TextLocRight )
{
autoExtent.x += strWidth + mTextMargin * 2;
}
else // Top, Bottom, Center
{
strWidth += mTextMargin * 2;
if ( strWidth > autoExtent.x )
autoExtent.x = strWidth;
}
}
return Parent::resize( newPosition, autoExtent );
}
void GuiIconButtonCtrl::setBitmap(const char *name)
{
mBitmapName = StringTable->insert(name);
if(!isAwake())
return;
if (*mBitmapName)
{
mTextureNormal = GFXTexHandle( name, &GFXDefaultPersistentProfile, avar("%s() - mTextureNormal (line %d)", __FUNCTION__, __LINE__) );
}
else
{
mTextureNormal = NULL;
}
// So that extent is recalculated if autoSize is set.
resize( getPosition(), getExtent() );
setUpdate();
}
void GuiIconButtonCtrl::onRender(Point2I offset, const RectI& updateRect)
{
renderButton( offset, updateRect);
}
void GuiIconButtonCtrl::renderButton( Point2I &offset, const RectI& updateRect )
{
bool highlight = mMouseOver;
bool depressed = mDepressed;
ColorI fontColor = mActive ? (highlight ? mProfile->mFontColor : mProfile->mFontColor) : mProfile->mFontColorNA;
RectI boundsRect(offset, getExtent());
GFXDrawUtil *drawer = GFX->getDrawUtil();
if (mDepressed || mStateOn)
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
renderBitmapArray(boundsRect, statePressed);
else
renderSlightlyLoweredBox(boundsRect, mProfile);
}
else if(mMouseOver && mActive)
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
renderBitmapArray(boundsRect, stateMouseOver);
else
renderSlightlyRaisedBox(boundsRect, mProfile);
}
else
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
{
if(mActive)
renderBitmapArray(boundsRect, stateNormal);
else
renderBitmapArray(boundsRect, stateDisabled);
}
else
{
drawer->drawRectFill(boundsRect, mProfile->mFillColorNA);
drawer->drawRect(boundsRect, mProfile->mBorderColorNA);
}
}
Point2I textPos = offset;
if(depressed)
textPos += Point2I(1,1);
RectI iconRect( 0, 0, 0, 0 );
// Render the icon
if ( mTextureNormal && mIconLocation != GuiIconButtonCtrl::IconLocNone )
{
// Render the normal bitmap
drawer->clearBitmapModulation();
// Maintain the bitmap size or fill the button?
if ( !mFitBitmapToButton )
{
Point2I textureSize( mTextureNormal->getWidth(), mTextureNormal->getHeight() );
iconRect.set( offset + mButtonMargin, textureSize );
if ( mIconLocation == IconLocRight )
{
iconRect.point.x = ( offset.x + getWidth() ) - ( mButtonMargin.x + textureSize.x );
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
else if ( mIconLocation == IconLocLeft )
{
iconRect.point.x = offset.x + mButtonMargin.x;
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
else if ( mIconLocation == IconLocCenter )
{
iconRect.point.x = offset.x + ( getWidth() - textureSize.x ) / 2;
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
drawer->drawBitmapStretch( mTextureNormal, iconRect );
}
else
{
iconRect.set( offset + mButtonMargin, getExtent() - (mButtonMargin * 2) );
if ( mMakeIconSquare )
{
// Square the icon to the smaller axis extent.
if ( iconRect.extent.x < iconRect.extent.y )
iconRect.extent.y = iconRect.extent.x;
else
iconRect.extent.x = iconRect.extent.y;
}
drawer->drawBitmapStretch( mTextureNormal, iconRect );
}
}
// Render text
if ( mTextLocation != TextLocNone )
{
// Clip text to fit (appends ...),
// pad some space to keep it off our border
String text( mButtonText );
S32 textWidth = clipText( text, getWidth() - 4 - mTextMargin );
drawer->setBitmapModulation( fontColor );
if ( mTextLocation == TextLocRight )
{
Point2I start( mTextMargin, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
if ( mTextureNormal && mIconLocation != IconLocNone )
{
start.x = iconRect.extent.x + mButtonMargin.x + mTextMargin;
}
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocLeft )
{
Point2I start( mTextMargin, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocCenter )
{
Point2I start;
if ( mTextureNormal && mIconLocation == IconLocLeft )
{
start.set( ( getWidth() - textWidth - iconRect.extent.x ) / 2 + iconRect.extent.x,
( getHeight() - mProfile->mFont->getHeight() ) / 2 );
}
else
start.set( ( getWidth() - textWidth ) / 2, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
drawer->setBitmapModulation( fontColor );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocBottom )
{
Point2I start;
start.set( ( getWidth() - textWidth ) / 2, getHeight() - mProfile->mFont->getHeight() - mTextMargin );
// If the text is longer then the box size
// it will get clipped, force Left Justify
if( textWidth > getWidth() )
start.x = 0;
drawer->setBitmapModulation( fontColor );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
}
renderChildControls( offset, updateRect);
}
// Draw the bitmap array's borders according to the button's state.
void GuiIconButtonCtrl::renderBitmapArray(RectI &bounds, S32 state)
{
switch(state)
{
case stateNormal:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 1, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 1, mProfile);
break;
case stateMouseOver:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 2, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 2, mProfile);
break;
case statePressed:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 3, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 3, mProfile);
break;
case stateDisabled:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 4, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 4, mProfile);
break;
}
}
DefineEngineMethod( GuiIconButtonCtrl, setBitmap, void, (const char* buttonFilename),,
"@brief Set the bitmap to use for the button portion of this control.\n\n"
"@param buttonFilename Filename for the image\n"
"@tsexample\n"
"// Define the button filename\n"
"%buttonFilename = \"pearlButton\";\n\n"
"// Inform the GuiIconButtonCtrl control to update its main button graphic to the defined bitmap\n"
"%thisGuiIconButtonCtrl.setBitmap(%buttonFilename);\n"
"@endtsexample\n\n"
"@see GuiControl\n"
"@see GuiButtonCtrl\n\n")
{
char* argBuffer = Con::getArgBuffer( 512 );
Platform::makeFullPathName( buttonFilename, argBuffer, 512 );
object->setBitmap( argBuffer );
}<commit_msg>Fixed missing check for highlighted font color on GUI icon button<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//-------------------------------------
//
// Icon Button Control
// Draws the bitmap within a special button control. Only a single bitmap is used and the
// button will be drawn in a highlighted mode when the mouse hovers over it or when it
// has been clicked.
//
// Use mTextLocation to choose where within the button the text will be drawn, if at all.
// Use mTextMargin to set the text away from the button sides or from the bitmap.
// Use mButtonMargin to set everything away from the button sides.
// Use mErrorBitmapName to set the name of a bitmap to draw if the main bitmap cannot be found.
// Use mFitBitmapToButton to force the bitmap to fill the entire button extent. Usually used
// with no button text defined.
//
//
#include "platform/platform.h"
#include "gui/buttons/guiIconButtonCtrl.h"
#include "console/console.h"
#include "gfx/gfxDevice.h"
#include "gfx/gfxDrawUtil.h"
#include "console/consoleTypes.h"
#include "gui/core/guiCanvas.h"
#include "gui/core/guiDefaultControlRender.h"
#include "console/engineAPI.h"
static const ColorI colorWhite(255,255,255);
static const ColorI colorBlack(0,0,0);
IMPLEMENT_CONOBJECT(GuiIconButtonCtrl);
ConsoleDocClass( GuiIconButtonCtrl,
"@brief Draws the bitmap within a special button control. Only a single bitmap is used and the\n"
"button will be drawn in a highlighted mode when the mouse hovers over it or when it\n"
"has been clicked.\n\n"
"@tsexample\n"
"new GuiIconButtonCtrl(TestIconButton)\n"
"{\n"
" buttonMargin = \"4 4\";\n"
" iconBitmap = \"art/gui/lagIcon.png\";\n"
" iconLocation = \"Center\";\n"
" sizeIconToButton = \"0\";\n"
" makeIconSquare = \"1\";\n"
" textLocation = \"Bottom\";\n"
" textMargin = \"-2\";\n"
" autoSize = \"0\";\n"
" text = \"Lag Icon\";\n"
" textID = \"\"STR_LAG\"\";\n"
" buttonType = \"PushButton\";\n"
" profile = \"GuiIconButtonProfile\";\n"
"};\n"
"@endtsexample\n\n"
"@see GuiControl\n"
"@see GuiButtonCtrl\n\n"
"@ingroup GuiCore\n"
);
GuiIconButtonCtrl::GuiIconButtonCtrl()
{
mBitmapName = StringTable->insert("");
mTextLocation = TextLocLeft;
mIconLocation = IconLocLeft;
mTextMargin = 4;
mButtonMargin.set(4,4);
mFitBitmapToButton = false;
mMakeIconSquare = false;
mErrorBitmapName = StringTable->insert("");
mErrorTextureHandle = NULL;
mAutoSize = false;
setExtent(140, 30);
}
ImplementEnumType( GuiIconButtonTextLocation,
"\n\n"
"@ingroup GuiImages" )
{ GuiIconButtonCtrl::TextLocNone, "None" },
{ GuiIconButtonCtrl::TextLocBottom, "Bottom" },
{ GuiIconButtonCtrl::TextLocRight, "Right" },
{ GuiIconButtonCtrl::TextLocTop, "Top" },
{ GuiIconButtonCtrl::TextLocLeft, "Left" },
{ GuiIconButtonCtrl::TextLocCenter, "Center" },
EndImplementEnumType;
ImplementEnumType( GuiIconButtonIconLocation,
"\n\n"
"@ingroup GuiImages" )
{ GuiIconButtonCtrl::IconLocNone, "None" },
{ GuiIconButtonCtrl::IconLocLeft, "Left" },
{ GuiIconButtonCtrl::IconLocRight, "Right" },
{ GuiIconButtonCtrl::IconLocCenter, "Center" }
EndImplementEnumType;
void GuiIconButtonCtrl::initPersistFields()
{
addField( "buttonMargin", TypePoint2I, Offset( mButtonMargin, GuiIconButtonCtrl ),"Margin area around the button.\n");
addField( "iconBitmap", TypeFilename, Offset( mBitmapName, GuiIconButtonCtrl ),"Bitmap file for the icon to display on the button.\n");
addField( "iconLocation", TYPEID< IconLocation >(), Offset( mIconLocation, GuiIconButtonCtrl ),"Where to place the icon on the control. Options are 0 (None), 1 (Left), 2 (Right), 3 (Center).\n");
addField( "sizeIconToButton", TypeBool, Offset( mFitBitmapToButton, GuiIconButtonCtrl ),"If true, the icon will be scaled to be the same size as the button.\n");
addField( "makeIconSquare", TypeBool, Offset( mMakeIconSquare, GuiIconButtonCtrl ),"If true, will make sure the icon is square.\n");
addField( "textLocation", TYPEID< TextLocation >(), Offset( mTextLocation, GuiIconButtonCtrl ),"Where to place the text on the control.\n"
"Options are 0 (None), 1 (Bottom), 2 (Right), 3 (Top), 4 (Left), 5 (Center).\n");
addField( "textMargin", TypeS32, Offset( mTextMargin, GuiIconButtonCtrl ),"Margin between the icon and the text.\n");
addField( "autoSize", TypeBool, Offset( mAutoSize, GuiIconButtonCtrl ),"If true, the text and icon will be automatically sized to the size of the control.\n");
Parent::initPersistFields();
}
bool GuiIconButtonCtrl::onWake()
{
if (! Parent::onWake())
return false;
setActive(true);
setBitmap(mBitmapName);
if( mProfile )
mProfile->constructBitmapArray();
return true;
}
void GuiIconButtonCtrl::onSleep()
{
mTextureNormal = NULL;
Parent::onSleep();
}
void GuiIconButtonCtrl::inspectPostApply()
{
Parent::inspectPostApply();
}
void GuiIconButtonCtrl::onStaticModified(const char* slotName, const char* newValue)
{
if ( isProperlyAdded() && !dStricmp(slotName, "autoSize") )
resize( getPosition(), getExtent() );
}
bool GuiIconButtonCtrl::resize(const Point2I &newPosition, const Point2I &newExtent)
{
if ( !mAutoSize || !mProfile->mFont )
return Parent::resize( newPosition, newExtent );
Point2I autoExtent( mMinExtent );
if ( mIconLocation != IconLocNone )
{
autoExtent.y = mTextureNormal.getHeight() + mButtonMargin.y * 2;
autoExtent.x = mTextureNormal.getWidth() + mButtonMargin.x * 2;
}
if ( mTextLocation != TextLocNone && mButtonText && mButtonText[0] )
{
U32 strWidth = mProfile->mFont->getStrWidthPrecise( mButtonText );
if ( mTextLocation == TextLocLeft || mTextLocation == TextLocRight )
{
autoExtent.x += strWidth + mTextMargin * 2;
}
else // Top, Bottom, Center
{
strWidth += mTextMargin * 2;
if ( strWidth > autoExtent.x )
autoExtent.x = strWidth;
}
}
return Parent::resize( newPosition, autoExtent );
}
void GuiIconButtonCtrl::setBitmap(const char *name)
{
mBitmapName = StringTable->insert(name);
if(!isAwake())
return;
if (*mBitmapName)
{
mTextureNormal = GFXTexHandle( name, &GFXDefaultPersistentProfile, avar("%s() - mTextureNormal (line %d)", __FUNCTION__, __LINE__) );
}
else
{
mTextureNormal = NULL;
}
// So that extent is recalculated if autoSize is set.
resize( getPosition(), getExtent() );
setUpdate();
}
void GuiIconButtonCtrl::onRender(Point2I offset, const RectI& updateRect)
{
renderButton( offset, updateRect);
}
void GuiIconButtonCtrl::renderButton( Point2I &offset, const RectI& updateRect )
{
bool highlight = mMouseOver;
bool depressed = mDepressed;
ColorI fontColor = mActive ? (highlight ? mProfile->mFontColorHL : mProfile->mFontColor) : mProfile->mFontColorNA;
RectI boundsRect(offset, getExtent());
GFXDrawUtil *drawer = GFX->getDrawUtil();
if (mDepressed || mStateOn)
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
renderBitmapArray(boundsRect, statePressed);
else
renderSlightlyLoweredBox(boundsRect, mProfile);
}
else if(mMouseOver && mActive)
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
renderBitmapArray(boundsRect, stateMouseOver);
else
renderSlightlyRaisedBox(boundsRect, mProfile);
}
else
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
{
if(mActive)
renderBitmapArray(boundsRect, stateNormal);
else
renderBitmapArray(boundsRect, stateDisabled);
}
else
{
drawer->drawRectFill(boundsRect, mProfile->mFillColorNA);
drawer->drawRect(boundsRect, mProfile->mBorderColorNA);
}
}
Point2I textPos = offset;
if(depressed)
textPos += Point2I(1,1);
RectI iconRect( 0, 0, 0, 0 );
// Render the icon
if ( mTextureNormal && mIconLocation != GuiIconButtonCtrl::IconLocNone )
{
// Render the normal bitmap
drawer->clearBitmapModulation();
// Maintain the bitmap size or fill the button?
if ( !mFitBitmapToButton )
{
Point2I textureSize( mTextureNormal->getWidth(), mTextureNormal->getHeight() );
iconRect.set( offset + mButtonMargin, textureSize );
if ( mIconLocation == IconLocRight )
{
iconRect.point.x = ( offset.x + getWidth() ) - ( mButtonMargin.x + textureSize.x );
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
else if ( mIconLocation == IconLocLeft )
{
iconRect.point.x = offset.x + mButtonMargin.x;
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
else if ( mIconLocation == IconLocCenter )
{
iconRect.point.x = offset.x + ( getWidth() - textureSize.x ) / 2;
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
drawer->drawBitmapStretch( mTextureNormal, iconRect );
}
else
{
iconRect.set( offset + mButtonMargin, getExtent() - (mButtonMargin * 2) );
if ( mMakeIconSquare )
{
// Square the icon to the smaller axis extent.
if ( iconRect.extent.x < iconRect.extent.y )
iconRect.extent.y = iconRect.extent.x;
else
iconRect.extent.x = iconRect.extent.y;
}
drawer->drawBitmapStretch( mTextureNormal, iconRect );
}
}
// Render text
if ( mTextLocation != TextLocNone )
{
// Clip text to fit (appends ...),
// pad some space to keep it off our border
String text( mButtonText );
S32 textWidth = clipText( text, getWidth() - 4 - mTextMargin );
drawer->setBitmapModulation( fontColor );
if ( mTextLocation == TextLocRight )
{
Point2I start( mTextMargin, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
if ( mTextureNormal && mIconLocation != IconLocNone )
{
start.x = iconRect.extent.x + mButtonMargin.x + mTextMargin;
}
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocLeft )
{
Point2I start( mTextMargin, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocCenter )
{
Point2I start;
if ( mTextureNormal && mIconLocation == IconLocLeft )
{
start.set( ( getWidth() - textWidth - iconRect.extent.x ) / 2 + iconRect.extent.x,
( getHeight() - mProfile->mFont->getHeight() ) / 2 );
}
else
start.set( ( getWidth() - textWidth ) / 2, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
drawer->setBitmapModulation( fontColor );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocBottom )
{
Point2I start;
start.set( ( getWidth() - textWidth ) / 2, getHeight() - mProfile->mFont->getHeight() - mTextMargin );
// If the text is longer then the box size
// it will get clipped, force Left Justify
if( textWidth > getWidth() )
start.x = 0;
drawer->setBitmapModulation( fontColor );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
}
renderChildControls( offset, updateRect);
}
// Draw the bitmap array's borders according to the button's state.
void GuiIconButtonCtrl::renderBitmapArray(RectI &bounds, S32 state)
{
switch(state)
{
case stateNormal:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 1, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 1, mProfile);
break;
case stateMouseOver:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 2, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 2, mProfile);
break;
case statePressed:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 3, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 3, mProfile);
break;
case stateDisabled:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 4, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 4, mProfile);
break;
}
}
DefineEngineMethod( GuiIconButtonCtrl, setBitmap, void, (const char* buttonFilename),,
"@brief Set the bitmap to use for the button portion of this control.\n\n"
"@param buttonFilename Filename for the image\n"
"@tsexample\n"
"// Define the button filename\n"
"%buttonFilename = \"pearlButton\";\n\n"
"// Inform the GuiIconButtonCtrl control to update its main button graphic to the defined bitmap\n"
"%thisGuiIconButtonCtrl.setBitmap(%buttonFilename);\n"
"@endtsexample\n\n"
"@see GuiControl\n"
"@see GuiButtonCtrl\n\n")
{
char* argBuffer = Con::getArgBuffer( 512 );
Platform::makeFullPathName( buttonFilename, argBuffer, 512 );
object->setBitmap( argBuffer );
}
<|endoftext|>
|
<commit_before>#include "TTExtensionLoader.h"
#include "TTFoundation.h"
#include "TTEnvironment.h"
#include <vector>
#include <string>
// The organization here is as follows :
// 1. TTLoadExtensions is called and selects the paths
// where the extensions should be searched, in order.
// As soon as extensions are found in a folder, the search stops.
// 2. Platforms are defined as classes :
// - TTUnixCommon contains generic data for Unix-like systems
// - OS X, Linux, Android, Windows are the available platforms.
// 3. Each platform has a specific way to list what's in a folder :
// The relevant method is TTPlatform::TTLoadExtensionsFromFolder
// 4. The algorithm to load a file is generic : TTLoadExtension. The
// platform provides the algorithm with functions to get a handle.
using namespace std;
using TTStringVector = vector<string>;
// Utility compile-time functions to work with string constants.
// Except on windows, where constexpr will only be in VS2015 (hopefully...)
// This would allow to shrink this file size by a small half.
#if !defined(TT_PLATFORM_WIN)
template <typename T, size_t n>
constexpr size_t array_length(const T (&)[n])
{ return n; }
template <typename T>
constexpr size_t string_length(T&& t)
{ return array_length(forward<T&&>(t)) - 1; }
template<typename T>
constexpr bool string_empty(T&& t)
{ return string_length(forward<T&&>(t)) == 0; }
#endif
template<typename OS>
// Returns true if the filename (ex. : AudioEngine.ttdylib)
// is a correct extension filename for the platform we're in.
bool TTIsExtensionFilename(const string& filename)
{
auto res = mismatch(begin(OS::extensionPrefix),
end(OS::extensionPrefix),
begin(filename));
if (string_empty(OS::extensionPrefix) || res.first == (end(OS::extensionPrefix)))
{
if(filename.length() >= string_length(OS::extensionSuffix))
{
return (0 == filename.compare(
filename.length() - string_length(OS::extensionSuffix),
string_length(OS::extensionSuffix),
OS::extensionSuffix));
}
}
return false;
}
template<typename OS>
// Gets the extension name from the file name.
// ex. : libWebSocket.so on Android -> WebSocket
string TTFilenameToExtensionName(string name)
{
// Remove the prefix
if(!string_empty(OS::extensionPrefix))
name.erase(begin(name),
begin(name) + string_length(OS::extensionPrefix));
// Remove the suffix
if(!string_empty(OS::extensionSuffix))
name.erase(end(name) - string_length(OS::extensionSuffix),
end(name));
return name;
}
template<typename OS, typename Loader, typename GetProc>
// A generic way to load classes.
// Loader : a callable object that takes a filename of a shared object,
// and returns a handle.
// GetProc : a callable object that takes a handle and a function name,
// and returns a pointer to the function.
bool TTLoadExtension(const string& filename,
const string& folder,
Loader&& handle_fun,
GetProc&& getproc_fun)
{
// Check if the file is a Jamoma extension
if(!TTIsExtensionFilename<OS>(filename))
return false;
// Get a handle
void *handle = handle_fun((folder + "/" + filename).c_str());
if (!handle)
{
TTLogMessage("Error when trying to get an handle on %s.\n", filename.c_str());
return false;
}
// Load the Jamoma extension
string initFun = "TTLoadJamomaExtension_" + TTFilenameToExtensionName<OS>(filename);
auto initializer = reinterpret_cast<TTExtensionInitializationMethod>(getproc_fun(handle, initFun.c_str()));
if (initializer)
{
auto err = initializer();
if(err != kTTErrNone)
{
TTLogMessage("Error when initializing extension %s.\n", filename.c_str());
return false;
}
return true;
}
return false;
}
// Here is the platform-specific code.
// It is organized in the following fashion :
//
// * Each platform has an extension prefix (e.g. "lib", required on Android) and suffix (e.g. ".ttdylib").
// * Platforms have these paths defined (they will be evaluated in this order) :
// * A computed relative path (the path of the JamomaFoundation shared object)
// * Built-in relative paths (e.g. in an app bundle on OS X)
// * Built-in absolute paths (standard paths, e.g. "/usr/local/jamoma"...
// and a compiled-in absolute path (to allow package maintainers to add their own paths)
// * Common code for Unix-like platforms is abstracted in TTUnixCommon.
#if defined(TT_PLATFORM_MAC) || defined(TT_PLATFORM_LINUX)
#include <dlfcn.h>
#include <dirent.h>
// This class contains informations that are applicable to
// UNIX-like systems (i.e. they respect the Filesystem Hierarchy Standard
// and load shared objects using dlopen / dlsym).
class TTUnixCommon
{
public:
static TTStringVector builtinAbsolutePaths()
{
return {
#if defined(JAMOMA_EXTENSIONS_INSTALL_PREFIX)
JAMOMA_EXTENSIONS_INSTALL_PREFIX,
#endif
"/usr/lib/jamoma",
"/usr/local/lib/jamoma",
"/usr/jamoma/lib",
"/usr/jamoma/extensions",
"/usr/local/jamoma/lib",
"/usr/local/jamoma/extensions"
};
}
template<typename OS>
// Try to load extensions. Returns "true" only if at least one extension was loaded.
static bool TTLoadExtensionsFromFolder(const string& folder)
{
DIR* dirp = opendir(folder.c_str());
if(!dirp)
return false;
dirent* dp{};
int count = 0; // Number of extensions loaded.
while ((dp = readdir(dirp)))
{
if(TTLoadExtension<OS>(dp->d_name,
folder,
[] (const char * file)
{ return dlopen(file, RTLD_LAZY); },
[] (void* handle, const char * fun)
{ return dlsym(handle, fun); }))
{
++count;
}
}
closedir(dirp);
if(count > 0)
{
TTFoundationBinaryPath = folder.c_str();
return true;
}
return false;
}
// Returns the path of the extensions
// relative to the folder of the JamomaFoundation library
// the application uses.
static string computedRelativePath()
{
Dl_info info;
char mainBundleStr[4096];
// Use the path of JamomaFoundation
if (dladdr((const void*)TTLoadExtensions, &info))
{
char *c = 0;
TTLogMessage("computedRelativePath(): %s\n", info.dli_fname);
strncpy(mainBundleStr, info.dli_fname, 4096);
c = strrchr(mainBundleStr, '/');
if (c)
*c = 0; // chop the "/JamomaFoundation.dylib/so off of the path
}
return mainBundleStr;
}
};
#endif
#if defined(TT_PLATFORM_MAC)
class TTOSXSpecific
{
public:
static constexpr const char extensionPrefix[]{""};
static constexpr const char extensionSuffix[]{".ttdylib"};
static string computedRelativePath()
{ return TTUnixCommon::computedRelativePath(); }
static TTStringVector builtinRelativePaths()
{ return {"../Frameworks/jamoma/extensions"}; }
static TTStringVector builtinAbsolutePaths()
{ return TTUnixCommon::builtinAbsolutePaths(); }
static bool TTLoadExtensionsFromFolder(const string& folderName)
{ return TTUnixCommon::TTLoadExtensionsFromFolder<TTOSXSpecific>(folderName); }
};
using TTOperatingSystem = TTOSXSpecific;
#endif
// TODO iOS & Static loading.
#if defined(TT_PLATFORM_LINUX) && defined(__ANDROID_API__)
#include <unistd.h>
#include <iostream>
class TTAndroidSpecific
{
public:
static constexpr const char extensionPrefix[]{"lib"};
static constexpr const char extensionSuffix[]{".so"};
static string computedRelativePath()
{
string s{"/proc/" + string{getpid()} + "/cmdline"};
ifstream input{s.c_str()};
string line;
getline(input, line);
return string{"/data/data/"} + line + string{"/lib"};
}
static TTStringVector builtinRelativePaths()
{ return {}; }
static TTStringVector builtinAbsolutePaths()
{ return {}; }
static bool TTLoadExtensionsFromFolder(const string& folderName)
{ return TTUnixCommon::TTLoadExtensionsFromFolder<TTAndroidSpecific>(folderName); }
};
using TTOperatingSystem = TTAndroidSpecific;
#endif
#if defined(TT_PLATFORM_LINUX)
class TTLinuxSpecific
{
public:
static constexpr const char extensionPrefix[]="";
static constexpr const char extensionSuffix[]=".ttso";
static string computedRelativePath()
{ return TTUnixCommon::computedRelativePath(); }
static TTStringVector builtinRelativePaths()
{ return {"./extensions"}; }
static TTStringVector builtinAbsolutePaths()
{ return TTUnixCommon::builtinAbsolutePaths(); }
static bool TTLoadExtensionsFromFolder(const string& folderName)
{ return TTUnixCommon::TTLoadExtensionsFromFolder<TTLinuxSpecific>(folderName); }
};
using TTOperatingSystem = TTLinuxSpecific;
#endif
#if defined(TT_PLATFORM_WIN)
#include <ShlObj.h>
class TTWinSpecific
{
public:
static const char* extensionPrefix;
static const char* extensionSuffix;
static string computedRelativePath();
static TTStringVector builtinRelativePaths();
static TTStringVector builtinAbsolutePaths();
static bool TTLoadExtensionsFromFolder(const string& folder);
};
// Specializations since windows does not support constexpr yet.
template<>
string TTFilenameToExtensionName<TTWinSpecific>(string name)
{
name.erase(end(name) - strlen(TTWinSpecific::extensionSuffix), end(name));
return name;
}
template<>
bool TTIsExtensionFilename<TTWinSpecific>(const string& filename)
{
auto suffix_len = strlen(TTWinSpecific::extensionSuffix);
if(filename.length() >= suffix_len)
{
return (0 == filename.compare(
filename.length() - suffix_len,
suffix_len,
TTWinSpecific::extensionSuffix));
}
return false;
}
string TTWinSpecific::computedRelativePath()
{
TTString fullpath{};
char temppath[4096];
LONG lRes;
LPCSTR moduleName = "JamomaFoundation.dll";
HMODULE hmodule = GetModuleHandle(moduleName);
// get the path
GetModuleFileName(hmodule, (LPSTR)temppath, 4096);
if (!FAILED(hmodule) && temppath[0])
{
fullpath = temppath;
// get support folder path
fullpath = fullpath.substr(0, fullpath.length() - (strlen(moduleName) + 1));
lRes = SHCreateDirectory(NULL, (LPCWSTR)fullpath.c_str());
}
return fullpath.c_str();
}
TTStringVector TTWinSpecific::builtinRelativePaths()
{
return {"./extensions"};
}
TTStringVector TTWinSpecific::builtinAbsolutePaths()
{
return {
#if defined(JAMOMA_EXTENSIONS_INSTALL_PREFIX)
JAMOMA_EXTENSIONS_INSTALL_PREFIX,
#endif
"c:\\Program Files (x86)\\Jamoma\\extensions"
};
}
bool TTWinSpecific::TTLoadExtensionsFromFolder(const string& folder)
{
auto windowsPathSpec = folder
+ "/*"
+ string{TTWinSpecific::extensionSuffix};
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(windowsPathSpec.c_str(), &FindFileData);
int count = 0; // Number of extensions loaded.
if (hFind == INVALID_HANDLE_VALUE)
return false;
do {
if(TTLoadExtension<TTWinSpecific>(
FindFileData.cFileName,
folder,
[] (const char * file)
{ return LoadLibrary(file); },
[] (void* handle, const char * fun)
{ return GetProcAddress((HMODULE) handle, fun); }))
{
++count;
}
} while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
if(count > 0)
{
TTFoundationBinaryPath = folder.c_str();
return true;
}
return false;
}
using TTOperatingSystem = TTWinSpecific;
#endif
// Because these members are static they have to be allocated in this compilation unit.
#if defined(TT_PLATFORM_WIN)
const char* TTOperatingSystem::extensionPrefix{""};
const char* TTOperatingSystem::extensionSuffix{".ttdll"};
#else
constexpr const char TTOperatingSystem::extensionPrefix[array_length(TTOperatingSystem::extensionPrefix)];
constexpr const char TTOperatingSystem::extensionSuffix[array_length(TTOperatingSystem::extensionSuffix)];
#endif
template<typename OS>
// Try to load Jamoma classes from a vector of paths.
// This will return on the first successful folder.
bool TTLoadExtensionsFromPaths(TTStringVector&& v)
{
return find_if(begin(v), end(v), [] (const string& path)
{ return OS::TTLoadExtensionsFromFolder(path); }) != end(v);
}
template<typename OS>
// Try to load Jamoma classes from a path computed at runtime.
bool TTLoadExtensionsFromComputedPaths()
{
auto computedPath = TTOperatingSystem::computedRelativePath();
return (!computedPath.empty()
&& TTOperatingSystem::TTLoadExtensionsFromFolder(computedPath));
}
template<typename OS>
// Try to load Jamoma classes from the paths built-in for the
// platform.
bool TTLoadExtensionsFromBuiltinPaths()
{
return TTLoadExtensionsFromPaths<OS>(OS::builtinRelativePaths()) ||
TTLoadExtensionsFromPaths<OS>(OS::builtinAbsolutePaths());
}
void TTLoadExtensions(const char* pathToBinaries, bool loadFromOtherPaths)
{
if(!pathToBinaries)
{
if(!TTLoadExtensionsFromComputedPaths<TTOperatingSystem>() && loadFromOtherPaths)
{
TTLoadExtensionsFromBuiltinPaths<TTOperatingSystem>();
}
}
else
{
if(!TTOperatingSystem::TTLoadExtensionsFromFolder(pathToBinaries) && loadFromOtherPaths)
{
if(!TTLoadExtensionsFromComputedPaths<TTOperatingSystem>())
{
TTLoadExtensionsFromBuiltinPaths<TTOperatingSystem>();
}
}
}
if(TTFoundationBinaryPath == "")
{
TTLogMessage("Warning: no classes were loaded.");
}
}
<commit_msg>Add an extension loading class for iOS that does nothing<commit_after>#include "TTExtensionLoader.h"
#include "TTFoundation.h"
#include "TTEnvironment.h"
#include <vector>
#include <string>
// The organization here is as follows :
// 1. TTLoadExtensions is called and selects the paths
// where the extensions should be searched, in order.
// As soon as extensions are found in a folder, the search stops.
// 2. Platforms are defined as classes :
// - TTUnixCommon contains generic data for Unix-like systems
// - OS X, Linux, Android, Windows are the available platforms.
// 3. Each platform has a specific way to list what's in a folder :
// The relevant method is TTPlatform::TTLoadExtensionsFromFolder
// 4. The algorithm to load a file is generic : TTLoadExtension. The
// platform provides the algorithm with functions to get a handle.
using namespace std;
using TTStringVector = vector<string>;
// Utility compile-time functions to work with string constants.
// Except on windows, where constexpr will only be in VS2015 (hopefully...)
// This would allow to shrink this file size by a small half.
#if !defined(TT_PLATFORM_WIN)
template <typename T, size_t n>
constexpr size_t array_length(const T (&)[n])
{ return n; }
template <typename T>
constexpr size_t string_length(T&& t)
{ return array_length(forward<T&&>(t)) - 1; }
template<typename T>
constexpr bool string_empty(T&& t)
{ return string_length(forward<T&&>(t)) == 0; }
#endif
template<typename OS>
// Returns true if the filename (ex. : AudioEngine.ttdylib)
// is a correct extension filename for the platform we're in.
bool TTIsExtensionFilename(const string& filename)
{
auto res = mismatch(begin(OS::extensionPrefix),
end(OS::extensionPrefix),
begin(filename));
if (string_empty(OS::extensionPrefix) || res.first == (end(OS::extensionPrefix)))
{
if(filename.length() >= string_length(OS::extensionSuffix))
{
return (0 == filename.compare(
filename.length() - string_length(OS::extensionSuffix),
string_length(OS::extensionSuffix),
OS::extensionSuffix));
}
}
return false;
}
template<typename OS>
// Gets the extension name from the file name.
// ex. : libWebSocket.so on Android -> WebSocket
string TTFilenameToExtensionName(string name)
{
// Remove the prefix
if(!string_empty(OS::extensionPrefix))
name.erase(begin(name),
begin(name) + string_length(OS::extensionPrefix));
// Remove the suffix
if(!string_empty(OS::extensionSuffix))
name.erase(end(name) - string_length(OS::extensionSuffix),
end(name));
return name;
}
template<typename OS, typename Loader, typename GetProc>
// A generic way to load classes.
// Loader : a callable object that takes a filename of a shared object,
// and returns a handle.
// GetProc : a callable object that takes a handle and a function name,
// and returns a pointer to the function.
bool TTLoadExtension(const string& filename,
const string& folder,
Loader&& handle_fun,
GetProc&& getproc_fun)
{
// Check if the file is a Jamoma extension
if(!TTIsExtensionFilename<OS>(filename))
return false;
// Get a handle
void *handle = handle_fun((folder + "/" + filename).c_str());
if (!handle)
{
TTLogMessage("Error when trying to get an handle on %s.\n", filename.c_str());
return false;
}
// Load the Jamoma extension
string initFun = "TTLoadJamomaExtension_" + TTFilenameToExtensionName<OS>(filename);
auto initializer = reinterpret_cast<TTExtensionInitializationMethod>(getproc_fun(handle, initFun.c_str()));
if (initializer)
{
auto err = initializer();
if(err != kTTErrNone)
{
TTLogMessage("Error when initializing extension %s.\n", filename.c_str());
return false;
}
return true;
}
return false;
}
// Here is the platform-specific code.
// It is organized in the following fashion :
//
// * Each platform has an extension prefix (e.g. "lib", required on Android) and suffix (e.g. ".ttdylib").
// * Platforms have these paths defined (they will be evaluated in this order) :
// * A computed relative path (the path of the JamomaFoundation shared object)
// * Built-in relative paths (e.g. in an app bundle on OS X)
// * Built-in absolute paths (standard paths, e.g. "/usr/local/jamoma"...
// and a compiled-in absolute path (to allow package maintainers to add their own paths)
// * Common code for Unix-like platforms is abstracted in TTUnixCommon.
#if defined(TT_PLATFORM_MAC) || defined(TT_PLATFORM_LINUX)
#include <dlfcn.h>
#include <dirent.h>
// This class contains informations that are applicable to
// UNIX-like systems (i.e. they respect the Filesystem Hierarchy Standard
// and load shared objects using dlopen / dlsym).
class TTUnixCommon
{
public:
static TTStringVector builtinAbsolutePaths()
{
return {
#if defined(JAMOMA_EXTENSIONS_INSTALL_PREFIX)
JAMOMA_EXTENSIONS_INSTALL_PREFIX,
#endif
"/usr/lib/jamoma",
"/usr/local/lib/jamoma",
"/usr/jamoma/lib",
"/usr/jamoma/extensions",
"/usr/local/jamoma/lib",
"/usr/local/jamoma/extensions"
};
}
template<typename OS>
// Try to load extensions. Returns "true" only if at least one extension was loaded.
static bool TTLoadExtensionsFromFolder(const string& folder)
{
DIR* dirp = opendir(folder.c_str());
if(!dirp)
return false;
dirent* dp{};
int count = 0; // Number of extensions loaded.
while ((dp = readdir(dirp)))
{
if(TTLoadExtension<OS>(dp->d_name,
folder,
[] (const char * file)
{ return dlopen(file, RTLD_LAZY); },
[] (void* handle, const char * fun)
{ return dlsym(handle, fun); }))
{
++count;
}
}
closedir(dirp);
if(count > 0)
{
TTFoundationBinaryPath = folder.c_str();
return true;
}
return false;
}
// Returns the path of the extensions
// relative to the folder of the JamomaFoundation library
// the application uses.
static string computedRelativePath()
{
Dl_info info;
char mainBundleStr[4096];
// Use the path of JamomaFoundation
if (dladdr((const void*)TTLoadExtensions, &info))
{
char *c = 0;
TTLogMessage("computedRelativePath(): %s\n", info.dli_fname);
strncpy(mainBundleStr, info.dli_fname, 4096);
c = strrchr(mainBundleStr, '/');
if (c)
*c = 0; // chop the "/JamomaFoundation.dylib/so off of the path
}
return mainBundleStr;
}
};
#endif
#if defined(TT_PLATFORM_MAC)
class TTOSXSpecific
{
public:
static constexpr const char extensionPrefix[]{""};
static constexpr const char extensionSuffix[]{".ttdylib"};
static string computedRelativePath()
{ return TTUnixCommon::computedRelativePath(); }
static TTStringVector builtinRelativePaths()
{ return {"../Frameworks/jamoma/extensions"}; }
static TTStringVector builtinAbsolutePaths()
{ return TTUnixCommon::builtinAbsolutePaths(); }
static bool TTLoadExtensionsFromFolder(const string& folderName)
{ return TTUnixCommon::TTLoadExtensionsFromFolder<TTOSXSpecific>(folderName); }
};
using TTOperatingSystem = TTOSXSpecific;
#endif
#if defined(TT_PLATFORM_IOS)
class TTiOSSpecific
{
public:
static constexpr const char extensionPrefix[]{""};
static constexpr const char extensionSuffix[]{".ttdylib"};
static string computedRelativePath()
{ return ""; }
static TTStringVector builtinRelativePaths()
{ return {}; }
static TTStringVector builtinAbsolutePaths()
{ return {}; }
static bool TTLoadExtensionsFromFolder(const string& folderName)
{ return false; }
};
using TTOperatingSystem = TTiOSSpecific;
#endif
#if defined(TT_PLATFORM_LINUX) && defined(__ANDROID_API__)
#include <unistd.h>
#include <iostream>
class TTAndroidSpecific
{
public:
static constexpr const char extensionPrefix[]{"lib"};
static constexpr const char extensionSuffix[]{".so"};
static string computedRelativePath()
{
string s{"/proc/" + string{getpid()} + "/cmdline"};
ifstream input{s.c_str()};
string line;
getline(input, line);
return string{"/data/data/"} + line + string{"/lib"};
}
static TTStringVector builtinRelativePaths()
{ return {}; }
static TTStringVector builtinAbsolutePaths()
{ return {}; }
static bool TTLoadExtensionsFromFolder(const string& folderName)
{ return TTUnixCommon::TTLoadExtensionsFromFolder<TTAndroidSpecific>(folderName); }
};
using TTOperatingSystem = TTAndroidSpecific;
#endif
#if defined(TT_PLATFORM_LINUX)
class TTLinuxSpecific
{
public:
static constexpr const char extensionPrefix[]="";
static constexpr const char extensionSuffix[]=".ttso";
static string computedRelativePath()
{ return TTUnixCommon::computedRelativePath(); }
static TTStringVector builtinRelativePaths()
{ return {"./extensions"}; }
static TTStringVector builtinAbsolutePaths()
{ return TTUnixCommon::builtinAbsolutePaths(); }
static bool TTLoadExtensionsFromFolder(const string& folderName)
{ return TTUnixCommon::TTLoadExtensionsFromFolder<TTLinuxSpecific>(folderName); }
};
using TTOperatingSystem = TTLinuxSpecific;
#endif
#if defined(TT_PLATFORM_WIN)
#include <ShlObj.h>
class TTWinSpecific
{
public:
static const char* extensionPrefix;
static const char* extensionSuffix;
static string computedRelativePath();
static TTStringVector builtinRelativePaths();
static TTStringVector builtinAbsolutePaths();
static bool TTLoadExtensionsFromFolder(const string& folder);
};
// Specializations since windows does not support constexpr yet.
template<>
string TTFilenameToExtensionName<TTWinSpecific>(string name)
{
name.erase(end(name) - strlen(TTWinSpecific::extensionSuffix), end(name));
return name;
}
template<>
bool TTIsExtensionFilename<TTWinSpecific>(const string& filename)
{
auto suffix_len = strlen(TTWinSpecific::extensionSuffix);
if(filename.length() >= suffix_len)
{
return (0 == filename.compare(
filename.length() - suffix_len,
suffix_len,
TTWinSpecific::extensionSuffix));
}
return false;
}
string TTWinSpecific::computedRelativePath()
{
TTString fullpath{};
char temppath[4096];
LONG lRes;
LPCSTR moduleName = "JamomaFoundation.dll";
HMODULE hmodule = GetModuleHandle(moduleName);
// get the path
GetModuleFileName(hmodule, (LPSTR)temppath, 4096);
if (!FAILED(hmodule) && temppath[0])
{
fullpath = temppath;
// get support folder path
fullpath = fullpath.substr(0, fullpath.length() - (strlen(moduleName) + 1));
lRes = SHCreateDirectory(NULL, (LPCWSTR)fullpath.c_str());
}
return fullpath.c_str();
}
TTStringVector TTWinSpecific::builtinRelativePaths()
{
return {"./extensions"};
}
TTStringVector TTWinSpecific::builtinAbsolutePaths()
{
return {
#if defined(JAMOMA_EXTENSIONS_INSTALL_PREFIX)
JAMOMA_EXTENSIONS_INSTALL_PREFIX,
#endif
"c:\\Program Files (x86)\\Jamoma\\extensions"
};
}
bool TTWinSpecific::TTLoadExtensionsFromFolder(const string& folder)
{
auto windowsPathSpec = folder
+ "/*"
+ string{TTWinSpecific::extensionSuffix};
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(windowsPathSpec.c_str(), &FindFileData);
int count = 0; // Number of extensions loaded.
if (hFind == INVALID_HANDLE_VALUE)
return false;
do {
if(TTLoadExtension<TTWinSpecific>(
FindFileData.cFileName,
folder,
[] (const char * file)
{ return LoadLibrary(file); },
[] (void* handle, const char * fun)
{ return GetProcAddress((HMODULE) handle, fun); }))
{
++count;
}
} while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
if(count > 0)
{
TTFoundationBinaryPath = folder.c_str();
return true;
}
return false;
}
using TTOperatingSystem = TTWinSpecific;
#endif
// Because these members are static they have to be allocated in this compilation unit.
#if defined(TT_PLATFORM_WIN)
const char* TTOperatingSystem::extensionPrefix{""};
const char* TTOperatingSystem::extensionSuffix{".ttdll"};
#else
constexpr const char TTOperatingSystem::extensionPrefix[array_length(TTOperatingSystem::extensionPrefix)];
constexpr const char TTOperatingSystem::extensionSuffix[array_length(TTOperatingSystem::extensionSuffix)];
#endif
template<typename OS>
// Try to load Jamoma classes from a vector of paths.
// This will return on the first successful folder.
bool TTLoadExtensionsFromPaths(TTStringVector&& v)
{
return find_if(begin(v), end(v), [] (const string& path)
{ return OS::TTLoadExtensionsFromFolder(path); }) != end(v);
}
template<typename OS>
// Try to load Jamoma classes from a path computed at runtime.
bool TTLoadExtensionsFromComputedPaths()
{
auto computedPath = TTOperatingSystem::computedRelativePath();
return (!computedPath.empty()
&& TTOperatingSystem::TTLoadExtensionsFromFolder(computedPath));
}
template<typename OS>
// Try to load Jamoma classes from the paths built-in for the
// platform.
bool TTLoadExtensionsFromBuiltinPaths()
{
return TTLoadExtensionsFromPaths<OS>(OS::builtinRelativePaths()) ||
TTLoadExtensionsFromPaths<OS>(OS::builtinAbsolutePaths());
}
void TTLoadExtensions(const char* pathToBinaries, bool loadFromOtherPaths)
{
if(!pathToBinaries)
{
if(!TTLoadExtensionsFromComputedPaths<TTOperatingSystem>() && loadFromOtherPaths)
{
TTLoadExtensionsFromBuiltinPaths<TTOperatingSystem>();
}
}
else
{
if(!TTOperatingSystem::TTLoadExtensionsFromFolder(pathToBinaries) && loadFromOtherPaths)
{
if(!TTLoadExtensionsFromComputedPaths<TTOperatingSystem>())
{
TTLoadExtensionsFromBuiltinPaths<TTOperatingSystem>();
}
}
}
if(TTFoundationBinaryPath == "")
{
TTLogMessage("Warning: no classes were loaded.");
}
}
<|endoftext|>
|
<commit_before>/* --
* Copyright (C) 2013, George Makrydakis <irrequietus@gmail.com>
*
* This file is part of odreex.
*
* odreex 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 3 of the License, or (at your option) any later
* version.
*
* odreex 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
* odreex. If not, see http://www.gnu.org/licenses/.
*
*/
#ifndef _ODREEX_AMPLE_TEST_HH_
#define _ODREEX_AMPLE_TEST_HH_
#define ample_vldt_(t) \
static constexpr char const * showln() noexcept \
{ return t ; }
# ifdef AMPLE_PRINTLN_LIM
# if AMPLE_PRINTLN_LIM > 255
# define AMPLE_PRINTLN_LIM 52
# endif
# else
# define AMPLE_PRINTLN_LIM 52
# endif
#ifdef USE_ANSI_COLORS
#define ample_printf_(i, sz, N) \
printf( "\033[1;37m[%06llu]\033[0m: %s | %s |: \033[34m%s%s\033[0m\n" \
, static_cast<unsigned long long>(i) \
, result[ i ] ? "\033[36mpass\033[0m" : "\033[31mfail\033[0m" \
, output[ i ] ? "\033[1;36mpass\033[0m" : "\033[1;31mfail\033[0m" \
, cbuf \
, sz < N ? "" : "..." )
#else
#define ample_printf_(i, sz, N) \
printf( "[%06llu]: %s | %s |: %s%s\n" \
, static_cast<unsigned long long>(i) \
, result[ i ] ? "pass" : "fail" \
, output[ i ] ? "pass" : "fail" \
, cbuf \
, sz < N ? "" : "..." )
#endif
/**
* NOTE: Testing mechanism fundamentals for the various odreex::ample template
* metaprogramming constructs.
**/
#include <cstdio>
#include <cstring>
#include <type_traits>
#include <algorithm>
namespace odreex {
namespace ample {
namespace test {
struct as_passed {};
struct as_failed {};
struct as_output {};
struct as_expect {};
struct as_result {};
struct as_showln {};
/* class template for types that must be "matched" */
template<typename Type_X, typename Type_Y>
struct types_match
: std::integral_constant<bool, std::is_same<Type_X, Type_Y>::value >
{};
/* class template for values in types that must be "matched" */
template<typename Type_X, typename Type_Y>
struct values_match
: std::integral_constant<bool, Type_X::value == Type_Y::value>
{};
/* the default test class templates providing details */
template<typename Type_A, typename Type_B, bool Expected_B = true>
struct vldt_types : types_match<Type_A, Type_B> {
static constexpr bool expected() {
return Expected_B;
}
static constexpr bool result() {
return types_match<Type_A, Type_B>::value;
}
static constexpr bool output() {
return types_match<Type_A, Type_B>::value == Expected_B;
}
static constexpr char const * showln() {
return "default odreex::ample::test validation showln";
}
};
template<typename Type_A, typename Type_B, bool Expected_B = true>
struct vldt_values : values_match<Type_A, Type_B> {
static constexpr bool expected() {
return Expected_B;
}
static constexpr bool result() {
return values_match<Type_A, Type_B>::value;
}
static constexpr bool output() {
return values_match<Type_A, Type_B>::value == Expected_B;
}
static constexpr char const * showln() {
return "default odreex::ample::test validation showln";
}
};
/*NOTE: a wrapper class that is a temporary utility */
template<std::size_t... N>
struct wrap_
{};
/* NOTE: constexpr arrays seem to be having some issues with clang++ (3.3.x) so
* we will be using the "old" way of doing things until this thing gets fixed.
* Notice that g++ has no problem with either style.
*/
template<typename... T>
struct check_all {
template<typename, typename, typename, typename, std::size_t, bool Casc_B>
struct check_impl;
template< typename X
, typename... Xn
, std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Casc_B >
struct check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<X, Xn...>
, N
, Casc_B >
: std::conditional< X::output() == Casc_B
, check_impl< wrap_<A..., N>
, wrap_<B...>
, wrap_<C..., N>
, check_all<Xn...>
, N + 1
, Casc_B >
, check_impl< wrap_<A...>
, wrap_<B..., N>
, wrap_<C..., N>
, check_all<Xn...>
, N + 1
, Casc_B >>::type
{};
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Casc_B >
struct check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Casc_B > {
static std::size_t const passed_total = sizeof...(A);
static std::size_t const failed_total = sizeof...(B);
static std::size_t const checks_total = sizeof...(T);
static std::size_t const passed[sizeof...(A)];
static std::size_t const failed[sizeof...(B)];
static std::size_t const shnoop[sizeof...(C)];
static char const * showln[sizeof...(T)];
static bool const output[sizeof...(T)];
static bool const result[sizeof...(T)];
static bool const expect[sizeof...(T)];
};
public:
template<bool B>
using apply = check_impl<wrap_<>, wrap_<>, wrap_<>, check_all<T...>, 0, B>;
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
std::size_t const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::passed[] = {
A...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
std::size_t const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::failed[] = {
B...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
bool const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::result[] = {
T::result()...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
bool const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::output[] = {
T::output()...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
bool const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::expect[] = {
T::expected()...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
char const * check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::showln[] = {
T::showln()...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
std::size_t const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::shnoop[] = {
C...
};
template<bool Cascade_B, typename Check_T>
struct check : private Check_T::template apply<Cascade_B> {
private:
using Check_T::template apply<Cascade_B>::passed;
using Check_T::template apply<Cascade_B>::failed;
using Check_T::template apply<Cascade_B>::output;
using Check_T::template apply<Cascade_B>::result;
using Check_T::template apply<Cascade_B>::expect;
using Check_T::template apply<Cascade_B>::showln;
using Check_T::template apply<Cascade_B>::shnoop;
using Check_T::template apply<Cascade_B>::passed_total;
using Check_T::template apply<Cascade_B>::failed_total;
using Check_T::template apply<Cascade_B>::checks_total;
static constexpr char const * at_(std::size_t const &i, as_failed) {
return showln[failed[i]];
}
static constexpr char const * at_(std::size_t const &i, as_passed) {
return showln[passed[i]];
}
static constexpr char const * at_(std::size_t const &i, as_showln) {
return showln[i];
}
static constexpr std::size_t const * begin_(as_output) {
return &output[0];
}
static constexpr std::size_t const * begin_(as_result) {
return &result[0];
}
static constexpr std::size_t const * begin_(as_expect) {
return &expect[0];
}
static constexpr std::size_t const * begin_(as_failed) {
return &failed[0];
}
static constexpr std::size_t const * begin_(as_passed) {
return &passed[0];
}
static constexpr std::size_t const * begin_(as_showln) {
return &shnoop[0];
}
static constexpr std::size_t const * end_(as_output) {
return &output[checks_total];
}
static constexpr std::size_t const * end_(as_result) {
return &result[checks_total];
}
static constexpr std::size_t const * end_(as_expect) {
return &expect[checks_total];
}
static constexpr std::size_t const * end_(as_failed) {
return &failed[failed_total];
}
static constexpr std::size_t const * end_(as_passed) {
return &passed[passed_total];
}
static constexpr std::size_t const * end_(as_showln) {
return &shnoop[checks_total];
}
public:
template<typename Input_T = as_showln>
static constexpr auto at(std::size_t const & i)
-> decltype(at_(i, Input_T()))
{ return at_(i, Input_T()); }
template<typename Input_T = as_showln>
static constexpr auto begin()
-> decltype(begin_(Input_T()))
{ return begin_(Input_T()); }
template<typename Input_T = as_showln>
static constexpr auto end()
-> decltype(begin_(Input_T()))
{ return end_(Input_T()); }
template<typename Input_T = as_showln>
auto operator[](std::size_t const &i) const
-> decltype(at_(i, Input_T()))
{ return at_(i, Input_T()); }
static bool println(std::size_t const &i) {
size_t sz(strlen(showln[i]))
, cz(sz < AMPLE_PRINTLN_LIM ? sz : AMPLE_PRINTLN_LIM);
char cbuf[AMPLE_PRINTLN_LIM + 1];
std::copy_n(showln[i], cz, cbuf);
cbuf[cz] = (char)0;
ample_printf_(i, cz, AMPLE_PRINTLN_LIM);
return result[i];
}
static void println_head(char const *s) {
#ifdef USE_ANSI_COLORS
printf("\n\033[1;37m* %s\033[0m\n", s);
#else
printf("\n* %s\n", s);
#endif
}
static void println_foot(char const *s) {
#ifdef USE_ANSI_COLORS
printf("\033[1;37m* %s\033[0m\n", s);
#else
printf("* %s\n", s);
#endif
}
static void deploy(char const *s = nullptr) {
println_head(!s ? "all of the following are supposed be a PASS." : s);
std::for_each(begin(), end(), println);
println_foot("test block completed.");
}
};
} /* test */
} /* ample */
} /* odreex */
#undef ample_printf_ /* remove this macro */
#endif /* _ODREEX_AMPLE_TEST_HH_ */
<commit_msg>Making sure no zero length arrays are used in tests.<commit_after>/* --
* Copyright (C) 2013, George Makrydakis <irrequietus@gmail.com>
*
* This file is part of odreex.
*
* odreex 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 3 of the License, or (at your option) any later
* version.
*
* odreex 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
* odreex. If not, see http://www.gnu.org/licenses/.
*
*/
#ifndef _ODREEX_AMPLE_TEST_HH_
#define _ODREEX_AMPLE_TEST_HH_
#define ample_vldt_(t) \
static constexpr char const * showln() noexcept \
{ return t ; }
# ifdef AMPLE_PRINTLN_LIM
# if AMPLE_PRINTLN_LIM > 255
# define AMPLE_PRINTLN_LIM 52
# endif
# else
# define AMPLE_PRINTLN_LIM 52
# endif
#ifdef USE_ANSI_COLORS
#define ample_printf_(i, sz, N) \
printf( "\033[1;37m[%06llu]\033[0m: %s | %s |: \033[34m%s%s\033[0m\n" \
, static_cast<unsigned long long>(i) \
, result[ i ] ? "\033[36mpass\033[0m" : "\033[31mfail\033[0m" \
, output[ i ] ? "\033[1;36mpass\033[0m" : "\033[1;31mfail\033[0m" \
, cbuf \
, sz < N ? "" : "..." )
#else
#define ample_printf_(i, sz, N) \
printf( "[%06llu]: %s | %s |: %s%s\n" \
, static_cast<unsigned long long>(i) \
, result[ i ] ? "pass" : "fail" \
, output[ i ] ? "pass" : "fail" \
, cbuf \
, sz < N ? "" : "..." )
#endif
/**
* NOTE: Testing mechanism fundamentals for the various odreex::ample template
* metaprogramming constructs.
**/
#include <cstdio>
#include <cstring>
#include <type_traits>
#include <algorithm>
namespace odreex {
namespace ample {
namespace test {
struct as_passed {};
struct as_failed {};
struct as_output {};
struct as_expect {};
struct as_result {};
struct as_showln {};
/* class template for types that must be "matched" */
template<typename Type_X, typename Type_Y>
struct types_match
: std::integral_constant<bool, std::is_same<Type_X, Type_Y>::value >
{};
/* class template for values in types that must be "matched" */
template<typename Type_X, typename Type_Y>
struct values_match
: std::integral_constant<bool, Type_X::value == Type_Y::value>
{};
/* the default test class templates providing details */
template<typename Type_A, typename Type_B, bool Expected_B = true>
struct vldt_types : types_match<Type_A, Type_B> {
static constexpr bool expected() {
return Expected_B;
}
static constexpr bool result() {
return types_match<Type_A, Type_B>::value;
}
static constexpr bool output() {
return types_match<Type_A, Type_B>::value == Expected_B;
}
static constexpr char const * showln() {
return "default odreex::ample::test validation showln";
}
};
template<typename Type_A, typename Type_B, bool Expected_B = true>
struct vldt_values : values_match<Type_A, Type_B> {
static constexpr bool expected() {
return Expected_B;
}
static constexpr bool result() {
return values_match<Type_A, Type_B>::value;
}
static constexpr bool output() {
return values_match<Type_A, Type_B>::value == Expected_B;
}
static constexpr char const * showln() {
return "default odreex::ample::test validation showln";
}
};
/*NOTE: a wrapper class that is a temporary utility */
template<std::size_t... N>
struct wrap_
{};
constexpr std::size_t nozero_array(std::size_t n) {
return n == 0 ? 1 : n;
}
/* NOTE: constexpr arrays seem to be having some issues with clang++ (3.3.x) so
* we will be using the "old" way of doing things until this thing gets fixed.
* Notice that g++ has no problem with either style.
*/
template<typename... T>
struct check_all {
template<typename, typename, typename, typename, std::size_t, bool Casc_B>
struct check_impl;
template< typename X
, typename... Xn
, std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Casc_B >
struct check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<X, Xn...>
, N
, Casc_B >
: std::conditional< X::output() == Casc_B
, check_impl< wrap_<A..., N>
, wrap_<B...>
, wrap_<C..., N>
, check_all<Xn...>
, N + 1
, Casc_B >
, check_impl< wrap_<A...>
, wrap_<B..., N>
, wrap_<C..., N>
, check_all<Xn...>
, N + 1
, Casc_B >>::type
{};
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Casc_B >
struct check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Casc_B > {
static std::size_t const passed_total = sizeof...(A);
static std::size_t const failed_total = sizeof...(B);
static std::size_t const checks_total = sizeof...(T);
static std::size_t const passed[nozero_array(sizeof...(A))];
static std::size_t const failed[nozero_array(sizeof...(B))];
static std::size_t const shnoop[nozero_array(sizeof...(C))];
static char const * showln[nozero_array(sizeof...(T))];
static bool const output[nozero_array(sizeof...(T))];
static bool const result[nozero_array(sizeof...(T))];
static bool const expect[nozero_array(sizeof...(T))];
};
public:
template<bool B>
using apply = check_impl<wrap_<>, wrap_<>, wrap_<>, check_all<T...>, 0, B>;
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
std::size_t const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::passed[] = {
A...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
std::size_t const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::failed[] = {
B...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
bool const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::result[] = {
T::result()...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
bool const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::output[] = {
T::output()...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
bool const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::expect[] = {
T::expected()...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
char const * check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::showln[] = {
T::showln()...
};
template<typename... T>
template< std::size_t... A
, std::size_t... B
, std::size_t... C
, std::size_t N
, bool Cb >
std::size_t const check_all<T...>
::check_impl< wrap_<A...>
, wrap_<B...>
, wrap_<C...>
, check_all<>
, N
, Cb >::shnoop[] = {
C...
};
template<bool Cascade_B, typename Check_T>
struct check : private Check_T::template apply<Cascade_B> {
private:
using Check_T::template apply<Cascade_B>::passed;
using Check_T::template apply<Cascade_B>::failed;
using Check_T::template apply<Cascade_B>::output;
using Check_T::template apply<Cascade_B>::result;
using Check_T::template apply<Cascade_B>::expect;
using Check_T::template apply<Cascade_B>::showln;
using Check_T::template apply<Cascade_B>::shnoop;
using Check_T::template apply<Cascade_B>::passed_total;
using Check_T::template apply<Cascade_B>::failed_total;
using Check_T::template apply<Cascade_B>::checks_total;
static constexpr char const * at_(std::size_t const &i, as_failed) {
return showln[failed[i]];
}
static constexpr char const * at_(std::size_t const &i, as_passed) {
return showln[passed[i]];
}
static constexpr char const * at_(std::size_t const &i, as_showln) {
return showln[i];
}
static constexpr std::size_t const * begin_(as_output) {
return &output[0];
}
static constexpr std::size_t const * begin_(as_result) {
return &result[0];
}
static constexpr std::size_t const * begin_(as_expect) {
return &expect[0];
}
static constexpr std::size_t const * begin_(as_failed) {
return &failed[0];
}
static constexpr std::size_t const * begin_(as_passed) {
return &passed[0];
}
static constexpr std::size_t const * begin_(as_showln) {
return &shnoop[0];
}
static constexpr std::size_t const * end_(as_output) {
return &output[checks_total];
}
static constexpr std::size_t const * end_(as_result) {
return &result[checks_total];
}
static constexpr std::size_t const * end_(as_expect) {
return &expect[checks_total];
}
static constexpr std::size_t const * end_(as_failed) {
return &failed[failed_total];
}
static constexpr std::size_t const * end_(as_passed) {
return &passed[passed_total];
}
static constexpr std::size_t const * end_(as_showln) {
return &shnoop[checks_total];
}
public:
template<typename Input_T = as_showln>
static constexpr auto at(std::size_t const & i)
-> decltype(at_(i, Input_T()))
{ return at_(i, Input_T()); }
template<typename Input_T = as_showln>
static constexpr auto begin()
-> decltype(begin_(Input_T()))
{ return begin_(Input_T()); }
template<typename Input_T = as_showln>
static constexpr auto end()
-> decltype(begin_(Input_T()))
{ return end_(Input_T()); }
template<typename Input_T = as_showln>
auto operator[](std::size_t const &i) const
-> decltype(at_(i, Input_T()))
{ return at_(i, Input_T()); }
static bool println(std::size_t const &i) {
size_t sz(strlen(showln[i]))
, cz(sz < AMPLE_PRINTLN_LIM ? sz : AMPLE_PRINTLN_LIM);
char cbuf[AMPLE_PRINTLN_LIM + 1];
std::copy_n(showln[i], cz, cbuf);
cbuf[cz] = (char)0;
ample_printf_(i, cz, AMPLE_PRINTLN_LIM);
return result[i];
}
static void println_head(char const *s) {
#ifdef USE_ANSI_COLORS
printf("\n\033[1;37m* %s\033[0m\n", s);
#else
printf("\n* %s\n", s);
#endif
}
static void println_foot(char const *s) {
#ifdef USE_ANSI_COLORS
printf("\033[1;37m* %s\033[0m\n", s);
#else
printf("* %s\n", s);
#endif
}
static void deploy(char const *s = nullptr) {
println_head(!s ? "all of the following are supposed be a PASS." : s);
std::for_each(begin(), end(), println);
println_foot("test block completed.");
}
};
} /* test */
} /* ample */
} /* odreex */
#undef ample_printf_ /* remove this macro */
#endif /* _ODREEX_AMPLE_TEST_HH_ */
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* 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.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_PATTERN_ALIGNMENT_HPP
#define MAPNIK_PATTERN_ALIGNMENT_HPP
#include <mapnik/coord.hpp>
namespace mapnik {
class symbolizer_base;
class feature_impl;
class proj_transform;
class renderer_common;
coord<double, 2> pattern_offset(
symbolizer_base const & sym,
feature_impl const & feature,
proj_transform const & prj_trans,
renderer_common const & common,
unsigned pattern_width,
unsigned pattern_height);
}
#endif // MAPNIK_PATTERN_ALIGNMENT_HPP
<commit_msg>fix compiler warnings e.g warning: class 'xxx' was previously declared as a struct [-Wmismatched-tags]<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2017 Artem Pavlenko
*
* 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.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_PATTERN_ALIGNMENT_HPP
#define MAPNIK_PATTERN_ALIGNMENT_HPP
#include <mapnik/coord.hpp>
namespace mapnik {
struct symbolizer_base;
class feature_impl;
class proj_transform;
struct renderer_common;
coord<double, 2> pattern_offset(
symbolizer_base const & sym,
feature_impl const & feature,
proj_transform const & prj_trans,
renderer_common const & common,
unsigned pattern_width,
unsigned pattern_height);
}
#endif // MAPNIK_PATTERN_ALIGNMENT_HPP
<|endoftext|>
|
<commit_before>/**
* @file naive_method.hpp
* @author Ajinkya Kale
*
* Use the naive method to construct the kernel matrix.
*/
#ifndef __MLPACK_METHODS_KERNEL_PCA_NAIVE_METHOD_HPP
#define __MLPACK_METHODS_KERNEL_PCA_NAIVE_METHOD_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace kpca {
template<typename KernelType>
class NaiveKernelRule
{
public:
/**
* Construct the kernel matrix approximation using the all pairs method.
*
* @param data Input data points.
* @param transformedData Matrix to output results into.
* @param eigval KPCA eigenvalues will be written to this vector.
* @param eigvec KPCA eigenvectors will be written to this matrix.
* @param rank Rank to be used for matrix approximation.
* @param kernel Kernel to be used for computation.
*/
static void ApplyKernelMatrix(const arma::mat& data,
arma::mat& transformedData,
arma::vec& eigval,
arma::mat& eigvec,
const size_t /* unused */,
KernelType kernel = KernelType())
{
// Construct the kernel matrix.
arma::mat kernelMatrix;
// Resize the kernel matrix to the right size.
kernelMatrix.set_size(data.n_cols, data.n_cols);
// Note that we only need to calculate the upper triangular part of the
// kernel matrix, since it is symmetric. This helps minimize the number of
// kernel evaluations.
for (size_t i = 0; i < data.n_cols; ++i)
{
for (size_t j = i; j < data.n_cols; ++j)
{
// Evaluate the kernel on these two points.
kernelMatrix(i, j) = kernel.Evaluate(data.unsafe_col(i),
data.unsafe_col(j));
}
}
// Copy to the lower triangular part of the matrix.
for (size_t i = 1; i < data.n_cols; ++i)
for (size_t j = 0; j < i; ++j)
kernelMatrix(i, j) = kernelMatrix(j, i);
// For PCA the data has to be centered, even if the data is centered. But it
// is not guaranteed that the data, when mapped to the kernel space, is also
// centered. Since we actually never work in the feature space we cannot
// center the data. So, we perform a "psuedo-centering" using the kernel
// matrix.
arma::rowvec rowMean = arma::sum(kernelMatrix, 0) / kernelMatrix.n_cols;
kernelMatrix.each_col() -= arma::sum(kernelMatrix, 1) / kernelMatrix.n_cols;
kernelMatrix.each_row() -= rowMean;
kernelMatrix += arma::sum(rowMean) / kernelMatrix.n_cols;
// Eigendecompose the centered kernel matrix.
arma::eig_sym(eigval, eigvec, kernelMatrix);
// Swap the eigenvalues since they are ordered backwards (we need largest to
// smallest).
for (size_t i = 0; i < floor(eigval.n_elem / 2.0); ++i)
eigval.swap_rows(i, (eigval.n_elem - 1) - i);
// Flip the coefficients to produce the same effect.
eigvec = arma::fliplr(eigvec);
transformedData = eigvec.t() * kernelMatrix;
transformedData.each_col() /= arma::sqrt(eigval);
}
};
}; // namespace kpca
}; // namespace mlpack
#endif
<commit_msg>Update naive_method.hpp<commit_after>/**
* @file naive_method.hpp
* @author Ajinkya Kale
*
* Use the naive method to construct the kernel matrix.
*/
#ifndef __MLPACK_METHODS_KERNEL_PCA_NAIVE_METHOD_HPP
#define __MLPACK_METHODS_KERNEL_PCA_NAIVE_METHOD_HPP
#include <mlpack/core.hpp>
namespace mlpack {
namespace kpca {
template<typename KernelType>
class NaiveKernelRule
{
public:
/**
* Construct the exact kernel matrix.
*
* @param data Input data points.
* @param transformedData Matrix to output results into.
* @param eigval KPCA eigenvalues will be written to this vector.
* @param eigvec KPCA eigenvectors will be written to this matrix.
* @param rank Rank to be used for matrix approximation.
* @param kernel Kernel to be used for computation.
*/
static void ApplyKernelMatrix(const arma::mat& data,
arma::mat& transformedData,
arma::vec& eigval,
arma::mat& eigvec,
const size_t /* unused */,
KernelType kernel = KernelType())
{
// Construct the kernel matrix.
arma::mat kernelMatrix;
// Resize the kernel matrix to the right size.
kernelMatrix.set_size(data.n_cols, data.n_cols);
// Note that we only need to calculate the upper triangular part of the
// kernel matrix, since it is symmetric. This helps minimize the number of
// kernel evaluations.
for (size_t i = 0; i < data.n_cols; ++i)
{
for (size_t j = i; j < data.n_cols; ++j)
{
// Evaluate the kernel on these two points.
kernelMatrix(i, j) = kernel.Evaluate(data.unsafe_col(i),
data.unsafe_col(j));
}
}
// Copy to the lower triangular part of the matrix.
for (size_t i = 1; i < data.n_cols; ++i)
for (size_t j = 0; j < i; ++j)
kernelMatrix(i, j) = kernelMatrix(j, i);
// For PCA the data has to be centered, even if the data is centered. But it
// is not guaranteed that the data, when mapped to the kernel space, is also
// centered. Since we actually never work in the feature space we cannot
// center the data. So, we perform a "psuedo-centering" using the kernel
// matrix.
arma::rowvec rowMean = arma::sum(kernelMatrix, 0) / kernelMatrix.n_cols;
kernelMatrix.each_col() -= arma::sum(kernelMatrix, 1) / kernelMatrix.n_cols;
kernelMatrix.each_row() -= rowMean;
kernelMatrix += arma::sum(rowMean) / kernelMatrix.n_cols;
// Eigendecompose the centered kernel matrix.
arma::eig_sym(eigval, eigvec, kernelMatrix);
// Swap the eigenvalues since they are ordered backwards (we need largest to
// smallest).
for (size_t i = 0; i < floor(eigval.n_elem / 2.0); ++i)
eigval.swap_rows(i, (eigval.n_elem - 1) - i);
// Flip the coefficients to produce the same effect.
eigvec = arma::fliplr(eigvec);
transformedData = eigvec.t() * kernelMatrix;
transformedData.each_col() /= arma::sqrt(eigval);
}
};
}; // namespace kpca
}; // namespace mlpack
#endif
<|endoftext|>
|
<commit_before>/**
* @file llwidgetreg.cpp
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2002-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llwidgetreg.h"
#include "llbutton.h"
#include "llcheckboxctrl.h"
#include "llcombobox.h"
#include "llcontainerview.h"
#include "lliconctrl.h"
#include "llmenubutton.h"
#include "llmenugl.h"
#include "llmultislider.h"
#include "llmultisliderctrl.h"
#include "llprogressbar.h"
#include "llradiogroup.h"
#include "llsearcheditor.h"
#include "llscrollcontainer.h"
#include "llscrollingpanellist.h"
#include "llscrolllistctrl.h"
#include "llslider.h"
#include "llsliderctrl.h"
#include "llspinctrl.h"
#include "llstatview.h"
#include "lltabcontainer.h"
#include "lltextbox.h"
#include "lltexteditor.h"
#include "llflyoutbutton.h"
#include "llfiltereditor.h"
#include "lllayoutstack.h"
void LLWidgetReg::initClass(bool register_widgets)
{
// Only need to register if the Windows linker has optimized away the
// references to the object files.
if (register_widgets)
{
LLDefaultChildRegistry::Register<LLButton> button("button");
LLDefaultChildRegistry::Register<LLMenuButton> menu_button("menu_button");
LLDefaultChildRegistry::Register<LLCheckBoxCtrl> check_box("check_box");
LLDefaultChildRegistry::Register<LLComboBox> combo_box("combo_box");
LLDefaultChildRegistry::Register<LLFilterEditor> filter_editor("filter_editor");
LLDefaultChildRegistry::Register<LLFlyoutButton> flyout_button("flyout_button");
LLDefaultChildRegistry::Register<LLContainerView> container_view("container_view");
LLDefaultChildRegistry::Register<LLIconCtrl> icon("icon");
LLDefaultChildRegistry::Register<LLLineEditor> line_editor("line_editor");
LLDefaultChildRegistry::Register<LLMenuItemSeparatorGL> menu_item_separator("menu_item_separator");
LLDefaultChildRegistry::Register<LLMenuItemCallGL> menu_item_call_gl("menu_item_call");
LLDefaultChildRegistry::Register<LLMenuItemCheckGL> menu_item_check_gl("menu_item_check");
LLDefaultChildRegistry::Register<LLMenuGL> menu("menu");
LLDefaultChildRegistry::Register<LLMenuBarGL> menu_bar("menu_bar");
LLDefaultChildRegistry::Register<LLContextMenu> context_menu("context_menu");
LLDefaultChildRegistry::Register<LLMultiSlider> multi_slider_bar("multi_slider_bar");
LLDefaultChildRegistry::Register<LLMultiSliderCtrl> multi_slider("multi_slider");
LLDefaultChildRegistry::Register<LLPanel> panel("panel", &LLPanel::fromXML);
LLDefaultChildRegistry::Register<LLLayoutStack> layout_stack("layout_stack", &LLLayoutStack::fromXML);
LLDefaultChildRegistry::Register<LLProgressBar> progress_bar("progress_bar");
LLDefaultChildRegistry::Register<LLRadioGroup> radio_group("radio_group");
LLDefaultChildRegistry::Register<LLRadioCtrl> radio_item("radio_item");
LLDefaultChildRegistry::Register<LLSearchEditor> search_editor("search_editor");
LLDefaultChildRegistry::Register<LLScrollContainer> scroll_container("scroll_container");
LLDefaultChildRegistry::Register<LLScrollingPanelList> scrolling_panel_list("scrolling_panel_list");
LLDefaultChildRegistry::Register<LLScrollListCtrl> scroll_list("scroll_list");
LLDefaultChildRegistry::Register<LLSlider> slider_bar("slider_bar");
LLDefaultChildRegistry::Register<LLSliderCtrl> slider("slider");
LLDefaultChildRegistry::Register<LLSpinCtrl> spinner("spinner");
LLDefaultChildRegistry::Register<LLStatBar> stat_bar("stat_bar");
//LLDefaultChildRegistry::Register<LLPlaceHolderPanel> placeholder("placeholder");
LLDefaultChildRegistry::Register<LLTabContainer> tab_container("tab_container");
LLDefaultChildRegistry::Register<LLTextBox> text("text");
LLDefaultChildRegistry::Register<LLTextEditor> simple_text_editor("simple_text_editor");
LLDefaultChildRegistry::Register<LLUICtrl> ui_ctrl("ui_ctrl");
LLDefaultChildRegistry::Register<LLStatView> stat_view("stat_view");
//LLDefaultChildRegistry::Register<LLUICtrlLocate> locate("locate");
//LLDefaultChildRegistry::Register<LLUICtrlLocate> pad("pad");
LLDefaultChildRegistry::Register<LLViewBorder> view_border("view_border");
}
// *HACK: Usually this is registered as a viewer text editor
LLDefaultChildRegistry::Register<LLTextEditor> text_editor("text_editor");
}
<commit_msg>fix for llui unit test<commit_after>/**
* @file llwidgetreg.cpp
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2002-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llwidgetreg.h"
#include "llbutton.h"
#include "llcheckboxctrl.h"
#include "llcombobox.h"
#include "llcontainerview.h"
#include "lliconctrl.h"
#include "llmenubutton.h"
#include "llmenugl.h"
#include "llmultislider.h"
#include "llmultisliderctrl.h"
#include "llprogressbar.h"
#include "llradiogroup.h"
#include "llsearcheditor.h"
#include "llscrollcontainer.h"
#include "llscrollingpanellist.h"
#include "llscrolllistctrl.h"
#include "llslider.h"
#include "llsliderctrl.h"
#include "llspinctrl.h"
#include "llstatview.h"
#include "lltabcontainer.h"
#include "lltextbox.h"
#include "lltexteditor.h"
#include "llflyoutbutton.h"
#include "llfiltereditor.h"
#include "lllayoutstack.h"
void LLWidgetReg::initClass(bool register_widgets)
{
// Only need to register if the Windows linker has optimized away the
// references to the object files.
if (register_widgets)
{
LLDefaultChildRegistry::Register<LLButton> button("button");
LLDefaultChildRegistry::Register<LLMenuButton> menu_button("menu_button");
LLDefaultChildRegistry::Register<LLCheckBoxCtrl> check_box("check_box");
LLDefaultChildRegistry::Register<LLComboBox> combo_box("combo_box");
LLDefaultChildRegistry::Register<LLFilterEditor> filter_editor("filter_editor");
LLDefaultChildRegistry::Register<LLFlyoutButton> flyout_button("flyout_button");
LLDefaultChildRegistry::Register<LLContainerView> container_view("container_view");
LLDefaultChildRegistry::Register<LLIconCtrl> icon("icon");
LLDefaultChildRegistry::Register<LLLineEditor> line_editor("line_editor");
LLDefaultChildRegistry::Register<LLMenuItemSeparatorGL> menu_item_separator("menu_item_separator");
LLDefaultChildRegistry::Register<LLMenuItemCallGL> menu_item_call_gl("menu_item_call");
LLDefaultChildRegistry::Register<LLMenuItemCheckGL> menu_item_check_gl("menu_item_check");
LLDefaultChildRegistry::Register<LLMenuGL> menu("menu");
LLDefaultChildRegistry::Register<LLMenuBarGL> menu_bar("menu_bar");
LLDefaultChildRegistry::Register<LLContextMenu> context_menu("context_menu");
LLDefaultChildRegistry::Register<LLMultiSlider> multi_slider_bar("multi_slider_bar");
LLDefaultChildRegistry::Register<LLMultiSliderCtrl> multi_slider("multi_slider");
LLDefaultChildRegistry::Register<LLPanel> panel("panel", &LLPanel::fromXML);
LLDefaultChildRegistry::Register<LLLayoutStack> layout_stack("layout_stack", &LLLayoutStack::fromXML);
LLDefaultChildRegistry::Register<LLProgressBar> progress_bar("progress_bar");
LLDefaultChildRegistry::Register<LLRadioGroup> radio_group("radio_group");
LLDefaultChildRegistry::Register<LLSearchEditor> search_editor("search_editor");
LLDefaultChildRegistry::Register<LLScrollContainer> scroll_container("scroll_container");
LLDefaultChildRegistry::Register<LLScrollingPanelList> scrolling_panel_list("scrolling_panel_list");
LLDefaultChildRegistry::Register<LLScrollListCtrl> scroll_list("scroll_list");
LLDefaultChildRegistry::Register<LLSlider> slider_bar("slider_bar");
LLDefaultChildRegistry::Register<LLSliderCtrl> slider("slider");
LLDefaultChildRegistry::Register<LLSpinCtrl> spinner("spinner");
LLDefaultChildRegistry::Register<LLStatBar> stat_bar("stat_bar");
//LLDefaultChildRegistry::Register<LLPlaceHolderPanel> placeholder("placeholder");
LLDefaultChildRegistry::Register<LLTabContainer> tab_container("tab_container");
LLDefaultChildRegistry::Register<LLTextBox> text("text");
LLDefaultChildRegistry::Register<LLTextEditor> simple_text_editor("simple_text_editor");
LLDefaultChildRegistry::Register<LLUICtrl> ui_ctrl("ui_ctrl");
LLDefaultChildRegistry::Register<LLStatView> stat_view("stat_view");
//LLDefaultChildRegistry::Register<LLUICtrlLocate> locate("locate");
//LLDefaultChildRegistry::Register<LLUICtrlLocate> pad("pad");
LLDefaultChildRegistry::Register<LLViewBorder> view_border("view_border");
}
// *HACK: Usually this is registered as a viewer text editor
LLDefaultChildRegistry::Register<LLTextEditor> text_editor("text_editor");
}
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkImageClassifierFilter.h"
#include "itkFixedArray.h"
#include "itkGaussianMembershipFunction.h"
#include "itkMaximumDecisionRule2.h"
#include "itkImageToListSampleAdaptor.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkLabelToRGBImageFilter.h"
int main(int argc, char * argv [] )
{
if( argc < 5 )
{
std::cerr << "Missing command line arguments: ";
std::cerr << argv[0] << "\t" << "InputImage ClassifiedOutputImage ColorEncodedClassifiedImage inputMembership1 inputMembership2 ..." << std::endl;
return EXIT_FAILURE;
}
const unsigned int MeasurementVectorSize = 3;
const unsigned int NumberOfComponents = MeasurementVectorSize;
typedef unsigned char MeasurementComponentType;
const unsigned int numberOfArgumentsBeforeMemberships = 4;
const unsigned int numberOfClasses = argc - numberOfArgumentsBeforeMemberships;
typedef itk::FixedArray< MeasurementComponentType, MeasurementVectorSize > InputPixelType;
typedef InputPixelType MeasurementVectorType;
const unsigned int ImageDimension = 2;
typedef itk::Image< InputPixelType, ImageDimension > InputImageType;
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
try
{
reader->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
InputImageType::ConstPointer image = reader->GetOutput();
typedef itk::Statistics::ImageToListSampleAdaptor< InputImageType > ImageToListSampleAdaptorType;
ImageToListSampleAdaptorType::Pointer sample = ImageToListSampleAdaptorType::New();
sample->SetImage( image );
typedef itk::Statistics::ImageClassifierFilter<
ImageToListSampleAdaptorType, InputImageType, OutputImageType > ImageClassifierFilterType;
ImageClassifierFilterType::Pointer filter = ImageClassifierFilterType::New();
typedef ImageClassifierFilterType::ClassLabelVectorObjectType ClassLabelVectorObjectType;
typedef ImageClassifierFilterType::ClassLabelVectorType ClassLabelVectorType;
ClassLabelVectorObjectType::Pointer classLabelsObject = ClassLabelVectorObjectType::New();
ClassLabelVectorType classLabelVector = classLabelsObject->Get();
typedef ImageClassifierFilterType::MembershipFunctionVectorObjectType MembershipFunctionVectorObjectType;
MembershipFunctionVectorObjectType::Pointer membershipFunctionsObject = MembershipFunctionVectorObjectType::New();
typedef ImageClassifierFilterType::MembershipFunctionVectorType MembershipFunctionVectorType;
MembershipFunctionVectorType membershipFunctions;
typedef itk::Statistics::GaussianMembershipFunction< MeasurementVectorType > GaussianMembershipFunctionType;
typedef GaussianMembershipFunctionType::MeanType MeanVectorType;
typedef GaussianMembershipFunctionType::CovarianceType CovarianceMatrixType;
for( unsigned int j = 0; j < numberOfClasses; j++ )
{
classLabelVector.push_back( 100 + j * 50 );
GaussianMembershipFunctionType::Pointer membershipFunction = GaussianMembershipFunctionType::New();
MeanVectorType mean(NumberOfComponents);
CovarianceMatrixType covariance(NumberOfComponents,NumberOfComponents);
std::ifstream inputMembership;
const unsigned int numberOfArgument = j + numberOfArgumentsBeforeMemberships;
inputMembership.open( argv[numberOfArgument] );
for( unsigned int i = 0; i < NumberOfComponents; i++ )
{
inputMembership >> mean[i];
}
for( unsigned int i = 0; i < NumberOfComponents; i++ )
{
for( unsigned int j = 0; j < NumberOfComponents; j++ )
{
inputMembership >> covariance(i,j);
}
}
inputMembership.close();
std::cout << "Mean vector = " << std::endl;
std::cout << mean << std::endl;
std::cout << "Covariance matrix = " << std::endl;
std::cout << covariance << std::endl;
membershipFunction->SetMean( mean );
membershipFunction->SetCovariance( covariance );
membershipFunctions.push_back( membershipFunction.GetPointer() );
}
classLabelsObject->Set( classLabelVector );
membershipFunctionsObject->Set( membershipFunctions );
typedef ImageClassifierFilterType::MembershipFunctionsWeightsArrayObjectType MembershipFunctionsWeightsArrayObjectType;
MembershipFunctionsWeightsArrayObjectType::Pointer weightArrayObjects = MembershipFunctionsWeightsArrayObjectType::New();
ImageClassifierFilterType::MembershipFunctionsWeightsArrayType weightsArray(numberOfClasses);
weightsArray[0] = 0.20; // Lumen
weightsArray[1] = 0.25; // Germ cells
weightsArray[2] = 0.20; // Epithelium
weightsArray[3] = 0.30; // Mature cells
weightsArray[4] = 0.05; // External epithelium
weightArrayObjects->Set( weightsArray );
filter->SetImage( image );
filter->SetNumberOfClasses( numberOfClasses );
filter->SetClassLabels( classLabelsObject );
filter->SetMembershipFunctions( membershipFunctionsObject );
filter->SetMembershipFunctionsWeightsArray( weightArrayObjects );
typedef itk::Statistics::MaximumDecisionRule2 DecisionRuleType;
DecisionRuleType::Pointer decisionRule = DecisionRuleType::New();
filter->SetDecisionRule( decisionRule );
try
{
filter->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
typedef itk::ImageFileWriter< OutputImageType > OutputImageWriterType;
OutputImageWriterType::Pointer outputImageWriter = OutputImageWriterType::New();
outputImageWriter->SetFileName( argv[2] );
outputImageWriter->SetInput( filter->GetOutput() );
try
{
outputImageWriter->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
//
// Instantiate the filter that will encode the label image
// into a color image (random color attribution).
//
typedef itk::RGBPixel<unsigned char> RGBPixelType;
typedef itk::Image< RGBPixelType, ImageDimension > RGBImageType;
typedef itk::ImageFileWriter< RGBImageType > RGBWriterType;
RGBWriterType::Pointer colorWriter = RGBWriterType::New();
typedef itk::LabelToRGBImageFilter< OutputImageType, RGBImageType > ColorMapFilterType;
ColorMapFilterType::Pointer colorMapFilter = ColorMapFilterType::New();
colorMapFilter->SetInput( filter->GetOutput() );
colorWriter->SetFileName( argv[3] );
colorWriter->SetInput( colorMapFilter->GetOutput() );
try
{
colorWriter->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << excep << std::endl;
}
return EXIT_SUCCESS;
}
<commit_msg>ENH: Better labels and color defaults.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkImageClassifierFilter.h"
#include "itkFixedArray.h"
#include "itkGaussianMembershipFunction.h"
#include "itkMaximumDecisionRule2.h"
#include "itkImageToListSampleAdaptor.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkLabelToRGBImageFilter.h"
int main(int argc, char * argv [] )
{
if( argc < 5 )
{
std::cerr << "Missing command line arguments: ";
std::cerr << argv[0] << "\t" << "InputImage ClassifiedOutputImage ColorEncodedClassifiedImage inputMembership1 inputMembership2 ..." << std::endl;
return EXIT_FAILURE;
}
const unsigned int MeasurementVectorSize = 3;
const unsigned int NumberOfComponents = MeasurementVectorSize;
typedef unsigned char MeasurementComponentType;
const unsigned int numberOfArgumentsBeforeMemberships = 4;
const unsigned int numberOfClasses = argc - numberOfArgumentsBeforeMemberships;
typedef itk::FixedArray< MeasurementComponentType, MeasurementVectorSize > InputPixelType;
typedef InputPixelType MeasurementVectorType;
const unsigned int ImageDimension = 2;
typedef itk::Image< InputPixelType, ImageDimension > InputImageType;
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
try
{
reader->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
InputImageType::ConstPointer image = reader->GetOutput();
typedef itk::Statistics::ImageToListSampleAdaptor< InputImageType > ImageToListSampleAdaptorType;
ImageToListSampleAdaptorType::Pointer sample = ImageToListSampleAdaptorType::New();
sample->SetImage( image );
typedef itk::Statistics::ImageClassifierFilter<
ImageToListSampleAdaptorType, InputImageType, OutputImageType > ImageClassifierFilterType;
ImageClassifierFilterType::Pointer filter = ImageClassifierFilterType::New();
typedef ImageClassifierFilterType::ClassLabelVectorObjectType ClassLabelVectorObjectType;
typedef ImageClassifierFilterType::ClassLabelVectorType ClassLabelVectorType;
ClassLabelVectorObjectType::Pointer classLabelsObject = ClassLabelVectorObjectType::New();
ClassLabelVectorType classLabelVector = classLabelsObject->Get();
typedef ImageClassifierFilterType::MembershipFunctionVectorObjectType MembershipFunctionVectorObjectType;
MembershipFunctionVectorObjectType::Pointer membershipFunctionsObject = MembershipFunctionVectorObjectType::New();
typedef ImageClassifierFilterType::MembershipFunctionVectorType MembershipFunctionVectorType;
MembershipFunctionVectorType membershipFunctions;
typedef itk::Statistics::GaussianMembershipFunction< MeasurementVectorType > GaussianMembershipFunctionType;
typedef GaussianMembershipFunctionType::MeanType MeanVectorType;
typedef GaussianMembershipFunctionType::CovarianceType CovarianceMatrixType;
for( unsigned int j = 0; j < numberOfClasses; j++ )
{
classLabelVector.push_back( j );
GaussianMembershipFunctionType::Pointer membershipFunction = GaussianMembershipFunctionType::New();
MeanVectorType mean(NumberOfComponents);
CovarianceMatrixType covariance(NumberOfComponents,NumberOfComponents);
std::ifstream inputMembership;
const unsigned int numberOfArgument = j + numberOfArgumentsBeforeMemberships;
inputMembership.open( argv[numberOfArgument] );
for( unsigned int i = 0; i < NumberOfComponents; i++ )
{
inputMembership >> mean[i];
}
for( unsigned int i = 0; i < NumberOfComponents; i++ )
{
for( unsigned int j = 0; j < NumberOfComponents; j++ )
{
inputMembership >> covariance(i,j);
}
}
inputMembership.close();
std::cout << "Mean vector = " << std::endl;
std::cout << mean << std::endl;
std::cout << "Covariance matrix = " << std::endl;
std::cout << covariance << std::endl;
membershipFunction->SetMean( mean );
membershipFunction->SetCovariance( covariance );
membershipFunctions.push_back( membershipFunction.GetPointer() );
}
classLabelsObject->Set( classLabelVector );
membershipFunctionsObject->Set( membershipFunctions );
typedef ImageClassifierFilterType::MembershipFunctionsWeightsArrayObjectType MembershipFunctionsWeightsArrayObjectType;
MembershipFunctionsWeightsArrayObjectType::Pointer weightArrayObjects = MembershipFunctionsWeightsArrayObjectType::New();
ImageClassifierFilterType::MembershipFunctionsWeightsArrayType weightsArray(numberOfClasses);
weightsArray[0] = 0.20; // Lumen
weightsArray[1] = 0.25; // Germ cells
weightsArray[2] = 0.20; // Epithelium
weightsArray[3] = 0.30; // Mature cells
weightsArray[4] = 0.05; // External epithelium
weightArrayObjects->Set( weightsArray );
filter->SetImage( image );
filter->SetNumberOfClasses( numberOfClasses );
filter->SetClassLabels( classLabelsObject );
filter->SetMembershipFunctions( membershipFunctionsObject );
filter->SetMembershipFunctionsWeightsArray( weightArrayObjects );
typedef itk::Statistics::MaximumDecisionRule2 DecisionRuleType;
DecisionRuleType::Pointer decisionRule = DecisionRuleType::New();
filter->SetDecisionRule( decisionRule );
try
{
filter->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
typedef itk::ImageFileWriter< OutputImageType > OutputImageWriterType;
OutputImageWriterType::Pointer outputImageWriter = OutputImageWriterType::New();
outputImageWriter->SetFileName( argv[2] );
outputImageWriter->SetInput( filter->GetOutput() );
try
{
outputImageWriter->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
//
// Instantiate the filter that will encode the label image
// into a color image (random color attribution).
//
typedef itk::RGBPixel<unsigned char> RGBPixelType;
typedef itk::Image< RGBPixelType, ImageDimension > RGBImageType;
typedef itk::ImageFileWriter< RGBImageType > RGBWriterType;
RGBWriterType::Pointer colorWriter = RGBWriterType::New();
typedef itk::LabelToRGBImageFilter< OutputImageType, RGBImageType > ColorMapFilterType;
ColorMapFilterType::Pointer colorMapFilter = ColorMapFilterType::New();
colorMapFilter->SetInput( filter->GetOutput() );
colorMapFilter->ResetColors();
colorMapFilter->AddColor( 255, 0, 0 );
colorMapFilter->AddColor( 0, 255, 0 );
colorMapFilter->AddColor( 0, 0, 255 );
colorMapFilter->AddColor( 255, 0, 255 );
colorMapFilter->AddColor( 0, 255, 255 );
colorMapFilter->AddColor( 255, 255, 0 );
colorWriter->SetFileName( argv[3] );
colorWriter->SetInput( colorMapFilter->GetOutput() );
try
{
colorWriter->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << excep << std::endl;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// RUN: %clang_cc1 -verify -std=c++11 -fms-extensions %s
8gi///===--- recovery.cpp ---===// // expected-error {{unqualified-id}}
namespace Std { // expected-note {{here}}
typedef int Important;
}
/ redeclare as an inline namespace // expected-error {{unqualified-id}}
inline namespace Std { // expected-error {{cannot be reopened as inline}}
Important n;
} / end namespace Std // expected-error {{unqualified-id}}
int x;
Std::Important y;
extenr "C" { // expected-error {{did you mean 'extern'}}
void f();
}
void g() {
z = 1; // expected-error {{undeclared}}
f();
}
struct S {
int a, b, c;
S();
int x // expected-error {{expected ';'}}
friend void f()
};
8S::S() : a{ 5 }, b{ 6 }, c{ 2 } { // expected-error {{unqualified-id}}
return;
}
int k;
int l = k // expected-error {{expected ';'}}
constexpr int foo();
5int m = { l }, n = m; // expected-error {{unqualified-id}}
namespace MissingBrace {
struct S { // expected-error {{missing '}' at end of definition of 'MissingBrace::S'}}
int f();
// };
namespace N { int g(); } // expected-note {{still within definition of 'MissingBrace::S' here}}
int k1 = S().h(); // expected-error {{no member named 'h' in 'MissingBrace::S'}}
int k2 = S().f() + N::g();
template<typename T> struct PR17949 { // expected-error {{missing '}' at end of definition of 'MissingBrace::PR17949'}}
namespace X { // expected-note {{still within definition of 'MissingBrace::PR17949' here}}
}
}
namespace N {
int
} // expected-error {{unqualified-id}}
strcut Uuuu { // expected-error {{did you mean 'struct'}} \
// expected-note {{'Uuuu' declared here}}
} *u[3];
uuuu v; // expected-error {{did you mean 'Uuuu'}}
struct Redefined { // expected-note {{previous}}
Redefined() {}
};
struct Redefined { // expected-error {{redefinition}}
Redefined() {}
};
struct MissingSemi5;
namespace N {
typedef int afterMissingSemi4;
extern MissingSemi5 afterMissingSemi5;
}
struct MissingSemi1 {} // expected-error {{expected ';' after struct}}
static int afterMissingSemi1();
class MissingSemi2 {} // expected-error {{expected ';' after class}}
MissingSemi1 *afterMissingSemi2;
enum MissingSemi3 {} // expected-error {{expected ';' after enum}}
::MissingSemi1 afterMissingSemi3;
extern N::afterMissingSemi4 afterMissingSemi4b;
union MissingSemi4 { MissingSemi4(int); } // expected-error {{expected ';' after union}}
N::afterMissingSemi4 (afterMissingSemi4b);
int afterMissingSemi5b;
struct MissingSemi5 { MissingSemi5(int); } // ok, no missing ';' here
N::afterMissingSemi5 (afterMissingSemi5b);
template<typename T> struct MissingSemiT {
} // expected-error {{expected ';' after struct}}
MissingSemiT<int> msi;
struct MissingSemiInStruct {
struct Inner1 {} // expected-error {{expected ';' after struct}}
static MissingSemi5 ms1;
struct Inner2 {} // ok, no missing ';' here
static MissingSemi1;
struct Inner3 {} // expected-error {{expected ';' after struct}}
static MissingSemi5 *p;
};
void MissingSemiInFunction() {
struct Inner1 {} // expected-error {{expected ';' after struct}}
if (true) {}
// FIXME: It would be nice to at least warn on this.
struct Inner2 { Inner2(int); } // ok, no missing ';' here
k = l;
struct Inner3 {} // expected-error {{expected ';' after struct}}
Inner1 i1;
struct Inner4 {} // ok, no missing ';' here
Inner5;
}
namespace NS {
template<typename T> struct Foo {};
}
struct MissingSemiThenTemplate1 {} // expected-error {{expected ';' after struct}}
NS::Foo<int> missingSemiBeforeFunctionReturningTemplateId1();
using NS::Foo;
struct MissingSemiThenTemplate2 {} // expected-error {{expected ';' after struct}}
Foo<int> missingSemiBeforeFunctionReturningTemplateId2();
namespace PR17084 {
enum class EnumID {};
template <typename> struct TempID;
template <> struct TempID<BadType> : BadType, EnumID::Garbage; // expected-error{{use of undeclared identifier 'BadType'}}
}
namespace pr15133 {
namespace ns {
const int V1 = 1; // expected-note {{declared here}}
}
struct C1 {
enum E1 { V2 = 2 }; // expected-note {{declared here}}
static const int V3 = 3; // expected-note {{declared here}}
};
enum E2 {
V4 = 4, // expected-note {{declared here}}
V6 // expected-note {{declared here}}
};
enum class EC3 { V0 = 0, V5 = 5 }; // expected-note {{declared here}}
void func_3();
void func_1(int x) {
switch(x) {
case 0: break;
case ns::V1:: break; // expected-error{{'V1' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
case C1::V2:: break; // expected-error{{'V2' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
case C1::V3:: break; // expected-error{{'V3' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
case V4:: break; // expected-error{{'V4' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
case V6:: func_3(); // expected-error{{'V6' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
}
void func_2(EC3 x) {
switch(x) {
case EC3::V0: break;
case EC3::V5:: break; // expected-error{{'V5' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
}
template<class T> struct TS1 {
typedef int A;
};
template<class T> void func(int x) {
switch(x) {
case TS1<T>::A:: break; // expected-error{{expected unqualified-id}}
}
};
void mainf() {
func<int>(1);
}
struct S {
static int n; // expected-note{{declared here}}
int nn; // expected-note 2 {{declared here}}
};
int func_3(int x) {
return x ? S::n :: 0; // expected-error{{'n' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
int func_4(int x, S &s) {
return x ? s.nn :: x; // expected-error{{'nn' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
int func_5(int x, S &s) {
return x ? s.nn :: S::n; // expected-error{{'nn' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
struct S2 {
struct S3;
};
struct S2 :: S3 :: public S2 { // expected-error{{'public' cannot be a part of nested name specifier; did you mean ':'?}}
};
}
namespace InvalidEmptyNames {
// These shouldn't crash, the diagnostics aren't important.
struct ::, struct ::; // expected-error 2 {{expected identifier}} expected-error 2 {{declaration of anonymous struct must be a definition}} expected-warning {{declaration does not declare anything}}
enum ::, enum ::; // expected-error 2 {{expected identifier}} expected-warning {{declaration does not declare anything}}
struct ::__super, struct ::__super; // expected-error 2 {{expected identifier}} expected-error 2 {{expected '::' after '__super'}}
struct ::template foo, struct ::template bar; // expected-error 2 {{expected identifier}} expected-error 2 {{declaration of anonymous struct must be a definition}} expected-warning {{declaration does not declare anything}}
}
<commit_msg>Add more tests for crashes that happend to be fixed by r229288.<commit_after>// RUN: %clang_cc1 -verify -std=c++11 -fms-extensions %s
8gi///===--- recovery.cpp ---===// // expected-error {{unqualified-id}}
namespace Std { // expected-note {{here}}
typedef int Important;
}
/ redeclare as an inline namespace // expected-error {{unqualified-id}}
inline namespace Std { // expected-error {{cannot be reopened as inline}}
Important n;
} / end namespace Std // expected-error {{unqualified-id}}
int x;
Std::Important y;
extenr "C" { // expected-error {{did you mean 'extern'}}
void f();
}
void g() {
z = 1; // expected-error {{undeclared}}
f();
}
struct S {
int a, b, c;
S();
int x // expected-error {{expected ';'}}
friend void f()
};
8S::S() : a{ 5 }, b{ 6 }, c{ 2 } { // expected-error {{unqualified-id}}
return;
}
int k;
int l = k // expected-error {{expected ';'}}
constexpr int foo();
5int m = { l }, n = m; // expected-error {{unqualified-id}}
namespace MissingBrace {
struct S { // expected-error {{missing '}' at end of definition of 'MissingBrace::S'}}
int f();
// };
namespace N { int g(); } // expected-note {{still within definition of 'MissingBrace::S' here}}
int k1 = S().h(); // expected-error {{no member named 'h' in 'MissingBrace::S'}}
int k2 = S().f() + N::g();
template<typename T> struct PR17949 { // expected-error {{missing '}' at end of definition of 'MissingBrace::PR17949'}}
namespace X { // expected-note {{still within definition of 'MissingBrace::PR17949' here}}
}
}
namespace N {
int
} // expected-error {{unqualified-id}}
strcut Uuuu { // expected-error {{did you mean 'struct'}} \
// expected-note {{'Uuuu' declared here}}
} *u[3];
uuuu v; // expected-error {{did you mean 'Uuuu'}}
struct Redefined { // expected-note {{previous}}
Redefined() {}
};
struct Redefined { // expected-error {{redefinition}}
Redefined() {}
};
struct MissingSemi5;
namespace N {
typedef int afterMissingSemi4;
extern MissingSemi5 afterMissingSemi5;
}
struct MissingSemi1 {} // expected-error {{expected ';' after struct}}
static int afterMissingSemi1();
class MissingSemi2 {} // expected-error {{expected ';' after class}}
MissingSemi1 *afterMissingSemi2;
enum MissingSemi3 {} // expected-error {{expected ';' after enum}}
::MissingSemi1 afterMissingSemi3;
extern N::afterMissingSemi4 afterMissingSemi4b;
union MissingSemi4 { MissingSemi4(int); } // expected-error {{expected ';' after union}}
N::afterMissingSemi4 (afterMissingSemi4b);
int afterMissingSemi5b;
struct MissingSemi5 { MissingSemi5(int); } // ok, no missing ';' here
N::afterMissingSemi5 (afterMissingSemi5b);
template<typename T> struct MissingSemiT {
} // expected-error {{expected ';' after struct}}
MissingSemiT<int> msi;
struct MissingSemiInStruct {
struct Inner1 {} // expected-error {{expected ';' after struct}}
static MissingSemi5 ms1;
struct Inner2 {} // ok, no missing ';' here
static MissingSemi1;
struct Inner3 {} // expected-error {{expected ';' after struct}}
static MissingSemi5 *p;
};
void MissingSemiInFunction() {
struct Inner1 {} // expected-error {{expected ';' after struct}}
if (true) {}
// FIXME: It would be nice to at least warn on this.
struct Inner2 { Inner2(int); } // ok, no missing ';' here
k = l;
struct Inner3 {} // expected-error {{expected ';' after struct}}
Inner1 i1;
struct Inner4 {} // ok, no missing ';' here
Inner5;
}
namespace NS {
template<typename T> struct Foo {};
}
struct MissingSemiThenTemplate1 {} // expected-error {{expected ';' after struct}}
NS::Foo<int> missingSemiBeforeFunctionReturningTemplateId1();
using NS::Foo;
struct MissingSemiThenTemplate2 {} // expected-error {{expected ';' after struct}}
Foo<int> missingSemiBeforeFunctionReturningTemplateId2();
namespace PR17084 {
enum class EnumID {};
template <typename> struct TempID;
template <> struct TempID<BadType> : BadType, EnumID::Garbage; // expected-error{{use of undeclared identifier 'BadType'}}
}
namespace pr15133 {
namespace ns {
const int V1 = 1; // expected-note {{declared here}}
}
struct C1 {
enum E1 { V2 = 2 }; // expected-note {{declared here}}
static const int V3 = 3; // expected-note {{declared here}}
};
enum E2 {
V4 = 4, // expected-note {{declared here}}
V6 // expected-note {{declared here}}
};
enum class EC3 { V0 = 0, V5 = 5 }; // expected-note {{declared here}}
void func_3();
void func_1(int x) {
switch(x) {
case 0: break;
case ns::V1:: break; // expected-error{{'V1' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
case C1::V2:: break; // expected-error{{'V2' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
case C1::V3:: break; // expected-error{{'V3' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
case V4:: break; // expected-error{{'V4' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
case V6:: func_3(); // expected-error{{'V6' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
}
void func_2(EC3 x) {
switch(x) {
case EC3::V0: break;
case EC3::V5:: break; // expected-error{{'V5' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
}
template<class T> struct TS1 {
typedef int A;
};
template<class T> void func(int x) {
switch(x) {
case TS1<T>::A:: break; // expected-error{{expected unqualified-id}}
}
};
void mainf() {
func<int>(1);
}
struct S {
static int n; // expected-note{{declared here}}
int nn; // expected-note 2 {{declared here}}
};
int func_3(int x) {
return x ? S::n :: 0; // expected-error{{'n' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
int func_4(int x, S &s) {
return x ? s.nn :: x; // expected-error{{'nn' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
int func_5(int x, S &s) {
return x ? s.nn :: S::n; // expected-error{{'nn' cannot appear before '::' because it is not a class, namespace, or enumeration; did you mean ':'?}}
}
struct S2 {
struct S3;
};
struct S2 :: S3 :: public S2 { // expected-error{{'public' cannot be a part of nested name specifier; did you mean ':'?}}
};
}
namespace InvalidEmptyNames {
// These shouldn't crash, the diagnostics aren't important.
struct ::, struct ::; // expected-error 2 {{expected identifier}} expected-error 2 {{declaration of anonymous struct must be a definition}} expected-warning {{declaration does not declare anything}}
enum ::, enum ::; // expected-error 2 {{expected identifier}} expected-warning {{declaration does not declare anything}}
struct ::__super, struct ::__super; // expected-error 2 {{expected identifier}} expected-error 2 {{expected '::' after '__super'}}
struct ::template foo, struct ::template bar; // expected-error 2 {{expected identifier}} expected-error 2 {{declaration of anonymous struct must be a definition}} expected-warning {{declaration does not declare anything}}
struct ::foo struct::; // expected-error {{no struct named 'foo' in the global namespace}} expected-error {{expected identifier}} expected-error {{declaration of anonymous struct must be a definition}}
class :: : {} a; // expected-error {{expected identifier}} expected-error {{expected class name}}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.