text stringlengths 54 60.6k |
|---|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkScalars.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkScalars.h"
#include "vtkFloatScalars.h"
#include "vtkShortScalars.h"
#include "vtkIdList.h"
#include "vtkLookupTable.h"
vtkScalars::vtkScalars()
{
this->Range[0] = this->Range[2] = this->Range[4] = this->Range[6] = 0.0;
this->Range[1] = this->Range[3] = this->Range[5] = this->Range[7] = 1.0;
this->LookupTable = NULL;
}
vtkScalars::~vtkScalars()
{
if ( this->LookupTable ) this->LookupTable->UnRegister(this);
}
// Description:
// Given a list of point ids, return an array of scalar values.
void vtkScalars::GetScalars(vtkIdList& ptId, vtkFloatScalars& fs)
{
for (int i=0; i<ptId.GetNumberOfIds(); i++)
{
fs.InsertScalar(i,this->GetScalar(ptId.GetId(i)));
}
}
// Description:
// Given a range of point ids [p1,p2], return an array of scalar values.
// Make sure enough space has been allocated in the vtkFloatScalars object
// to hold all the values.
void vtkScalars::GetScalars(int p1, int p2, vtkFloatScalars& fs)
{
int i, id;
for (i=0, id=p1; id <= p2; id++, i++)
{
fs.SetScalar(i,this->GetScalar(id));
}
}
// Description:
// Determine (rmin,rmax) range of scalar values.
void vtkScalars::ComputeRange()
{
int i;
float s;
if ( this->GetMTime() > this->ComputeTime )
{
this->Range[0] = VTK_LARGE_FLOAT;
this->Range[1] = -VTK_LARGE_FLOAT;
for (i=0; i<this->GetNumberOfScalars(); i++)
{
s = this->GetScalar(i);
if ( s < this->Range[0] ) this->Range[0] = s;
if ( s > this->Range[1] ) this->Range[1] = s;
}
this->ComputeTime.Modified();
}
}
// Description:
// Return the range of scalar values. Data returned as pointer to float array
// of length 2.
float *vtkScalars::GetRange()
{
this->ComputeRange();
return this->Range;
}
// Description:
// Return the range of scalar values. Range copied into array provided.
void vtkScalars::GetRange(float range[2])
{
this->ComputeRange();
range[0] = this->Range[0];
range[1] = this->Range[1];
}
void vtkScalars::CreateDefaultLookupTable()
{
if ( this->LookupTable ) this->LookupTable->UnRegister(this);
this->LookupTable = new vtkLookupTable;
this->LookupTable->Register(this);
}
void vtkScalars::SetLookupTable(vtkLookupTable *lut)
{
if ( this->LookupTable != lut )
{
if ( this->LookupTable ) this->LookupTable->UnRegister(this);
this->LookupTable = lut;
this->LookupTable->Register(this);
this->Modified();
}
}
void vtkScalars::PrintSelf(ostream& os, vtkIndent indent)
{
float *range;
vtkRefCount::PrintSelf(os,indent);
os << indent << "Number Of Scalars: " << this->GetNumberOfScalars() << "\n";
range = this->GetRange();
os << indent << "Range: (" << range[0] << ", " << range[1] << ")\n";
if ( this->LookupTable )
{
os << indent << "Lookup Table:\n";
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "LookupTable: (none)\n";
}
}
<commit_msg>lookup table created but not built<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkScalars.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkScalars.h"
#include "vtkFloatScalars.h"
#include "vtkShortScalars.h"
#include "vtkIdList.h"
#include "vtkLookupTable.h"
vtkScalars::vtkScalars()
{
this->Range[0] = this->Range[2] = this->Range[4] = this->Range[6] = 0.0;
this->Range[1] = this->Range[3] = this->Range[5] = this->Range[7] = 1.0;
this->LookupTable = NULL;
}
vtkScalars::~vtkScalars()
{
if ( this->LookupTable ) this->LookupTable->UnRegister(this);
}
// Description:
// Given a list of point ids, return an array of scalar values.
void vtkScalars::GetScalars(vtkIdList& ptId, vtkFloatScalars& fs)
{
for (int i=0; i<ptId.GetNumberOfIds(); i++)
{
fs.InsertScalar(i,this->GetScalar(ptId.GetId(i)));
}
}
// Description:
// Given a range of point ids [p1,p2], return an array of scalar values.
// Make sure enough space has been allocated in the vtkFloatScalars object
// to hold all the values.
void vtkScalars::GetScalars(int p1, int p2, vtkFloatScalars& fs)
{
int i, id;
for (i=0, id=p1; id <= p2; id++, i++)
{
fs.SetScalar(i,this->GetScalar(id));
}
}
// Description:
// Determine (rmin,rmax) range of scalar values.
void vtkScalars::ComputeRange()
{
int i;
float s;
if ( this->GetMTime() > this->ComputeTime )
{
this->Range[0] = VTK_LARGE_FLOAT;
this->Range[1] = -VTK_LARGE_FLOAT;
for (i=0; i<this->GetNumberOfScalars(); i++)
{
s = this->GetScalar(i);
if ( s < this->Range[0] ) this->Range[0] = s;
if ( s > this->Range[1] ) this->Range[1] = s;
}
this->ComputeTime.Modified();
}
}
// Description:
// Return the range of scalar values. Data returned as pointer to float array
// of length 2.
float *vtkScalars::GetRange()
{
this->ComputeRange();
return this->Range;
}
// Description:
// Return the range of scalar values. Range copied into array provided.
void vtkScalars::GetRange(float range[2])
{
this->ComputeRange();
range[0] = this->Range[0];
range[1] = this->Range[1];
}
void vtkScalars::CreateDefaultLookupTable()
{
if ( this->LookupTable ) this->LookupTable->UnRegister(this);
this->LookupTable = new vtkLookupTable;
// make sure it is built
// otherwise problems with InsertScalar trying to map through
// non built lut
this->LookupTable->Build();
this->LookupTable->Register(this);
}
void vtkScalars::SetLookupTable(vtkLookupTable *lut)
{
if ( this->LookupTable != lut )
{
if ( this->LookupTable ) this->LookupTable->UnRegister(this);
this->LookupTable = lut;
this->LookupTable->Register(this);
this->Modified();
}
}
void vtkScalars::PrintSelf(ostream& os, vtkIndent indent)
{
float *range;
vtkRefCount::PrintSelf(os,indent);
os << indent << "Number Of Scalars: " << this->GetNumberOfScalars() << "\n";
range = this->GetRange();
os << indent << "Range: (" << range[0] << ", " << range[1] << ")\n";
if ( this->LookupTable )
{
os << indent << "Lookup Table:\n";
this->LookupTable->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "LookupTable: (none)\n";
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: menubarwrapper.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2005-03-23 14:12:51 $
*
* 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): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_
#include <uielement/menubarwrapper.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_
#include <helper/actiontriggerhelper.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
#include <uielement/constitemcontainer.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_
#include <uielement/rootitemcontainer.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XMENUBAR_HPP_
#include <com/sun/star/awt/XMenuBar.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <com/sun/star/ui/UIElementType.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include <tools/solar.h>
#include <vcl/svapp.hxx>
#include <rtl/logfile.hxx>
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace ::com::sun::star::ui;
namespace framework
{
// #110897#
MenuBarWrapper::MenuBarWrapper(
const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager
)
: // #110897#
mxServiceFactory( xServiceManager ),
UIConfigElementWrapperBase( UIElementType::MENUBAR )
{
}
MenuBarWrapper::~MenuBarWrapper()
{
}
// #110897#
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& MenuBarWrapper::getServiceFactory()
{
// #110897#
return mxServiceFactory;
}
void SAL_CALL MenuBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)
{
Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );
com::sun::star::lang::EventObject aEvent( xThis );
m_aListenerContainer.disposeAndClear( aEvent );
ResetableGuard aLock( m_aLock );
m_xMenuBarManager->dispose();
m_xMenuBarManager.clear();
m_xConfigSource.clear();
m_xConfigData.clear();
m_xMenuBar.clear();
m_bDisposed = sal_True;
}
// XInitialization
void SAL_CALL MenuBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
RTL_LOGFILE_CONTEXT( aLog, "framework (cd100003) ::MenuBarWrapper::initialize" );
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( !m_bInitialized )
{
rtl::OUString aModuleIdentifier;
UIConfigElementWrapperBase::initialize( aArguments );
Reference< XFrame > xFrame( m_xWeakFrame );
if ( xFrame.is() && m_xConfigSource.is() )
{
// Create VCL menubar which will be filled with settings data
MenuBar* pVCLMenuBar = 0;
VCLXMenuBar* pAwtMenuBar = 0;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
pVCLMenuBar = new MenuBar();
}
try
{
m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
if ( m_xConfigData.is() )
{
// Fill menubar with container contents
USHORT nId = 1;
MenuBarManager::FillMenu( nId, pVCLMenuBar, aModuleIdentifier, m_xConfigData );
}
}
catch ( NoSuchElementException& )
{
}
sal_Bool bMenuOnly( sal_False );
for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )
{
PropertyValue aPropValue;
if ( aArguments[n] >>= aPropValue )
{
if ( aPropValue.Name.equalsAscii( "MenuOnly" ))
aPropValue.Value >>= bMenuOnly;
}
}
if ( !bMenuOnly )
{
// Initialize menubar manager with our vcl menu bar. There are some situations where we only want to get the menu without any
// interaction which is done by the menu bar manager. This must be requested by a special property called "MenuOnly". Be careful
// a menu bar created with this property is not fully supported. It must be attached to a real menu bar manager to have full
// support. This feature is currently used for "Inplace editing"!
// #110897# MenuBarManager* pMenuBarManager = new MenuBarManager( xFrame, pVCLMenuBar, sal_False, sal_True );
MenuBarManager* pMenuBarManager = new MenuBarManager( getServiceFactory(), xFrame, aModuleIdentifier, pVCLMenuBar, sal_False, sal_True );
m_xMenuBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pMenuBarManager ), UNO_QUERY );
}
// Initialize toolkit menu bar implementation to have awt::XMenuBar for data exchange.
// Don't use this toolkit menu bar or one of its functions. It is only used as a data container!
pAwtMenuBar = new VCLXMenuBar( pVCLMenuBar );
m_xMenuBar = Reference< XMenuBar >( static_cast< OWeakObject *>( pAwtMenuBar ), UNO_QUERY );
}
}
}
// XUIElementSettings
void SAL_CALL MenuBarWrapper::updateSettings() throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( m_bPersistent &&
m_xConfigSource.is() &&
m_xMenuBarManager.is() )
{
try
{
MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );
m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
if ( m_xConfigData.is() )
pMenuBarManager->SetItemContainer( m_xConfigData );
}
catch ( NoSuchElementException& )
{
}
}
}
void SAL_CALL MenuBarWrapper::setSettings( const Reference< XIndexAccess >& xSettings ) throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( xSettings.is() )
{
// Create a copy of the data if the container is not const
Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );
if ( xReplace.is() )
m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );
else
m_xConfigData = xSettings;
if ( m_xConfigSource.is() && m_bPersistent )
{
OUString aResourceURL( m_aResourceURL );
Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );
aLock.unlock();
try
{
xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );
}
catch( NoSuchElementException& )
{
}
}
}
}
Reference< XIndexAccess > SAL_CALL MenuBarWrapper::getSettings( sal_Bool bWriteable ) throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( bWriteable )
return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );
else
return m_xConfigData;
}
Reference< XInterface > SAL_CALL MenuBarWrapper::getRealInterface() throw ( RuntimeException )
{
if ( m_bDisposed )
throw DisposedException();
return Reference< XInterface >( m_xMenuBarManager, UNO_QUERY );
}
} // namespace framework
<commit_msg>INTEGRATION: CWS fwkfinal6 (1.7.30); FILE MERGED 2005/03/29 09:53:42 cd 1.7.30.1: #i46194# Support transient changes for menu bar<commit_after>/*************************************************************************
*
* $RCSfile: menubarwrapper.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-04-01 16:14:16 $
*
* 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): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_
#include <uielement/menubarwrapper.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_
#include <helper/actiontriggerhelper.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
#include <uielement/constitemcontainer.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_
#include <uielement/rootitemcontainer.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XMENUBAR_HPP_
#include <com/sun/star/awt/XMenuBar.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <com/sun/star/ui/UIElementType.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include <tools/solar.h>
#include <vcl/svapp.hxx>
#include <rtl/logfile.hxx>
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace ::com::sun::star::ui;
namespace framework
{
// #110897#
MenuBarWrapper::MenuBarWrapper(
const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager
)
: // #110897#
mxServiceFactory( xServiceManager ),
UIConfigElementWrapperBase( UIElementType::MENUBAR )
{
}
MenuBarWrapper::~MenuBarWrapper()
{
}
// #110897#
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& MenuBarWrapper::getServiceFactory()
{
// #110897#
return mxServiceFactory;
}
void SAL_CALL MenuBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)
{
Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );
com::sun::star::lang::EventObject aEvent( xThis );
m_aListenerContainer.disposeAndClear( aEvent );
ResetableGuard aLock( m_aLock );
m_xMenuBarManager->dispose();
m_xMenuBarManager.clear();
m_xConfigSource.clear();
m_xConfigData.clear();
m_xMenuBar.clear();
m_bDisposed = sal_True;
}
// XInitialization
void SAL_CALL MenuBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
RTL_LOGFILE_CONTEXT( aLog, "framework (cd100003) ::MenuBarWrapper::initialize" );
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( !m_bInitialized )
{
rtl::OUString aModuleIdentifier;
UIConfigElementWrapperBase::initialize( aArguments );
Reference< XFrame > xFrame( m_xWeakFrame );
if ( xFrame.is() && m_xConfigSource.is() )
{
// Create VCL menubar which will be filled with settings data
MenuBar* pVCLMenuBar = 0;
VCLXMenuBar* pAwtMenuBar = 0;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
pVCLMenuBar = new MenuBar();
}
try
{
m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
if ( m_xConfigData.is() )
{
// Fill menubar with container contents
USHORT nId = 1;
MenuBarManager::FillMenu( nId, pVCLMenuBar, aModuleIdentifier, m_xConfigData );
}
}
catch ( NoSuchElementException& )
{
}
sal_Bool bMenuOnly( sal_False );
for ( sal_Int32 n = 0; n < aArguments.getLength(); n++ )
{
PropertyValue aPropValue;
if ( aArguments[n] >>= aPropValue )
{
if ( aPropValue.Name.equalsAscii( "MenuOnly" ))
aPropValue.Value >>= bMenuOnly;
}
}
if ( !bMenuOnly )
{
// Initialize menubar manager with our vcl menu bar. There are some situations where we only want to get the menu without any
// interaction which is done by the menu bar manager. This must be requested by a special property called "MenuOnly". Be careful
// a menu bar created with this property is not fully supported. It must be attached to a real menu bar manager to have full
// support. This feature is currently used for "Inplace editing"!
// #110897# MenuBarManager* pMenuBarManager = new MenuBarManager( xFrame, pVCLMenuBar, sal_False, sal_True );
MenuBarManager* pMenuBarManager = new MenuBarManager( getServiceFactory(), xFrame, aModuleIdentifier, pVCLMenuBar, sal_False, sal_True );
m_xMenuBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pMenuBarManager ), UNO_QUERY );
}
// Initialize toolkit menu bar implementation to have awt::XMenuBar for data exchange.
// Don't use this toolkit menu bar or one of its functions. It is only used as a data container!
pAwtMenuBar = new VCLXMenuBar( pVCLMenuBar );
m_xMenuBar = Reference< XMenuBar >( static_cast< OWeakObject *>( pAwtMenuBar ), UNO_QUERY );
}
}
}
// XUIElementSettings
void SAL_CALL MenuBarWrapper::updateSettings() throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( m_xMenuBarManager.is() )
{
if ( m_xConfigSource.is() && m_bPersistent )
{
try
{
MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );
m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
if ( m_xConfigData.is() )
pMenuBarManager->SetItemContainer( m_xConfigData );
}
catch ( NoSuchElementException& )
{
}
}
else if ( !m_bPersistent )
{
// Transient menubar: do nothing
}
}
}
void SAL_CALL MenuBarWrapper::setSettings( const Reference< XIndexAccess >& xSettings ) throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( xSettings.is() )
{
// Create a copy of the data if the container is not const
Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );
if ( xReplace.is() )
m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );
else
m_xConfigData = xSettings;
if ( m_xConfigSource.is() && m_bPersistent )
{
OUString aResourceURL( m_aResourceURL );
Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );
aLock.unlock();
try
{
xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );
}
catch( NoSuchElementException& )
{
}
}
else if ( !m_bPersistent )
{
// Transient menubar => Fill menubar with new data
MenuBarManager* pMenuBarManager = static_cast< MenuBarManager *>( m_xMenuBarManager.get() );
if ( pMenuBarManager )
pMenuBarManager->SetItemContainer( m_xConfigData );
}
}
}
Reference< XIndexAccess > SAL_CALL MenuBarWrapper::getSettings( sal_Bool bWriteable ) throw ( RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( bWriteable )
return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );
else
return m_xConfigData;
}
Reference< XInterface > SAL_CALL MenuBarWrapper::getRealInterface() throw ( RuntimeException )
{
if ( m_bDisposed )
throw DisposedException();
return Reference< XInterface >( m_xMenuBarManager, UNO_QUERY );
}
} // namespace framework
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetTaskTest
#include <boost/test/unit_test.hpp>
#define private public
#include "../../JPetTask/JPetTask.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE( my_test1 )
{
BOOST_REQUIRE(1==0);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Comment out empty test in JPetTaskTest<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetTaskTest
#include <boost/test/unit_test.hpp>
#define private public
#include "../../JPetTask/JPetTask.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE( my_test1 )
{
//BOOST_REQUIRE(1==0);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "classifier.h"
#include <iostream>
#include <fstream>
#include <string>
Data::Data(const char *data_file)
{
feat_cnt = 0;
row_cnt = 0;
std::string cur_line;
std::ifstream in_file;
in_file.open(data_file, std::ifstream::in);
while(in_file.good())
{
std::getline(in_file, cur_line);
if(cur_line != "")
{
std::cout << "Line " << row_cnt << ": " << cur_line << "\n";
row_cnt++;
}
}
in_file.close();
}
double Data::My_atof(char *ascii_str)
{
return 0.0;
}
void Data::Norm()
{
}
<commit_msg>Worked on file reading functionality<commit_after>#include "classifier.h"
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
Data::Data(const char *data_file)
{
feat_cnt = 0;
row_cnt = 0;
std::string cur_line;
std::ifstream in_file;
in_file.open(data_file, std::ifstream::in);
while(in_file.good())
{
std::getline(in_file, cur_line);
if(cur_line != "")
{
//std::cout << "Line " << row_cnt << ": " << cur_line << "\n";
int col_cnt = 0;
char *tok, *s_ptr;
char *tok_str = (char *)cur_line.c_str();
for(tok = strtok_r(tok_str, " \n", &s_ptr); tok != NULL; tok = strtok_r(NULL, " \n", &s_ptr))
{
//std::cout << tok << " ";
My_atof(tok);
col_cnt++;
}
std::cout << std::endl;
feat_cnt = col_cnt-1;
row_cnt++;
}
}
in_file.close();
}
double Data::My_atof(char *ascii_str)
{
char *s_ptr, *tok;
double value;
tok = strtok_r(ascii_str, "e+", &s_ptr);
//std::cout << "Base: " << tok;
tok = strtok_r(NULL, "e+", &s_ptr);
//std::cout << ", Exponent: " << tok << std::endl;
return 0.0;
}
void Data::Norm()
{
}
<|endoftext|> |
<commit_before>#include "Fit/Fitter.h"
#include "Math/WrappedMultiTF1.h"
#include "TH1.h"
#include "TMath.h"
#include "TRandom.h"
#include "TROOT.h"
#include<iostream>
#include<chrono>
constexpr int paramSize = 6;
bool compareResult(double v1, double v2, std::string s = "", double tol = 0.01)
{
// compare v1 with reference v2
// // give 1% tolerance
if (std::abs(v1 - v2) < tol * std::abs(v2)) return true;
std::cerr << s << " Failed comparison of fit results \t logl = " << v1 << " it should be = " << v2 << std::endl;
return false;
}
//Functor for a Higgs Fit normalized with analytical integral
template<class T>
class Func {
public:
Func()
{
params.resize(paramSize);
}
T operator()(const T *data, const Double_t *p)
{
bool changed = false;
for (unsigned i = 0; i < params.size(); i++) {
R__LOCKGUARD(gROOTMutex);
if (p[i] != params[i])
if (!changed) {
changed = true;
}
}
if (changed) {
R__LOCKGUARD(gROOTMutex);
for (unsigned i = 0; i < paramSize; i++) {
params[i] = p[i];
}
auto funcInt1 = [&](double x) {
return 50.*TMath::Sqrt(TMath::Pi()) * exp((p[4] * p[4]) / (4 * p[5])) * TMath::Erf((0.5 * p[4] + p[5] * 0.01 * x) / (TMath::Sqrt(p[5])))
/ (TMath::Sqrt(p[5]));
};
auto funcInt2 = [&](double x) {
return -p[3] * TMath::Sqrt(TMath::Pi() / 2.) * TMath::Erf((p[2] - x) / (TMath::Sqrt(2.) * p[3]));
};
integral1 = funcInt1(200) - funcInt1(100);
integral2 = funcInt2(200) - funcInt2(100);
}
auto f1 = params[0] * exp(-(*data + (-p[2])) * (*data + (-p[2])) / (2.*p[3] * p[3]));
auto f2 = (1 - params[0]) * exp(-(params[4] * (*data * (0.01)) +
params[5] * ((*data) * (0.01)) * ((*data) * (0.01))));
f1 /= integral2 != 0 ? integral2 : 1;
f2 /= integral1 != 0 ? integral1 : 1;
return f1 + f2;
}
private:
double integral1 = 1.;
double integral2 = 1.;
std::vector<double> params;
};
//Test class with functions for each of the cases
class TestVector {
public:
TestVector(unsigned nPoints)
{
fSeq = new TF1("fseq", Func<double>(), 100, 200, paramSize);
wfSeq = new ROOT::Math::WrappedMultiTF1Templ<double>(*fSeq);
#ifdef R__HAS_VECCORE
fVec = new TF1("fvCore", Func<ROOT::Double_v>(), 100, 200, paramSize);
wfVec = new ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v>(*fVec);
#endif
dataSB = new ROOT::Fit::UnBinData(nPoints);
fSeq->SetParameters(p);
if (!filledData) {
for (unsigned i = 0; i < nPoints; ++i) {
double x = fSeq->GetRandom();
dataSB->Add(x);
}
filledData = true;
}
fitter.Config().MinimizerOptions().SetPrintLevel(3);
fitter.Config().SetMinimizer("Minuit2", "Migrad");
}
double testFitSeq()
{
std::cout << "\n////////////////////////////SEQUENTIAL TEST////////////////////////////" << std::endl << std::endl;
fSeq->SetParameters(p);
fitter.SetFunction(*wfSeq, false);
fitter.Config().ParSettings(0).SetLimits(0, 1);
fitter.Config().ParSettings(1).Fix();
fitter.Config().ParSettings(3).SetLowerLimit(0);
fitter.Config().ParSettings(4).SetLowerLimit(0);
fitter.Config().ParSettings(5).SetLowerLimit(0);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << std::endl << "Time for the sequential test: " << duration.count() << std::endl;
return ret;
}
double testMTFit()
{
std::cout << "\n///////////////////////////////MT TEST////////////////////////////" << std::endl << std::endl;
fSeq->SetParameters(p);
fitter.SetFunction(*wfSeq, false);
fitter.Config().ParSettings(0).SetLimits(0, 1);
fitter.Config().ParSettings(1).Fix();
fitter.Config().ParSettings(3).SetLowerLimit(0);
fitter.Config().ParSettings(4).SetLowerLimit(0);
fitter.Config().ParSettings(5).SetLowerLimit(0);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the parallel test: " << duration.count() << std::endl;
return ret;
}
double testMPFit()
{
std::cout << "\n///////////////////////////////MP TEST////////////////////////////\n\n";
fSeq->SetParameters(p);
fitter.SetFunction(*wfSeq, false);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the multiprocess test:" << duration.count() << std::endl;
return ret;
}
#ifdef R__HAS_VECCORE
double testFitVec()
{
std::cout << "\n////////////////////////////VECTOR TEST////////////////////////////" << std::endl << std::endl;
fVec->SetParameters(p);
fitter.SetFunction(*wfVec);
fitter.Config().ParSettings(0).SetLimits(0, 1);
fitter.Config().ParSettings(1).Fix();
fitter.Config().ParSettings(3).SetLowerLimit(0);
fitter.Config().ParSettings(4).SetLowerLimit(0);
fitter.Config().ParSettings(5).SetLowerLimit(0);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the vectorized test: " << duration.count() << std::endl;
return ret;
}
double testMTFitVec()
{
std::cout << "\n///////////////////////////////MT+VEC TEST////////////////////////////\n\n";
fVec->SetParameters(p);
fitter.SetFunction(*wfVec);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the parallel+vectorized test: " << duration.count() << std::endl;
return ret;
}
double testMPFitVec()
{
std::cout << "\n///////////////////////////////MP+VEC TEST////////////////////////////\n\n";
fVec->SetParameters(p);
fitter.SetFunction(*wfVec);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the multiprocess+vectorized test:" << duration.count() << std::endl;
return ret;
}
#endif
const ROOT::Fit::Fitter &GetFitter()
{
return fitter;
}
private:
TF1 *fSeq;
ROOT::Math::WrappedMultiTF1Templ<double> *wfSeq;
#ifdef R__HAS_VECCORE
TF1 *fVec;
ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v> *wfVec;
#endif
std::chrono::time_point<std::chrono::system_clock> start, end;
std::chrono::duration<double> duration;
ROOT::Fit::Fitter fitter;
ROOT::Fit::UnBinData *dataSB;
bool filledData = false;
double p[paramSize] = {0.1, 1000., 130., 2., 3.5, 1.5};
};
int main()
{
TestVector test(200000);
//Sequential
if (!test.testFitSeq()) {
Error("testLogLExecPolicy", "Fit failed!");
return -1;
}
// #if defined(R__USE_IMT) || defined(R__HAS_VECCORE)
//#ifdef R__HAS_VECCORE
auto seq = test.GetFitter().Result().MinFcnValue();
//#endif
#ifdef R__USE_IMT
//Multithreaded
if (!test.testMTFit()) {
Error("testLogLExecPolicy", "Multithreaded Fit failed!");
return -1;
}
auto seqMT = test.GetFitter().Result().MinFcnValue();
if (!compareResult(seqMT, seq, "Mutithreaded LogL Fit: "))
return 1;
#endif
#ifdef R__HAS_VECCORE
//Vectorized
if (!test.testFitVec()) {
Error("testLogLExecPolicy", "Vectorized Fit failed!");
return -1;
}
auto vec = test.GetFitter().Result().MinFcnValue();
if (!compareResult(vec, seq, "vectorized LogL Fit: "))
return 2;
#endif
#if defined(R__USE_IMT) && defined(R__HAS_VECCORE)
//Multithreaded and vectorized
if (!test.testMTFitVec()) {
Error("testLogLExecPolicy", "Multithreaded + vectorized Fit failed!");
return -1;
}
auto vecMT = test.GetFitter().Result().MinFcnValue();
if (!compareResult(vecMT, seq, "Mutithreaded + vectorized LogL Fit: "))
return 3;
#endif
return 0;
}
<commit_msg>Increase the fit tolerance for the unbinned log-likelihood fit test. This should fix some failures observed in MT mode<commit_after>#include "Fit/Fitter.h"
#include "Math/WrappedMultiTF1.h"
#include "TH1.h"
#include "TMath.h"
#include "TRandom.h"
#include "TROOT.h"
#include<iostream>
#include<chrono>
constexpr int paramSize = 6;
bool compareResult(double v1, double v2, std::string s = "", double tol = 0.01)
{
// compare v1 with reference v2
// // give 1% tolerance
if (std::abs(v1 - v2) < tol * std::abs(v2)) return true;
std::cerr << s << " Failed comparison of fit results \t logl = " << v1 << " it should be = " << v2 << std::endl;
return false;
}
//Functor for a Higgs Fit normalized with analytical integral
template<class T>
class Func {
public:
Func()
{
params.resize(paramSize);
}
T operator()(const T *data, const Double_t *p)
{
bool changed = false;
for (unsigned i = 0; i < params.size(); i++) {
R__LOCKGUARD(gROOTMutex);
if (p[i] != params[i])
if (!changed) {
changed = true;
}
}
if (changed) {
R__LOCKGUARD(gROOTMutex);
for (unsigned i = 0; i < paramSize; i++) {
params[i] = p[i];
}
auto funcInt1 = [&](double x) {
return 50.*TMath::Sqrt(TMath::Pi()) * exp((p[4] * p[4]) / (4 * p[5])) * TMath::Erf((0.5 * p[4] + p[5] * 0.01 * x) / (TMath::Sqrt(p[5])))
/ (TMath::Sqrt(p[5]));
};
auto funcInt2 = [&](double x) {
return -p[3] * TMath::Sqrt(TMath::Pi() / 2.) * TMath::Erf((p[2] - x) / (TMath::Sqrt(2.) * p[3]));
};
integral1 = funcInt1(200) - funcInt1(100);
integral2 = funcInt2(200) - funcInt2(100);
}
auto f1 = params[0] * exp(-(*data + (-p[2])) * (*data + (-p[2])) / (2.*p[3] * p[3]));
auto f2 = (1 - params[0]) * exp(-(params[4] * (*data * (0.01)) +
params[5] * ((*data) * (0.01)) * ((*data) * (0.01))));
f1 /= integral2 != 0 ? integral2 : 1;
f2 /= integral1 != 0 ? integral1 : 1;
return f1 + f2;
}
private:
double integral1 = 1.;
double integral2 = 1.;
std::vector<double> params;
};
//Test class with functions for each of the cases
class TestVector {
public:
TestVector(unsigned nPoints)
{
fSeq = new TF1("fseq", Func<double>(), 100, 200, paramSize);
wfSeq = new ROOT::Math::WrappedMultiTF1Templ<double>(*fSeq);
#ifdef R__HAS_VECCORE
fVec = new TF1("fvCore", Func<ROOT::Double_v>(), 100, 200, paramSize);
wfVec = new ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v>(*fVec);
#endif
dataSB = new ROOT::Fit::UnBinData(nPoints);
fSeq->SetParameters(p);
if (!filledData) {
for (unsigned i = 0; i < nPoints; ++i) {
double x = fSeq->GetRandom();
dataSB->Add(x);
}
filledData = true;
}
fitter.Config().MinimizerOptions().SetPrintLevel(3);
fitter.Config().SetMinimizer("Minuit2", "Migrad");
fitter.Config().MinimizerOptions().SetTolerance(10);
}
double testFitSeq()
{
std::cout << "\n////////////////////////////SEQUENTIAL TEST////////////////////////////" << std::endl << std::endl;
fSeq->SetParameters(p);
fitter.SetFunction(*wfSeq, false);
fitter.Config().ParSettings(0).SetLimits(0, 1);
fitter.Config().ParSettings(1).Fix();
fitter.Config().ParSettings(3).SetLowerLimit(0);
fitter.Config().ParSettings(4).SetLowerLimit(0);
fitter.Config().ParSettings(5).SetLowerLimit(0);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << std::endl << "Time for the sequential test: " << duration.count() << std::endl;
return ret;
}
double testMTFit()
{
std::cout << "\n///////////////////////////////MT TEST////////////////////////////" << std::endl << std::endl;
fSeq->SetParameters(p);
fitter.SetFunction(*wfSeq, false);
fitter.Config().ParSettings(0).SetLimits(0, 1);
fitter.Config().ParSettings(1).Fix();
fitter.Config().ParSettings(3).SetLowerLimit(0);
fitter.Config().ParSettings(4).SetLowerLimit(0);
fitter.Config().ParSettings(5).SetLowerLimit(0);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the parallel test: " << duration.count() << std::endl;
return ret;
}
double testMPFit()
{
std::cout << "\n///////////////////////////////MP TEST////////////////////////////\n\n";
fSeq->SetParameters(p);
fitter.SetFunction(*wfSeq, false);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the multiprocess test:" << duration.count() << std::endl;
return ret;
}
#ifdef R__HAS_VECCORE
double testFitVec()
{
std::cout << "\n////////////////////////////VECTOR TEST////////////////////////////" << std::endl << std::endl;
fVec->SetParameters(p);
fitter.SetFunction(*wfVec);
fitter.Config().ParSettings(0).SetLimits(0, 1);
fitter.Config().ParSettings(1).Fix();
fitter.Config().ParSettings(3).SetLowerLimit(0);
fitter.Config().ParSettings(4).SetLowerLimit(0);
fitter.Config().ParSettings(5).SetLowerLimit(0);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the vectorized test: " << duration.count() << std::endl;
return ret;
}
double testMTFitVec()
{
std::cout << "\n///////////////////////////////MT+VEC TEST////////////////////////////\n\n";
fVec->SetParameters(p);
fitter.SetFunction(*wfVec);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultithread);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the parallel+vectorized test: " << duration.count() << std::endl;
return ret;
}
double testMPFitVec()
{
std::cout << "\n///////////////////////////////MP+VEC TEST////////////////////////////\n\n";
fVec->SetParameters(p);
fitter.SetFunction(*wfVec);
start = std::chrono::system_clock::now();
bool ret = fitter.Fit(*dataSB, 0, ROOT::Fit::ExecutionPolicy::kMultiprocess);
end = std::chrono::system_clock::now();
duration = end - start;
std::cout << "Time for the multiprocess+vectorized test:" << duration.count() << std::endl;
return ret;
}
#endif
const ROOT::Fit::Fitter &GetFitter()
{
return fitter;
}
private:
TF1 *fSeq;
ROOT::Math::WrappedMultiTF1Templ<double> *wfSeq;
#ifdef R__HAS_VECCORE
TF1 *fVec;
ROOT::Math::WrappedMultiTF1Templ<ROOT::Double_v> *wfVec;
#endif
std::chrono::time_point<std::chrono::system_clock> start, end;
std::chrono::duration<double> duration;
ROOT::Fit::Fitter fitter;
ROOT::Fit::UnBinData *dataSB;
bool filledData = false;
double p[paramSize] = {0.1, 1000., 130., 2., 3.5, 1.5};
};
int main()
{
TestVector test(200000);
//Sequential
if (!test.testFitSeq()) {
Error("testLogLExecPolicy", "Fit failed!");
return -1;
}
// #if defined(R__USE_IMT) || defined(R__HAS_VECCORE)
//#ifdef R__HAS_VECCORE
auto seq = test.GetFitter().Result().MinFcnValue();
//#endif
#ifdef R__USE_IMT
//Multithreaded
if (!test.testMTFit()) {
Error("testLogLExecPolicy", "Multithreaded Fit failed!");
return -1;
}
auto seqMT = test.GetFitter().Result().MinFcnValue();
if (!compareResult(seqMT, seq, "Mutithreaded LogL Fit: "))
return 1;
#endif
#ifdef R__HAS_VECCORE
//Vectorized
if (!test.testFitVec()) {
Error("testLogLExecPolicy", "Vectorized Fit failed!");
return -1;
}
auto vec = test.GetFitter().Result().MinFcnValue();
if (!compareResult(vec, seq, "vectorized LogL Fit: "))
return 2;
#endif
#if defined(R__USE_IMT) && defined(R__HAS_VECCORE)
//Multithreaded and vectorized
if (!test.testMTFitVec()) {
Error("testLogLExecPolicy", "Multithreaded + vectorized Fit failed!");
return -1;
}
auto vecMT = test.GetFitter().Result().MinFcnValue();
if (!compareResult(vecMT, seq, "Mutithreaded + vectorized LogL Fit: "))
return 3;
#endif
return 0;
}
<|endoftext|> |
<commit_before>#include "dbdriver/dbdriver.h"
#include "dbdriver/constants.h"
#include <mongo/client/dbclient.h>
#include <vector>
#include <string>
#include <cstdlib>
#include <sstream>
#include <mongo/db/jsobj.h>
#include <iostream>
namespace dbdriver {
status_t str2uint(const std::string & str, uint64_t & uintval);
const size_t LOG_FIELDS_COUNT = 8;
class DbDriverImpl {
private:
std::string _vhost;
std::string _remote_host;
uint64_t _timestamp;
std::string _req_str;
uint64_t _ret_code;
uint64_t _resp_size;
std::string _referrer;
std::string _user_agent;
mongo::DBClientConnection _conn;
DbDriverImpl(const DbDriverImpl & dbdriver_impl); // prevent copy construction
status_t _tokenize(const std::string & input_line, std::vector<std::string> & tokens);
status_t _populate_fields(const std::vector<std::string> & tokens);
status_t _insert_record_db();
public:
DbDriverImpl();
~DbDriverImpl();
status_t insert(const std::string & input_line);
};
DbDriver::DbDriver():
_impl(new DbDriverImpl())
{
}
status_t DbDriver::insert(const std::string & input_line)
{
return _impl->insert(input_line);
}
DbDriver::~DbDriver()
{
if (_impl){
delete _impl;
_impl = NULL;
}
}
DbDriverImpl::DbDriverImpl()
{
_conn.connect(DB_HOST);
}
status_t DbDriverImpl::insert(const std::string & input_line)
{
std::vector<std::string> tokens;
std::vector<std::string>::iterator token_it;
int i = 0;
if (DB_SUCCESS != _tokenize(input_line, tokens)){
std::cerr << "Error tokenizing input line" << std::endl;
return DB_FAILURE;
}
for(token_it = tokens.begin(); token_it < tokens.end(); token_it++, i++){
}
if (DB_SUCCESS != _populate_fields(tokens)){
std::cerr << "Error populating fields" << std::endl;
return DB_FAILURE;
}
if (DB_SUCCESS != _insert_record_db()){
std::cerr << "Error inserting record into database" << std::endl;
return DB_FAILURE;
}
return DB_SUCCESS;
}
status_t DbDriverImpl::_tokenize(const std::string & input_line, std::vector<std::string> & tokens)
{
const char * separator = " ";
char *tok = strtok((char *)input_line.c_str(), separator);
bool begin = false;
bool tok_complete = true;
std::string tmp_tok;
while(tok) {
if(tok[0] == '"' && begin == false && tok[strlen(tok) - 1] != '"'){
begin = true;
//tmp_tok = tok;
tmp_tok = tok + 1;
tok_complete = false;
}
else if(begin == true){
tmp_tok = tmp_tok + " " + tok;
if(tok[strlen(tok) - 1] == '"'){
tok_complete = true;
begin = false;
}
}
else {
if (tok[0] == '"') {
tmp_tok = tok + 1;
}
else {
tmp_tok = tok;
}
}
if(tok_complete){
// to remove the trailing "
if(tmp_tok[tmp_tok.size() - 1] == '"'){
tmp_tok = tmp_tok.substr(0, tmp_tok.length() - 1);
}
tokens.push_back(tmp_tok);
}
tok = strtok(NULL, " ");
}
return DB_SUCCESS;
}
status_t DbDriverImpl::_populate_fields(const std::vector<std::string> & tokens)
{
if(tokens.size() != LOG_FIELDS_COUNT){
std::cerr << "Invalid number of fields, expected " << LOG_FIELDS_COUNT << ", got " << tokens.size() << std::endl;
return DB_FAILURE;
}
_vhost = tokens[0];
_remote_host = tokens[1];
_req_str = tokens[3];
_referrer = tokens[6];
_user_agent = tokens[7];
if(str2uint(tokens[2], _timestamp) != DB_SUCCESS) {
std::cerr << "Unable to parse timestamp from " << tokens[2] << std::endl;
}
if(str2uint(tokens[4], _ret_code) != DB_SUCCESS) {
std::cerr << "Unable to parse return code from " << tokens[4] << std::endl;
}
if (tokens[5] == "-"){
_resp_size = 0;
}
else if(str2uint(tokens[5], _resp_size) != DB_SUCCESS) {
std::cerr << "Unable to parse response size from " << tokens[5] << std::endl;
}
return DB_SUCCESS;
}
status_t DbDriverImpl::_insert_record_db()
{
mongo::BSONObj ua_obj;
ua_obj = _conn.findOne(DB_UA_COLLECTION_NAME.c_str(), QUERY("user_agent" << _user_agent));
if (!ua_obj.isEmpty()) {
_conn.update(DB_UA_COLLECTION_NAME.c_str(), BSON("user_agent" << _user_agent),
BSON("$inc" << BSON("count" << 1)));
}
else {
_conn.insert(DB_UA_COLLECTION_NAME.c_str(), BSON(mongo::GENOID << "user_agent" << _user_agent << "count" << 1));
ua_obj = _conn.findOne(DB_UA_COLLECTION_NAME.c_str(), QUERY("user_agent" << _user_agent));
}
mongo::BSONObj vhost_obj;
vhost_obj = _conn.findOne(DB_VHOST_COLLECTION_NAME.c_str(), QUERY("vhost" << _vhost));
if (!vhost_obj.isEmpty()) {
_conn.update(DB_VHOST_COLLECTION_NAME.c_str(), BSON("vhost" << _vhost),
BSON("$inc" << BSON("count" << 1)));
}
else {
_conn.insert(DB_VHOST_COLLECTION_NAME.c_str(), BSON(mongo::GENOID << "vhost" << _vhost << "count" << 1));
vhost_obj = _conn.findOne(DB_VHOST_COLLECTION_NAME.c_str(), QUERY("vhost" << _vhost));
}
std::string ua_id = ua_obj["_id"].OID().toString();
std::string vhost_id = vhost_obj["_id"].OID().toString();
std::string req_str_stripped;
size_t found = _req_str.find_last_of(" ");
req_str_stripped = _req_str.substr(0, found);
mongo::BSONObjBuilder b;
b.genOID().append("vhost", _vhost_id);
b.append("remote_host", _remote_host);
//b.appendTimeT("timestamp", (time_t)_timestamp);
b.append("timestamp", (double)_timestamp);
b.append("req_str", req_str_stripped);
b.append("ret_code", (double)_ret_code);
b.append("resp_size", (double)_resp_size);
b.append("referrer", _referrer);
b.append("user_agent", ua_id);
mongo::BSONObj p = b.obj();
_conn.insert(DB_COLLECTION_NAME.c_str(), p);
return DB_SUCCESS;
}
DbDriverImpl::~DbDriverImpl()
{
}
status_t str2uint(const std::string & str, uint64_t & uintval)
{
uint64_t tmpval;
char c;
std::stringstream ss(str);
ss >> tmpval;
if(ss.fail() || ss.get(c)){
return DB_FAILURE;
}
uintval = tmpval;
return DB_SUCCESS;
}
};
<commit_msg>add vhost collection<commit_after>#include "dbdriver/dbdriver.h"
#include "dbdriver/constants.h"
#include <mongo/client/dbclient.h>
#include <vector>
#include <string>
#include <cstdlib>
#include <sstream>
#include <mongo/db/jsobj.h>
#include <iostream>
namespace dbdriver {
status_t str2uint(const std::string & str, uint64_t & uintval);
const size_t LOG_FIELDS_COUNT = 8;
class DbDriverImpl {
private:
std::string _vhost;
std::string _remote_host;
uint64_t _timestamp;
std::string _req_str;
uint64_t _ret_code;
uint64_t _resp_size;
std::string _referrer;
std::string _user_agent;
mongo::DBClientConnection _conn;
DbDriverImpl(const DbDriverImpl & dbdriver_impl); // prevent copy construction
status_t _tokenize(const std::string & input_line, std::vector<std::string> & tokens);
status_t _populate_fields(const std::vector<std::string> & tokens);
status_t _insert_record_db();
public:
DbDriverImpl();
~DbDriverImpl();
status_t insert(const std::string & input_line);
};
DbDriver::DbDriver():
_impl(new DbDriverImpl())
{
}
status_t DbDriver::insert(const std::string & input_line)
{
return _impl->insert(input_line);
}
DbDriver::~DbDriver()
{
if (_impl){
delete _impl;
_impl = NULL;
}
}
DbDriverImpl::DbDriverImpl()
{
_conn.connect(DB_HOST);
}
status_t DbDriverImpl::insert(const std::string & input_line)
{
std::vector<std::string> tokens;
std::vector<std::string>::iterator token_it;
int i = 0;
if (DB_SUCCESS != _tokenize(input_line, tokens)){
std::cerr << "Error tokenizing input line" << std::endl;
return DB_FAILURE;
}
for(token_it = tokens.begin(); token_it < tokens.end(); token_it++, i++){
}
if (DB_SUCCESS != _populate_fields(tokens)){
std::cerr << "Error populating fields" << std::endl;
return DB_FAILURE;
}
if (DB_SUCCESS != _insert_record_db()){
std::cerr << "Error inserting record into database" << std::endl;
return DB_FAILURE;
}
return DB_SUCCESS;
}
status_t DbDriverImpl::_tokenize(const std::string & input_line, std::vector<std::string> & tokens)
{
const char * separator = " ";
char *tok = strtok((char *)input_line.c_str(), separator);
bool begin = false;
bool tok_complete = true;
std::string tmp_tok;
while(tok) {
if(tok[0] == '"' && begin == false && tok[strlen(tok) - 1] != '"'){
begin = true;
//tmp_tok = tok;
tmp_tok = tok + 1;
tok_complete = false;
}
else if(begin == true){
tmp_tok = tmp_tok + " " + tok;
if(tok[strlen(tok) - 1] == '"'){
tok_complete = true;
begin = false;
}
}
else {
if (tok[0] == '"') {
tmp_tok = tok + 1;
}
else {
tmp_tok = tok;
}
}
if(tok_complete){
// to remove the trailing "
if(tmp_tok[tmp_tok.size() - 1] == '"'){
tmp_tok = tmp_tok.substr(0, tmp_tok.length() - 1);
}
tokens.push_back(tmp_tok);
}
tok = strtok(NULL, " ");
}
return DB_SUCCESS;
}
status_t DbDriverImpl::_populate_fields(const std::vector<std::string> & tokens)
{
if(tokens.size() != LOG_FIELDS_COUNT){
std::cerr << "Invalid number of fields, expected " << LOG_FIELDS_COUNT << ", got " << tokens.size() << std::endl;
return DB_FAILURE;
}
_vhost = tokens[0];
_remote_host = tokens[1];
_req_str = tokens[3];
_referrer = tokens[6];
_user_agent = tokens[7];
if(str2uint(tokens[2], _timestamp) != DB_SUCCESS) {
std::cerr << "Unable to parse timestamp from " << tokens[2] << std::endl;
}
if(str2uint(tokens[4], _ret_code) != DB_SUCCESS) {
std::cerr << "Unable to parse return code from " << tokens[4] << std::endl;
}
if (tokens[5] == "-"){
_resp_size = 0;
}
else if(str2uint(tokens[5], _resp_size) != DB_SUCCESS) {
std::cerr << "Unable to parse response size from " << tokens[5] << std::endl;
}
return DB_SUCCESS;
}
status_t DbDriverImpl::_insert_record_db()
{
mongo::BSONObj ua_obj;
ua_obj = _conn.findOne(DB_UA_COLLECTION_NAME.c_str(), QUERY("user_agent" << _user_agent));
if (!ua_obj.isEmpty()) {
_conn.update(DB_UA_COLLECTION_NAME.c_str(), BSON("user_agent" << _user_agent),
BSON("$inc" << BSON("count" << 1)));
}
else {
_conn.insert(DB_UA_COLLECTION_NAME.c_str(), BSON(mongo::GENOID << "user_agent" << _user_agent << "count" << 1));
ua_obj = _conn.findOne(DB_UA_COLLECTION_NAME.c_str(), QUERY("user_agent" << _user_agent));
}
mongo::BSONObj vhost_obj;
vhost_obj = _conn.findOne(DB_VHOST_COLLECTION_NAME.c_str(), QUERY("vhost" << _vhost));
if (!vhost_obj.isEmpty()) {
_conn.update(DB_VHOST_COLLECTION_NAME.c_str(), BSON("vhost" << _vhost),
BSON("$inc" << BSON("count" << 1)));
}
else {
_conn.insert(DB_VHOST_COLLECTION_NAME.c_str(), BSON(mongo::GENOID << "vhost" << _vhost << "count" << 1));
vhost_obj = _conn.findOne(DB_VHOST_COLLECTION_NAME.c_str(), QUERY("vhost" << _vhost));
}
std::string ua_id = ua_obj["_id"].OID().toString();
std::string vhost_id = vhost_obj["_id"].OID().toString();
std::string req_str_stripped;
size_t found = _req_str.find_last_of(" ");
req_str_stripped = _req_str.substr(0, found);
mongo::BSONObjBuilder b;
b.genOID().append("vhost", vhost_id);
b.append("remote_host", _remote_host);
//b.appendTimeT("timestamp", (time_t)_timestamp);
b.append("timestamp", (double)_timestamp);
b.append("req_str", req_str_stripped);
b.append("ret_code", (double)_ret_code);
b.append("resp_size", (double)_resp_size);
b.append("referrer", _referrer);
b.append("user_agent", ua_id);
mongo::BSONObj p = b.obj();
_conn.insert(DB_COLLECTION_NAME.c_str(), p);
return DB_SUCCESS;
}
DbDriverImpl::~DbDriverImpl()
{
}
status_t str2uint(const std::string & str, uint64_t & uintval)
{
uint64_t tmpval;
char c;
std::stringstream ss(str);
ss >> tmpval;
if(ss.fail() || ss.get(c)){
return DB_FAILURE;
}
uintval = tmpval;
return DB_SUCCESS;
}
};
<|endoftext|> |
<commit_before><commit_msg>add dither again<commit_after><|endoftext|> |
<commit_before><commit_msg>IP Address Updated<commit_after><|endoftext|> |
<commit_before><commit_msg>Update net.cpp<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2020 André Perez Maselco
//
// 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 "source/fuzz/fuzzer_pass_push_ids_through_variables.h"
#include "source/fuzz/fuzzer_util.h"
#include "source/fuzz/instruction_descriptor.h"
#include "source/fuzz/transformation_push_id_through_variable.h"
namespace spvtools {
namespace fuzz {
FuzzerPassPushIdsThroughVariables::FuzzerPassPushIdsThroughVariables(
opt::IRContext* ir_context, TransformationContext* transformation_context,
FuzzerContext* fuzzer_context,
protobufs::TransformationSequence* transformations)
: FuzzerPass(ir_context, transformation_context, fuzzer_context,
transformations) {}
FuzzerPassPushIdsThroughVariables::~FuzzerPassPushIdsThroughVariables() =
default;
void FuzzerPassPushIdsThroughVariables::Apply() {
ForEachInstructionWithInstructionDescriptor(
[this](opt::Function* function, opt::BasicBlock* block,
opt::BasicBlock::iterator instruction_iterator,
const protobufs::InstructionDescriptor& instruction_descriptor)
-> void {
assert(instruction_iterator->opcode() ==
instruction_descriptor.target_instruction_opcode() &&
"The opcode of the instruction we might insert before must be "
"the same as the opcode in the descriptor for the instruction");
// Randomly decide whether to try pushing an id through a variable.
if (!GetFuzzerContext()->ChoosePercentage(
GetFuzzerContext()->GetChanceOfPushingIdThroughVariable())) {
return;
}
// The block containing the instruction we are going to insert before
// must be reachable.
if (!fuzzerutil::BlockIsReachableInItsFunction(GetIRContext(), block)) {
return;
}
// It must be valid to insert OpStore and OpLoad instructions
// before the instruction to insert before.
if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(
SpvOpStore, instruction_iterator) ||
!fuzzerutil::CanInsertOpcodeBeforeInstruction(
SpvOpLoad, instruction_iterator)) {
return;
}
// Randomly decides whether a global or local variable will be added.
auto variable_storage_class = GetFuzzerContext()->ChooseEven()
? SpvStorageClassPrivate
: SpvStorageClassFunction;
// Gets the available basic and pointer types.
auto basic_type_ids_and_pointers =
GetAvailableBasicTypesAndPointers(variable_storage_class);
auto& basic_types = basic_type_ids_and_pointers.first;
uint32_t basic_type_id =
basic_types[GetFuzzerContext()->RandomIndex(basic_types)];
// Looks for ids that we might wish to consider pushing through a
// variable.
std::vector<opt::Instruction*> value_instructions =
FindAvailableInstructions(
function, block, instruction_iterator,
[basic_type_id](opt::IRContext* /*unused*/,
opt::Instruction* instruction) -> bool {
if (!instruction->result_id() || !instruction->type_id()) {
return false;
}
return instruction->type_id() == basic_type_id;
});
if (value_instructions.empty()) {
return;
}
// If the pointer type does not exist, then create it.
FindOrCreatePointerType(basic_type_id, variable_storage_class);
// Applies the push id through variable transformation.
ApplyTransformation(TransformationPushIdThroughVariable(
value_instructions[GetFuzzerContext()->RandomIndex(
value_instructions)]
->result_id(),
GetFuzzerContext()->GetFreshId(), GetFuzzerContext()->GetFreshId(),
variable_storage_class, instruction_descriptor));
});
}
} // namespace fuzz
} // namespace spvtools
<commit_msg>Add value instruction condition (#3385)<commit_after>// Copyright (c) 2020 André Perez Maselco
//
// 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 "source/fuzz/fuzzer_pass_push_ids_through_variables.h"
#include "source/fuzz/fuzzer_util.h"
#include "source/fuzz/instruction_descriptor.h"
#include "source/fuzz/transformation_push_id_through_variable.h"
namespace spvtools {
namespace fuzz {
FuzzerPassPushIdsThroughVariables::FuzzerPassPushIdsThroughVariables(
opt::IRContext* ir_context, TransformationContext* transformation_context,
FuzzerContext* fuzzer_context,
protobufs::TransformationSequence* transformations)
: FuzzerPass(ir_context, transformation_context, fuzzer_context,
transformations) {}
FuzzerPassPushIdsThroughVariables::~FuzzerPassPushIdsThroughVariables() =
default;
void FuzzerPassPushIdsThroughVariables::Apply() {
ForEachInstructionWithInstructionDescriptor(
[this](opt::Function* function, opt::BasicBlock* block,
opt::BasicBlock::iterator instruction_iterator,
const protobufs::InstructionDescriptor& instruction_descriptor)
-> void {
assert(instruction_iterator->opcode() ==
instruction_descriptor.target_instruction_opcode() &&
"The opcode of the instruction we might insert before must be "
"the same as the opcode in the descriptor for the instruction");
// Randomly decide whether to try pushing an id through a variable.
if (!GetFuzzerContext()->ChoosePercentage(
GetFuzzerContext()->GetChanceOfPushingIdThroughVariable())) {
return;
}
// The block containing the instruction we are going to insert before
// must be reachable.
if (!fuzzerutil::BlockIsReachableInItsFunction(GetIRContext(), block)) {
return;
}
// It must be valid to insert OpStore and OpLoad instructions
// before the instruction to insert before.
if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(
SpvOpStore, instruction_iterator) ||
!fuzzerutil::CanInsertOpcodeBeforeInstruction(
SpvOpLoad, instruction_iterator)) {
return;
}
// Randomly decides whether a global or local variable will be added.
auto variable_storage_class = GetFuzzerContext()->ChooseEven()
? SpvStorageClassPrivate
: SpvStorageClassFunction;
// Gets the available basic and pointer types.
auto basic_type_ids_and_pointers =
GetAvailableBasicTypesAndPointers(variable_storage_class);
auto& basic_types = basic_type_ids_and_pointers.first;
uint32_t basic_type_id =
basic_types[GetFuzzerContext()->RandomIndex(basic_types)];
// Looks for ids that we might wish to consider pushing through a
// variable.
std::vector<opt::Instruction*> value_instructions =
FindAvailableInstructions(
function, block, instruction_iterator,
[basic_type_id, instruction_descriptor](
opt::IRContext* ir_context,
opt::Instruction* instruction) -> bool {
if (!instruction->result_id() || !instruction->type_id()) {
return false;
}
if (instruction->type_id() != basic_type_id) {
return false;
}
return fuzzerutil::IdIsAvailableBeforeInstruction(
ir_context,
FindInstruction(instruction_descriptor, ir_context),
instruction->result_id());
});
if (value_instructions.empty()) {
return;
}
// If the pointer type does not exist, then create it.
FindOrCreatePointerType(basic_type_id, variable_storage_class);
// Applies the push id through variable transformation.
ApplyTransformation(TransformationPushIdThroughVariable(
value_instructions[GetFuzzerContext()->RandomIndex(
value_instructions)]
->result_id(),
GetFuzzerContext()->GetFreshId(), GetFuzzerContext()->GetFreshId(),
variable_storage_class, instruction_descriptor));
});
}
} // namespace fuzz
} // namespace spvtools
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "stx/io/filerepository.h"
#include "stx/io/fileutil.h"
#include "stx/application.h"
#include "stx/logging.h"
#include "stx/random.h"
#include "stx/thread/eventloop.h"
#include "stx/thread/threadpool.h"
#include "stx/wallclock.h"
#include "stx/rpc/ServerGroup.h"
#include "stx/rpc/RPC.h"
#include "stx/rpc/RPCClient.h"
#include "stx/cli/flagparser.h"
#include "stx/json/json.h"
#include "stx/json/jsonrpc.h"
#include "stx/http/httprouter.h"
#include "stx/http/httpserver.h"
#include "stx/stats/statsdagent.h"
#include "stx/http/httpconnectionpool.h"
#include "stx/mdb/MDB.h"
#include "logjoin/LogJoin.h"
#include "logjoin/SessionProcessor.h"
#include "logjoin/stages/SessionJoin.h"
#include "logjoin/stages/BuildSessionAttributes.h"
#include "logjoin/stages/NormalizeQueryStrings.h"
#include "logjoin/stages/DebugPrintStage.h"
#include "logjoin/stages/DeliverWebhookStage.h"
#include "logjoin/stages/TSDBUploadStage.h"
#include "inventory/DocStore.h"
#include "inventory/IndexChangeRequest.h"
#include "inventory/DocIndex.h"
#include <inventory/ItemRef.h>
#include <fnord-fts/Analyzer.h>
#include "common/CustomerDirectory.h"
#include "common/SessionSchema.h"
#include "common.h"
using namespace cm;
using namespace stx;
stx::thread::EventLoop ev;
cm::LogJoin* logjoin_instance;
void quit(int n) {
logjoin_instance->shutdown();
}
int main(int argc, const char** argv) {
stx::Application::init();
stx::Application::logToStderr();
stx::cli::FlagParser flags;
flags.defineFlag(
"conf",
cli::FlagParser::T_STRING,
false,
NULL,
"./conf",
"conf directory",
"<path>");
flags.defineFlag(
"cdb",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"data dir",
"<path>");
flags.defineFlag(
"datadir",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"data dir",
"<path>");
flags.defineFlag(
"index",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"index directory",
"<path>");
flags.defineFlag(
"tsdb_addr",
stx::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"upload target url",
"<addr>");
flags.defineFlag(
"broker_addr",
stx::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"upload target url",
"<addr>");
flags.defineFlag(
"statsd_addr",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"127.0.0.1:8192",
"Statsd addr",
"<addr>");
flags.defineFlag(
"batch_size",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"8192",
"batch_size",
"<num>");
flags.defineFlag(
"buffer_size",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"32000",
"buffer_size",
"<num>");
flags.defineFlag(
"flush_interval",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"30",
"flush_interval",
"<num>");
flags.defineFlag(
"db_size",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"128",
"max sessiondb size",
"<MB>");
flags.defineFlag(
"no_dryrun",
stx::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"no dryrun",
"<bool>");
flags.defineFlag(
"shard",
stx::cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"shard",
"<name>");
flags.defineFlag(
"loglevel",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
auto dry_run = !flags.isSet("no_dryrun");
/* start event loop */
auto evloop_thread = std::thread([] {
ev.run();
});
http::HTTPConnectionPool http(&ev);
/* start stats reporting */
stx::stats::StatsdAgent statsd_agent(
stx::InetAddr::resolve(flags.getString("statsd_addr")),
10 * stx::kMicrosPerSecond);
statsd_agent.start();
/* get logjoin shard */
cm::LogJoinShardMap shard_map;
auto shard = shard_map.getShard(flags.getString("shard"));
/* open customer directory */
CustomerDirectory customer_dir(flags.getString("cdb"));
customer_dir.updateCustomerConfig(createCustomerConfig("dawanda"));
HashMap<String, URI> input_feeds;
input_feeds.emplace(
"tracker_log.feedserver02.nue01.production.fnrd.net",
URI("http://s02.nue01.production.fnrd.net:7001/rpc"));
input_feeds.emplace(
"tracker_log.feedserver03.production.fnrd.net",
URI("http://nue03.prod.fnrd.net:7001/rpc"));
/* set up session processing pipeline */
cm::SessionProcessor session_proc(&customer_dir);
/* pipeline stage: session join */
session_proc.addPipelineStage(
std::bind(&SessionJoin::process, std::placeholders::_1));
/* pipeline stage: BuildSessionAttributes */
session_proc.addPipelineStage(
std::bind(&BuildSessionAttributes::process, std::placeholders::_1));
/* pipeline stage: NormalizeQueryStrings */
//stx::fts::Analyzer analyzer(flags.getString("conf"));
//session_proc.addPipelineStage(
// std::bind(
// &NormalizeQueryStrings::process,
// NormalizeQueryStrings::NormalizeFn(
// std::bind(
// &stx::fts::Analyzer::normalize,
// &analyzer,
// std::placeholders::_1,
// std::placeholders::_2)),
// std::placeholders::_1));
//session_proc.addPipelineStage(
// std::bind(&DebugPrintStage::process, std::placeholders::_1));
/* pipeline stage: TSDBUpload */
session_proc.addPipelineStage(
std::bind(
&TSDBUploadStage::process,
std::placeholders::_1,
flags.getString("tsdb_addr"),
&http));
/* pipeline stage: DeliverWebHook */
session_proc.addPipelineStage(
std::bind(&DeliverWebhookStage::process, std::placeholders::_1));
/* open session db */
mdb::MDBOptions mdb_opts;
mdb_opts.maxsize = 1000000 * flags.getInt("db_size"),
mdb_opts.data_filename = shard.shard_name + ".db",
mdb_opts.lock_filename = shard.shard_name + ".db.lck",
auto sessdb = mdb::MDB::open(flags.getString("datadir"), mdb_opts);
/* setup logjoin */
cm::LogJoin logjoin(shard, dry_run, sessdb, &session_proc, &ev);
logjoin.exportStats("/logjoind/global");
logjoin.exportStats(StringUtil::format("/logjoind/$0", shard.shard_name));
/* shutdown hook */
logjoin_instance = &logjoin;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = quit;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
/* run logjoin */
stx::logInfo(
"logjoind",
"Starting logjoind\n dry_run=$0\n shard=$1, [$2, $3) of [0, $4]",
dry_run,
shard.shard_name,
shard.begin,
shard.end,
cm::LogJoinShard::modulo);
session_proc.start();
logjoin.processClickstream(
input_feeds,
flags.getInt("batch_size"),
flags.getInt("buffer_size"),
flags.getInt("flush_interval") * kMicrosPerSecond);
/* shutdown */
stx::logInfo("logjoind", "LogJoin exiting...");
ev.shutdown();
evloop_thread.join();
sessdb->sync();
session_proc.stop();
exit(0);
}
<commit_msg>sneaky syntax fix<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "stx/io/filerepository.h"
#include "stx/io/fileutil.h"
#include "stx/application.h"
#include "stx/logging.h"
#include "stx/random.h"
#include "stx/thread/eventloop.h"
#include "stx/thread/threadpool.h"
#include "stx/wallclock.h"
#include "stx/rpc/ServerGroup.h"
#include "stx/rpc/RPC.h"
#include "stx/rpc/RPCClient.h"
#include "stx/cli/flagparser.h"
#include "stx/json/json.h"
#include "stx/json/jsonrpc.h"
#include "stx/http/httprouter.h"
#include "stx/http/httpserver.h"
#include "stx/stats/statsdagent.h"
#include "stx/http/httpconnectionpool.h"
#include "stx/mdb/MDB.h"
#include "logjoin/LogJoin.h"
#include "logjoin/SessionProcessor.h"
#include "logjoin/stages/SessionJoin.h"
#include "logjoin/stages/BuildSessionAttributes.h"
#include "logjoin/stages/NormalizeQueryStrings.h"
#include "logjoin/stages/DebugPrintStage.h"
#include "logjoin/stages/DeliverWebhookStage.h"
#include "logjoin/stages/TSDBUploadStage.h"
#include "inventory/DocStore.h"
#include "inventory/IndexChangeRequest.h"
#include "inventory/DocIndex.h"
#include <inventory/ItemRef.h>
#include <fnord-fts/Analyzer.h>
#include "common/CustomerDirectory.h"
#include "common/SessionSchema.h"
#include "common.h"
using namespace cm;
using namespace stx;
stx::thread::EventLoop ev;
cm::LogJoin* logjoin_instance;
void quit(int n) {
logjoin_instance->shutdown();
}
int main(int argc, const char** argv) {
stx::Application::init();
stx::Application::logToStderr();
stx::cli::FlagParser flags;
flags.defineFlag(
"conf",
cli::FlagParser::T_STRING,
false,
NULL,
"./conf",
"conf directory",
"<path>");
flags.defineFlag(
"cdb",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"data dir",
"<path>");
flags.defineFlag(
"datadir",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"data dir",
"<path>");
flags.defineFlag(
"index",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"index directory",
"<path>");
flags.defineFlag(
"tsdb_addr",
stx::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"upload target url",
"<addr>");
flags.defineFlag(
"broker_addr",
stx::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"upload target url",
"<addr>");
flags.defineFlag(
"statsd_addr",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"127.0.0.1:8192",
"Statsd addr",
"<addr>");
flags.defineFlag(
"batch_size",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"8192",
"batch_size",
"<num>");
flags.defineFlag(
"buffer_size",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"32000",
"buffer_size",
"<num>");
flags.defineFlag(
"flush_interval",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"30",
"flush_interval",
"<num>");
flags.defineFlag(
"db_size",
stx::cli::FlagParser::T_INTEGER,
false,
NULL,
"128",
"max sessiondb size",
"<MB>");
flags.defineFlag(
"no_dryrun",
stx::cli::FlagParser::T_SWITCH,
false,
NULL,
NULL,
"no dryrun",
"<bool>");
flags.defineFlag(
"shard",
stx::cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"shard",
"<name>");
flags.defineFlag(
"loglevel",
stx::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
auto dry_run = !flags.isSet("no_dryrun");
/* start event loop */
auto evloop_thread = std::thread([] {
ev.run();
});
http::HTTPConnectionPool http(&ev);
/* start stats reporting */
stx::stats::StatsdAgent statsd_agent(
stx::InetAddr::resolve(flags.getString("statsd_addr")),
10 * stx::kMicrosPerSecond);
statsd_agent.start();
/* get logjoin shard */
cm::LogJoinShardMap shard_map;
auto shard = shard_map.getShard(flags.getString("shard"));
/* open customer directory */
CustomerDirectory customer_dir(flags.getString("cdb"));
customer_dir.updateCustomerConfig(createCustomerConfig("dawanda"));
HashMap<String, URI> input_feeds;
input_feeds.emplace(
"tracker_log.feedserver02.nue01.production.fnrd.net",
URI("http://s02.nue01.production.fnrd.net:7001/rpc"));
input_feeds.emplace(
"tracker_log.feedserver03.production.fnrd.net",
URI("http://nue03.prod.fnrd.net:7001/rpc"));
/* set up session processing pipeline */
cm::SessionProcessor session_proc(&customer_dir);
/* pipeline stage: session join */
session_proc.addPipelineStage(
std::bind(&SessionJoin::process, std::placeholders::_1));
/* pipeline stage: BuildSessionAttributes */
session_proc.addPipelineStage(
std::bind(&BuildSessionAttributes::process, std::placeholders::_1));
/* pipeline stage: NormalizeQueryStrings */
//stx::fts::Analyzer analyzer(flags.getString("conf"));
//session_proc.addPipelineStage(
// std::bind(
// &NormalizeQueryStrings::process,
// NormalizeQueryStrings::NormalizeFn(
// std::bind(
// &stx::fts::Analyzer::normalize,
// &analyzer,
// std::placeholders::_1,
// std::placeholders::_2)),
// std::placeholders::_1));
//session_proc.addPipelineStage(
// std::bind(&DebugPrintStage::process, std::placeholders::_1));
/* pipeline stage: TSDBUpload */
session_proc.addPipelineStage(
std::bind(
&TSDBUploadStage::process,
std::placeholders::_1,
flags.getString("tsdb_addr"),
&http));
/* pipeline stage: DeliverWebHook */
session_proc.addPipelineStage(
std::bind(&DeliverWebhookStage::process, std::placeholders::_1));
/* open session db */
mdb::MDBOptions mdb_opts;
mdb_opts.maxsize = 1000000 * flags.getInt("db_size");
mdb_opts.data_filename = shard.shard_name + ".db";
mdb_opts.lock_filename = shard.shard_name + ".db.lck";
auto sessdb = mdb::MDB::open(flags.getString("datadir"), mdb_opts);
/* setup logjoin */
cm::LogJoin logjoin(shard, dry_run, sessdb, &session_proc, &ev);
logjoin.exportStats("/logjoind/global");
logjoin.exportStats(StringUtil::format("/logjoind/$0", shard.shard_name));
/* shutdown hook */
logjoin_instance = &logjoin;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = quit;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
/* run logjoin */
stx::logInfo(
"logjoind",
"Starting logjoind\n dry_run=$0\n shard=$1, [$2, $3) of [0, $4]",
dry_run,
shard.shard_name,
shard.begin,
shard.end,
cm::LogJoinShard::modulo);
session_proc.start();
logjoin.processClickstream(
input_feeds,
flags.getInt("batch_size"),
flags.getInt("buffer_size"),
flags.getInt("flush_interval") * kMicrosPerSecond);
/* shutdown */
stx::logInfo("logjoind", "LogJoin exiting...");
ev.shutdown();
evloop_thread.join();
sessdb->sync();
session_proc.stop();
exit(0);
}
<|endoftext|> |
<commit_before>/*
* opencog/comboreduct/main/combo-fmt-converter.cc
*
* Copyright (C) 2015 OpenCog Foundation
* All Rights Reserved
*
* Written by Nil Geisweiller
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <fstream>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "../combo/iostream_combo.h"
#include "../type_checker/type_tree.h"
using namespace boost::program_options;
using namespace boost::algorithm;
using namespace std;
using namespace opencog;
using namespace combo;
// using namespace ant_combo;
// Structure containing the options for the combo-fmt-converter program
struct pgrParameters
{
vector<string> combo_programs;
vector<string> combo_programs_files;
string output_file;
string output_format_str;
};
/**
* Read and parse the combo-fmt-converter program arguments.
* Return the parsed results in the parameters struct.
*/
pgrParameters parse_program_args(int argc, char** argv)
{
// program options, see options_description below for their meaning
pgrParameters pa;
// Declare the supported options.
options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce help message.\n")
("combo-program,c",
value<vector<string>>(&pa.combo_programs),
"Alternative way to entering the programs to convert "
"(as opposed to via stdin, not that using this option will "
"disable reading on the stdin). "
"Remember to escape the $ signs or to wrap them in single "
"quotes as to not let the shell perform variable expansions "
"on the combo program variables."
"This option may be "
"used several times to convert several programs.\n")
("combo-programs-file,C",
value<vector<string>>(&pa.combo_programs_files),
"Other alternative way (disables stdin). "
"Indicate the path of a file containing combo "
"programs (seperated by newlines) to convert. "
"This option may be used several times to progress several "
"files.\n")
("output-file,o",
value<string>(&pa.output_file),
"File where to save the results. If empty then outputs on "
"stdout.\n")
("output-format,f",
value<string>(&pa.output_format_str)->default_value("combo"),
"Supported output formats are combo, python and scheme.\n")
;
variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if (vm.count("help") || argc == 1) {
cout << desc << "\n";
exit(1);
}
return pa;
}
vector<string> get_all_combo_tree_str(const pgrParameters& pa)
{
vector<string> res(pa.combo_programs); // from command line
// from files
for (const string& combo_programs_file : pa.combo_programs_files) {
ifstream in(combo_programs_file.c_str());
if (in) {
while (in.good()) {
string line;
getline(in, line);
if (line.empty())
continue;
res.push_back(line);
}
} else {
logger().error("Error: file %s can not be found.",
combo_programs_file.c_str());
exit(1);
}
}
return res;
}
void output_tree(const pgrParameters& pa,
const combo_tree& tr,
const vector<string>& vars,
combo::output_format fmt)
{
if(pa.output_file.empty())
ostream_combo_tree(cout, tr, vars, fmt) << std::endl;
else {
ofstream of(pa.output_file.c_str());
ostream_combo_tree(of, tr, vars, fmt) << std::endl;
}
}
// Convert a single combo program gotten from istream
istream& convert(istream& in, const pgrParameters& pa,
combo::output_format fmt) {
// Parse combo tree
string line;
getline(in, line);
if (line.empty())
return in;
// Remove useless wrapping double quotes
if (starts_with(line, "\"") and ends_with(line, "\""))
line = line.substr(1, line.size() - 2);
vector<string> variables = parse_combo_variables(line);
combo_tree tr = str2combo_tree(line, variables);
type_tree tt = infer_type_tree(tr);
// Write to the right format
output_tree(pa, tr, variables, fmt);
return in;
}
int main(int argc, char** argv)
{
pgrParameters pa = parse_program_args(argc, argv);
// Parse output format
combo::output_format fmt = parse_output_format(pa.output_format_str);
// read combo program strings given by an alternative way than
// stdin
vector<string> combo_trees_str = get_all_combo_tree_str(pa);
if (combo_trees_str.empty()) {
// If empty then use stdin
while (cin.good())
convert(cin, pa, fmt);
} else {
// Don't use stdin
for (const string& str : combo_trees_str) {
stringstream ss(str);
convert(ss, pa, fmt);
}
}
return 0;
}
<commit_msg>Fix bug related to overwriting the last model + output thrown exceptions<commit_after>/*
* opencog/comboreduct/main/combo-fmt-converter.cc
*
* Copyright (C) 2015 OpenCog Foundation
* All Rights Reserved
*
* Written by Nil Geisweiller
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <fstream>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
#include "../combo/iostream_combo.h"
#include "../type_checker/type_tree.h"
using namespace boost::program_options;
using namespace boost::algorithm;
using namespace std;
using namespace opencog;
using namespace combo;
using boost::trim;
// using namespace ant_combo;
// Structure containing the options for the combo-fmt-converter program
struct pgrParameters
{
vector<string> combo_programs;
vector<string> combo_programs_files;
string log_level;
string output_file;
string output_format_str;
};
/**
* Read and parse the combo-fmt-converter program arguments.
* Return the parsed results in the parameters struct.
*/
pgrParameters parse_program_args(int argc, char** argv)
{
// program options, see options_description below for their meaning
pgrParameters pa;
// Declare the supported options.
options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce help message.\n")
("combo-program,c",
value<vector<string>>(&pa.combo_programs),
"Alternative way to entering the programs to convert "
"(as opposed to via stdin, not that using this option will "
"disable reading on the stdin). "
"Remember to escape the $ signs or to wrap them in single "
"quotes as to not let the shell perform variable expansions "
"on the combo program variables."
"This option may be "
"used several times to convert several programs.\n")
("log-level,l",
value<string>(&pa.log_level)->default_value("INFO"),
"Log level, possible levels are NONE, ERROR, WARN, INFO, "
"DEBUG, FINE. Case does not matter.\n")
("combo-programs-file,C",
value<vector<string>>(&pa.combo_programs_files),
"Other alternative way (disables stdin). "
"Indicate the path of a file containing combo "
"programs (seperated by newlines) to convert. "
"This option may be used several times to progress several "
"files.\n")
("output-file,o",
value<string>(&pa.output_file),
"File where to save the results. If empty then outputs on "
"stdout.\n")
("output-format,f",
value<string>(&pa.output_format_str)->default_value("combo"),
"Supported output formats are combo, python and scheme.\n")
;
variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);
if (vm.count("help") || argc == 1) {
cout << desc << "\n";
exit(1);
}
// Remove old log_file before setting the new one.
const string log_filename = "combo-fmt-converter.log";
remove(log_filename.c_str());
logger().setFilename(log_filename);
trim(pa.log_level);
Logger::Level level = logger().getLevelFromString(pa.log_level);
if (level != Logger::BAD_LEVEL)
logger().setLevel(level);
else {
cerr << "Error: Log level " << pa.log_level
<< " is incorrect (see --help)." << endl;
exit(1);
}
logger().setBackTraceLevel(Logger::ERROR);
logger().setPrintErrorLevelStdout();
return pa;
}
vector<string> get_all_combo_tree_str(const pgrParameters& pa)
{
vector<string> res(pa.combo_programs); // from command line
// from files
for (const string& combo_programs_file : pa.combo_programs_files) {
ifstream in(combo_programs_file.c_str());
if (in) {
while (in.good()) {
string line;
getline(in, line);
if (line.empty())
continue;
res.push_back(line);
}
} else {
logger().error("Error: file %s can not be found.",
combo_programs_file.c_str());
exit(1);
}
}
return res;
}
// Convert a single combo program gotten from istream
void convert(istream& in, ostream& out,
const pgrParameters& pa,
combo::output_format fmt) {
// Parse combo tree
string line;
getline(in, line);
if (line.empty())
return;
// Remove useless wrapping double quotes
if (starts_with(line, "\"") and ends_with(line, "\""))
line = line.substr(1, line.size() - 2);
vector<string> variables = parse_combo_variables(line);
combo_tree tr = str2combo_tree(line, variables);
type_tree tt = infer_type_tree(tr);
// Write to the right format
ostream_combo_tree(out, tr, variables, fmt) << std::endl;
}
int main(int argc, char** argv)
{
// Parse program options
pgrParameters pa = parse_program_args(argc, argv);
// Parse output format
combo::output_format fmt = parse_output_format(pa.output_format_str);
// read combo program strings given by an alternative way than
// stdin
vector<string> combo_trees_str = get_all_combo_tree_str(pa);
ostream* out = pa.output_file.empty()?
&cout : new ofstream(pa.output_file.c_str());
if (combo_trees_str.empty()) {
// If empty then use stdin
while (cin.good())
convert(cin, *out, pa, fmt);
} else {
// Don't use stdin
for (const string& str : combo_trees_str) {
stringstream ss(str);
convert(ss, *out, pa, fmt);
}
}
if (not pa.output_file.empty())
delete out;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2014-2017 The MexicanCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "masternode.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "protocol.h"
extern CWallet* pwalletMain;
// Keep track of the active Masternode
CActiveMasternode activeMasternode;
void CActiveMasternode::ManageState()
{
LogPrint("masternode", "CActiveMasternode::ManageState -- Start\n");
if(!fMasterNode) {
LogPrint("masternode", "CActiveMasternode::ManageState -- Not a masternode, returning\n");
return;
}
if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {
nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;
LogPrintf("CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus());
return;
}
if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) {
nState = ACTIVE_MASTERNODE_INITIAL;
}
LogPrint("masternode", "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
if(eType == MASTERNODE_UNKNOWN) {
ManageStateInitial();
}
if(eType == MASTERNODE_REMOTE) {
ManageStateRemote();
} else if(eType == MASTERNODE_LOCAL) {
// Try Remote Start first so the started local masternode can be restarted without recreate masternode broadcast.
ManageStateRemote();
if(nState != ACTIVE_MASTERNODE_STARTED)
ManageStateLocal();
}
SendMasternodePing();
}
std::string CActiveMasternode::GetStateString() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL:
return "INITIAL";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS:
return "SYNC_IN_PROCESS";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW:
return "INPUT_TOO_NEW";
case ACTIVE_MASTERNODE_NOT_CAPABLE:
return "NOT_CAPABLE";
case ACTIVE_MASTERNODE_STARTED:
return "STARTED";
default:
return "UNKNOWN";
}
}
std::string CActiveMasternode::GetStatus() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL:
return "Node just started, not yet activated";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS:
return "Sync in progress. Must wait until sync is complete to start Masternode";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW:
return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations);
case ACTIVE_MASTERNODE_NOT_CAPABLE:
return "Not capable masternode: " + strNotCapableReason;
case ACTIVE_MASTERNODE_STARTED:
return "Masternode successfully started";
default:
return "Unknown";
}
}
std::string CActiveMasternode::GetTypeString() const
{
std::string strType;
switch(eType) {
case MASTERNODE_UNKNOWN:
strType = "UNKNOWN";
break;
case MASTERNODE_REMOTE:
strType = "REMOTE";
break;
case MASTERNODE_LOCAL:
strType = "LOCAL";
break;
default:
strType = "UNKNOWN";
break;
}
return strType;
}
bool CActiveMasternode::SendMasternodePing()
{
if(!fPingerEnabled) {
LogPrint("masternode", "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString());
return false;
}
if(!mnodeman.Has(vin)) {
strNotCapableReason = "Masternode not in masternode list";
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
LogPrintf("CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason);
return false;
}
CMasternodePing mnp(vin);
if(!mnp.Sign(keyMasternode, pubKeyMasternode)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n");
return false;
}
// Update lastPing for our masternode in Masternode list
if(mnodeman.IsMasternodePingedWithin(vin, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n");
return false;
}
mnodeman.SetMasternodeLastPing(vin, mnp);
LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", vin.ToString());
mnp.Relay();
return true;
}
void CActiveMasternode::ManageStateInitial()
{
LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
// Check that our local network configuration is correct
if (!fListen) {
// listen option is probably overwritten by smth else, no good
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
bool fFoundLocal = false;
{
LOCK(cs_vNodes);
// First try to find whatever local address is specified by externalip option
fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service);
if(!fFoundLocal) {
// nothing and no live connections, can't do anything for now
if (vNodes.empty()) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// We have some peers, let's try to find our local address from one of them
BOOST_FOREACH(CNode* pnode, vNodes) {
if (pnode->fSuccessfullyConnected && pnode->addr.IsIPv4()) {
fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service);
if(fFoundLocal) break;
}
}
}
}
if(!fFoundLocal) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
if(service.GetPort() != mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
} else if(service.GetPort() == mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
LogPrintf("CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString());
if(!ConnectNode((CAddress)service, NULL, true)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Could not connect to " + service.ToString();
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// Default to REMOTE
eType = MASTERNODE_REMOTE;
// Check if wallet funds are available
if(!pwalletMain) {
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet not available\n", GetStateString());
return;
}
if(pwalletMain->IsLocked()) {
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet is locked\n", GetStateString());
return;
}
if(pwalletMain->GetBalance() < 500000 * COIN) {
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet balance is < 500000 MUE\n", GetStateString());
return;
}
// Choose coins to use
CPubKey pubKeyCollateral;
CKey keyCollateral;
// If collateral is found switch to LOCAL mode
if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) {
eType = MASTERNODE_LOCAL;
}
LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
}
void CActiveMasternode::ManageStateRemote()
{
LogPrint("masternode", "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n",
GetStatus(), fPingerEnabled, GetTypeString(), pubKeyMasternode.GetID().ToString());
mnodeman.CheckMasternode(pubKeyMasternode);
masternode_info_t infoMn = mnodeman.GetMasternodeInfo(pubKeyMasternode);
if(infoMn.fInfoValid) {
if(infoMn.nProtocolVersion != PROTOCOL_VERSION) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Invalid protocol version";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(service != infoMn.addr) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently.";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState));
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(nState != ACTIVE_MASTERNODE_STARTED) {
LogPrintf("CActiveMasternode::ManageStateRemote -- STARTED!\n");
vin = infoMn.vin;
service = infoMn.addr;
fPingerEnabled = true;
nState = ACTIVE_MASTERNODE_STARTED;
}
}
else {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode not in masternode list";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
}
}
void CActiveMasternode::ManageStateLocal()
{
LogPrint("masternode", "CActiveMasternode::ManageStateLocal -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
if(nState == ACTIVE_MASTERNODE_STARTED) {
return;
}
// Choose coins to use
CPubKey pubKeyCollateral;
CKey keyCollateral;
if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) {
int nInputAge = GetInputAge(vin);
if(nInputAge < Params().GetConsensus().nMasternodeMinimumConfirmations) {
nState = ACTIVE_MASTERNODE_INPUT_TOO_NEW;
strNotCapableReason = strprintf(_("%s - %d confirmations"), GetStatus(), nInputAge);
LogPrintf("CActiveMasternode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->LockCoin(vin.prevout);
}
CMasternodeBroadcast mnb;
std::string strError;
if(!CMasternodeBroadcast::Create(vin, service, keyCollateral, pubKeyCollateral, keyMasternode, pubKeyMasternode, strError, mnb)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Error creating mastenode broadcast: " + strError;
LogPrintf("CActiveMasternode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
fPingerEnabled = true;
nState = ACTIVE_MASTERNODE_STARTED;
//update to masternode list
LogPrintf("CActiveMasternode::ManageStateLocal -- Update Masternode List\n");
mnodeman.UpdateMasternodeList(mnb);
mnodeman.NotifyMasternodeUpdates();
//send to all peers
LogPrintf("CActiveMasternode::ManageStateLocal -- Relay broadcast, vin=%s\n", vin.ToString());
mnb.Relay();
}
}
<commit_msg>Update activemasternode.cpp<commit_after>// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2014-2017 The MexicanCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "masternode.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "protocol.h"
extern CWallet* pwalletMain;
// Keep track of the active Masternode
CActiveMasternode activeMasternode;
void CActiveMasternode::ManageState()
{
LogPrint("masternode", "CActiveMasternode::ManageState -- Start\n");
if(!fMasterNode) {
LogPrint("masternode", "CActiveMasternode::ManageState -- Not a masternode, returning\n");
return;
}
if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {
nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;
LogPrintf("CActiveMasternode::ManageState -- %s: %s\n", GetStateString(), GetStatus());
return;
}
if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) {
nState = ACTIVE_MASTERNODE_INITIAL;
}
LogPrint("masternode", "CActiveMasternode::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
if(eType == MASTERNODE_UNKNOWN) {
ManageStateInitial();
}
if(eType == MASTERNODE_REMOTE) {
ManageStateRemote();
} else if(eType == MASTERNODE_LOCAL) {
// Try Remote Start first so the started local masternode can be restarted without recreate masternode broadcast.
ManageStateRemote();
if(nState != ACTIVE_MASTERNODE_STARTED)
ManageStateLocal();
}
SendMasternodePing();
}
std::string CActiveMasternode::GetStateString() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL:
return "INITIAL";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS:
return "SYNC_IN_PROCESS";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW:
return "INPUT_TOO_NEW";
case ACTIVE_MASTERNODE_NOT_CAPABLE:
return "NOT_CAPABLE";
case ACTIVE_MASTERNODE_STARTED:
return "STARTED";
default:
return "UNKNOWN";
}
}
std::string CActiveMasternode::GetStatus() const
{
switch (nState) {
case ACTIVE_MASTERNODE_INITIAL:
return "Node just started, not yet activated";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS:
return "Sync in progress. Must wait until sync is complete to start Masternode";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW:
return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations);
case ACTIVE_MASTERNODE_NOT_CAPABLE:
return "Not capable masternode: " + strNotCapableReason;
case ACTIVE_MASTERNODE_STARTED:
return "Masternode successfully started";
default:
return "Unknown";
}
}
std::string CActiveMasternode::GetTypeString() const
{
std::string strType;
switch(eType) {
case MASTERNODE_UNKNOWN:
strType = "UNKNOWN";
break;
case MASTERNODE_REMOTE:
strType = "REMOTE";
break;
case MASTERNODE_LOCAL:
strType = "LOCAL";
break;
default:
strType = "UNKNOWN";
break;
}
return strType;
}
bool CActiveMasternode::SendMasternodePing()
{
if(!fPingerEnabled) {
LogPrint("masternode", "CActiveMasternode::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString());
return false;
}
if(!mnodeman.Has(vin)) {
strNotCapableReason = "Masternode not in masternode list";
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
LogPrintf("CActiveMasternode::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason);
return false;
}
CMasternodePing mnp(vin);
if(!mnp.Sign(keyMasternode, pubKeyMasternode)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n");
return false;
}
// Update lastPing for our masternode in Masternode list
if(mnodeman.IsMasternodePingedWithin(vin, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) {
LogPrintf("CActiveMasternode::SendMasternodePing -- Too early to send Masternode Ping\n");
return false;
}
mnodeman.SetMasternodeLastPing(vin, mnp);
LogPrintf("CActiveMasternode::SendMasternodePing -- Relaying ping, collateral=%s\n", vin.ToString());
mnp.Relay();
return true;
}
void CActiveMasternode::ManageStateInitial()
{
LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
// Check that our local network configuration is correct
if (!fListen) {
// listen option is probably overwritten by smth else, no good
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
bool fFoundLocal = false;
{
LOCK(cs_vNodes);
// First try to find whatever local address is specified by externalip option
fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service);
if(!fFoundLocal) {
// nothing and no live connections, can't do anything for now
if (vNodes.empty()) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// We have some peers, let's try to find our local address from one of them
BOOST_FOREACH(CNode* pnode, vNodes) {
if (pnode->fSuccessfullyConnected && pnode->addr.IsIPv4()) {
fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service);
if(fFoundLocal) break;
}
}
}
}
if(!fFoundLocal) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only.";
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
if(service.GetPort() != mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
} else if(service.GetPort() == mainnetDefaultPort) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", service.GetPort(), mainnetDefaultPort);
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
LogPrintf("CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString());
if(!ConnectNode((CAddress)service, NULL, true)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Could not connect to " + service.ToString();
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
// Default to REMOTE
eType = MASTERNODE_REMOTE;
// Check if wallet funds are available
if(!pwalletMain) {
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet not available\n", GetStateString());
return;
}
if(pwalletMain->IsLocked()) {
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet is locked\n", GetStateString());
return;
}
if(pwalletMain->GetBalance() < 1000 * COIN) {
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: Wallet balance is < 1000 MXN\n", GetStateString());
return;
}
// Choose coins to use
CPubKey pubKeyCollateral;
CKey keyCollateral;
// If collateral is found switch to LOCAL mode
if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) {
eType = MASTERNODE_LOCAL;
}
LogPrint("masternode", "CActiveMasternode::ManageStateInitial -- End status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
}
void CActiveMasternode::ManageStateRemote()
{
LogPrint("masternode", "CActiveMasternode::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, pubKeyMasternode.GetID() = %s\n",
GetStatus(), fPingerEnabled, GetTypeString(), pubKeyMasternode.GetID().ToString());
mnodeman.CheckMasternode(pubKeyMasternode);
masternode_info_t infoMn = mnodeman.GetMasternodeInfo(pubKeyMasternode);
if(infoMn.fInfoValid) {
if(infoMn.nProtocolVersion != PROTOCOL_VERSION) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Invalid protocol version";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(service != infoMn.addr) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently.";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState));
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
if(nState != ACTIVE_MASTERNODE_STARTED) {
LogPrintf("CActiveMasternode::ManageStateRemote -- STARTED!\n");
vin = infoMn.vin;
service = infoMn.addr;
fPingerEnabled = true;
nState = ACTIVE_MASTERNODE_STARTED;
}
}
else {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Masternode not in masternode list";
LogPrintf("CActiveMasternode::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason);
}
}
void CActiveMasternode::ManageStateLocal()
{
LogPrint("masternode", "CActiveMasternode::ManageStateLocal -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled);
if(nState == ACTIVE_MASTERNODE_STARTED) {
return;
}
// Choose coins to use
CPubKey pubKeyCollateral;
CKey keyCollateral;
if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateral, keyCollateral)) {
int nInputAge = GetInputAge(vin);
if(nInputAge < Params().GetConsensus().nMasternodeMinimumConfirmations) {
nState = ACTIVE_MASTERNODE_INPUT_TOO_NEW;
strNotCapableReason = strprintf(_("%s - %d confirmations"), GetStatus(), nInputAge);
LogPrintf("CActiveMasternode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
{
LOCK(pwalletMain->cs_wallet);
pwalletMain->LockCoin(vin.prevout);
}
CMasternodeBroadcast mnb;
std::string strError;
if(!CMasternodeBroadcast::Create(vin, service, keyCollateral, pubKeyCollateral, keyMasternode, pubKeyMasternode, strError, mnb)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Error creating mastenode broadcast: " + strError;
LogPrintf("CActiveMasternode::ManageStateLocal -- %s: %s\n", GetStateString(), strNotCapableReason);
return;
}
fPingerEnabled = true;
nState = ACTIVE_MASTERNODE_STARTED;
//update to masternode list
LogPrintf("CActiveMasternode::ManageStateLocal -- Update Masternode List\n");
mnodeman.UpdateMasternodeList(mnb);
mnodeman.NotifyMasternodeUpdates();
//send to all peers
LogPrintf("CActiveMasternode::ManageStateLocal -- Relay broadcast, vin=%s\n", vin.ToString());
mnb.Relay();
}
}
<|endoftext|> |
<commit_before>/**
* @file textfile.cc
*
* Implementations for the text-based file I/O helper classes.
*/
#include "textfile.h"
#include <ctype.h>
/*
char *TextTokenizer::ReadLine() {
char *buf = NULL;
size_t size = 0;
size_t len = 0;
const size_t extra = 64;
int c;
for (;;) {
c = getc(f_);
if (unlikely(c == '\r')) {
c = getc(f_);
if (c != '\n') {
ungetc(c, f_);
}
break;
} else if (unlikely(c == '\n')) {
break;
} else if (unlikely(c == EOF)) {
if (len == 0) {
return NULL;
} else {
break;
}
}
len++;
if (size <= len) {
size = len * 2 + extra;
buf = mem::Realloc(buf, size);
}
buf[len-1] = c;
}
if (len == 0) {
// special case: empty line
buf = mem::Alloc<char>(1);
}
buf[len] = '\0';
return buf;
}
*/
void TextLineReader::Error(const char *format, ...) {
va_list vl;
// TODO: Use a warning propagation system
fprintf(stderr, ".| %d: %s\nX| `-> ", line_num_, line_.c_str());
va_start(vl, format);
vfprintf(stderr, format, vl);
va_end(vl);
fprintf(stderr, "\n");
}
success_t TextLineReader::Open(const char *fname) {
f_ = fopen(fname, "r");
line_num_ = 0;
has_line_ = false;
line_.Init();
if (unlikely(f_ == NULL)) {
return SUCCESS_FAIL;
} else {
Gobble();
return SUCCESS_PASS;
}
}
bool TextLineReader::Gobble() {
char *ptr = ReadLine_();
line_.Destruct();
if (likely(ptr != NULL)) {
line_.Steal(ptr);
has_line_ = true;
line_num_++;
return true;
} else {
line_.Init();
has_line_ = false;
return false;
}
}
char *TextLineReader::ReadLine_() {
char *buf = NULL;
size_t size = 1;
size_t len = 0;
#ifdef DEBUG
const size_t extra = 10;
#else
const size_t extra = 80;
#endif
for (;;) {
size = size * 2 + extra;
buf = mem::Realloc(buf, size);
char *result = ::fgets(buf + len, size - len, f_);
if (len == 0 && result == NULL) {
mem::Free(buf);
return NULL;
}
len += strlen(buf + len);
if (len < size - 1 || buf[len - 1] == '\r' || buf[len - 1] == '\n') {
while (len && (buf[len-1] == '\r' || buf[len-1] == '\n')) {
len--;
}
buf[len] = '\0';
return buf;
}
}
}
success_t TextTokenizer::Open(const char *fname,
const char *comment_chars_in, const char *ident_extra_in,
int features_in) {
next_.Copy("");
cur_.Copy("");
next_type_ = END;
cur_type_ = END;
comment_start_ = comment_chars_in;
features_ = features_in;
ident_extra_ = ident_extra_in;
line_ = 1;
f_ = fopen(fname, "r");
if (unlikely(f_ == NULL)) {
return SUCCESS_FAIL;
} else {
Gobble();
return SUCCESS_PASS;
}
}
char TextTokenizer::NextChar_() {
int c = GetChar_();
if (c != EOF && unlikely(strchr(comment_start_, c) != NULL)) {
do {
c = GetChar_();
} while (likely(c != EOF) && likely(c != '\r') && likely(c != '\n'));
}
if (unlikely(c == EOF)) {
c = 0;
}
return c;
}
char TextTokenizer::NextChar_(ArrayList<char> *token) {
char c = NextChar_();
*token->AddBack() = c;
return c;
}
char TextTokenizer::Skip_(ArrayList<char> *token) {
int c;
while (1) {
c = NextChar_();
if (!isspace(c)) {
break;
}
if (c == '\r' || c == '\n') {
if (c == '\r') {
c = NextChar_();
if (c != '\n') {
Unget_(c);
}
}
line_++;
if ((features_ & WANT_NEWLINE)) {
c = '\n';
break;
}
}
}
*token->AddBack() = char(c);
return char(c);
}
void TextTokenizer::UndoNextChar_(ArrayList<char> *token) {
char c = *token->PopBackPtr();
if (c != 0) { /* don't put EOF back on the stream */
Unget_(c);
}
}
void Sanitize(const String& src, String* dest) {
dest->Init();
for (index_t i = 0; i < src.length(); i++) {
char c = src[i];
if (isgraph(c) || c == ' ' || c == '\t') {
*dest += c;
} else if (isspace(c)) {
*dest += "<whitespace>";
} else {
*dest += "<nonprint>";
}
}
}
void TextTokenizer::Error(const char *format, ...) {
va_list vl;
String cur_sanitized;
String next_sanitized;
Sanitize(cur_, &cur_sanitized);
Sanitize(next_, &next_sanitized);
// TODO: Use a warning propagation system
fprintf(stderr, ".| %d: %s <-HERE-> %s\nX| `-> ", line_,
cur_sanitized.c_str(), next_sanitized.c_str());
va_start(vl, format);
vfprintf(stderr, format, vl);
va_end(vl);
fprintf(stderr, "\n");
}
void TextTokenizer::Error_(const char *msg, const ArrayList<char>& token) {
next_type_ = INVALID;
printf("size is %"LI"d, token[0] = %d\n", token.size(), token[0]);
next_.Copy(token.begin(), token.size());
Error("%s", msg);
next_.Destruct();
}
void TextTokenizer::ScanNumber_(char c, ArrayList<char> *token) {
bool dot = false;
bool floating = false;
while (1) {
if (unlikely(c == '.')) {
/* handle a period */
if (unlikely(dot)) {
Error_("Multiple decimal points in a float", *token);
return;
}
dot = true;
floating = true;
} else if (likely(isdigit(c))) {
/* keep on processing digits */
} else if (unlikely(c == 'e' || c == 'E')) {
/* exponent - read exponent and finish */
c = NextChar_(token);
if (c == '+' || c == '-') {
c = NextChar_(token);
}
while (isdigit(c)) {
c = NextChar_(token);
}
floating = true;
break;
} else {
/* non numeric */
break;
}
c = NextChar_(token);
}
if (c == 'f' || c == 'F') {
// It's labelled a float. Gobble and go.
floating = true;
} else if (isspace(c) || ispunct(c)) {
UndoNextChar_(token);
} else {
Error_("Invalid character while parsing number", *token);
}
if (floating) {
next_type_ = DOUBLE;
} else {
next_type_ = INTEGER;
}
}
void TextTokenizer::ScanString_(char ending, ArrayList<char> *token) {
int c;
while (1) {
c = NextChar_(token);
if (c == 0) {
Error_("Unterminated String", *token);
UndoNextChar_(token);
return;
}
if (c == ending) {
next_type_ = STRING;
return;
}
}
}
void TextTokenizer::Scan_(ArrayList<char> *token) {
char c = Skip_(token);
if (c == 0) {
token->Clear();
next_type_ = END;
return;
} else if (c == '.' || isdigit(c)) {
ScanNumber_(c, token);
} else if (isident_begin_(c)) {
while (isident_rest_(NextChar_(token))) {}
UndoNextChar_(token);
next_type_ = IDENTIFIER;
} else if (ispunct(c) || isspace(c)) {
if (c == '"' || c == '\'') {
ScanString_(c, token);
} else if (c == '+' || c == '-') {
c = NextChar_(token);
if (c == '.' || isdigit(c)) {
ScanNumber_(c, token);
} else {
UndoNextChar_(token);
}
} else {
next_type_ = PUNCT;
}
} else {
Error_("Unknown Character", *token);
}
}
void TextTokenizer::Gobble() {
cur_.Destruct();
cur_.StealDestruct(&next_);
cur_type_ = next_type_;
ArrayList<char> token;
token.Init();
Scan_(&token);
*token.AddBack() = '\0';
next_.Steal(&token);
assert(next_.length() == index_t(strlen(next_.c_str())));
}
success_t TextWriter::Printf(const char *format, ...) {
int rv;
va_list vl;
va_start(vl, format);
rv = vfprintf(f_, format, vl);
va_end(vl);
return SUCCESS_FROM_C(rv);
}
<commit_msg>changed assert to DEBUG_ASSERT in textfile.cc<commit_after>/**
* @file textfile.cc
*
* Implementations for the text-based file I/O helper classes.
*/
#include "textfile.h"
#include <ctype.h>
/*
char *TextTokenizer::ReadLine() {
char *buf = NULL;
size_t size = 0;
size_t len = 0;
const size_t extra = 64;
int c;
for (;;) {
c = getc(f_);
if (unlikely(c == '\r')) {
c = getc(f_);
if (c != '\n') {
ungetc(c, f_);
}
break;
} else if (unlikely(c == '\n')) {
break;
} else if (unlikely(c == EOF)) {
if (len == 0) {
return NULL;
} else {
break;
}
}
len++;
if (size <= len) {
size = len * 2 + extra;
buf = mem::Realloc(buf, size);
}
buf[len-1] = c;
}
if (len == 0) {
// special case: empty line
buf = mem::Alloc<char>(1);
}
buf[len] = '\0';
return buf;
}
*/
void TextLineReader::Error(const char *format, ...) {
va_list vl;
// TODO: Use a warning propagation system
fprintf(stderr, ".| %d: %s\nX| `-> ", line_num_, line_.c_str());
va_start(vl, format);
vfprintf(stderr, format, vl);
va_end(vl);
fprintf(stderr, "\n");
}
success_t TextLineReader::Open(const char *fname) {
f_ = fopen(fname, "r");
line_num_ = 0;
has_line_ = false;
line_.Init();
if (unlikely(f_ == NULL)) {
return SUCCESS_FAIL;
} else {
Gobble();
return SUCCESS_PASS;
}
}
bool TextLineReader::Gobble() {
char *ptr = ReadLine_();
line_.Destruct();
if (likely(ptr != NULL)) {
line_.Steal(ptr);
has_line_ = true;
line_num_++;
return true;
} else {
line_.Init();
has_line_ = false;
return false;
}
}
char *TextLineReader::ReadLine_() {
char *buf = NULL;
size_t size = 1;
size_t len = 0;
#ifdef DEBUG
const size_t extra = 10;
#else
const size_t extra = 80;
#endif
for (;;) {
size = size * 2 + extra;
buf = mem::Realloc(buf, size);
char *result = ::fgets(buf + len, size - len, f_);
if (len == 0 && result == NULL) {
mem::Free(buf);
return NULL;
}
len += strlen(buf + len);
if (len < size - 1 || buf[len - 1] == '\r' || buf[len - 1] == '\n') {
while (len && (buf[len-1] == '\r' || buf[len-1] == '\n')) {
len--;
}
buf[len] = '\0';
return buf;
}
}
}
success_t TextTokenizer::Open(const char *fname,
const char *comment_chars_in, const char *ident_extra_in,
int features_in) {
next_.Copy("");
cur_.Copy("");
next_type_ = END;
cur_type_ = END;
comment_start_ = comment_chars_in;
features_ = features_in;
ident_extra_ = ident_extra_in;
line_ = 1;
f_ = fopen(fname, "r");
if (unlikely(f_ == NULL)) {
return SUCCESS_FAIL;
} else {
Gobble();
return SUCCESS_PASS;
}
}
char TextTokenizer::NextChar_() {
int c = GetChar_();
if (c != EOF && unlikely(strchr(comment_start_, c) != NULL)) {
do {
c = GetChar_();
} while (likely(c != EOF) && likely(c != '\r') && likely(c != '\n'));
}
if (unlikely(c == EOF)) {
c = 0;
}
return c;
}
char TextTokenizer::NextChar_(ArrayList<char> *token) {
char c = NextChar_();
*token->AddBack() = c;
return c;
}
char TextTokenizer::Skip_(ArrayList<char> *token) {
int c;
while (1) {
c = NextChar_();
if (!isspace(c)) {
break;
}
if (c == '\r' || c == '\n') {
if (c == '\r') {
c = NextChar_();
if (c != '\n') {
Unget_(c);
}
}
line_++;
if ((features_ & WANT_NEWLINE)) {
c = '\n';
break;
}
}
}
*token->AddBack() = char(c);
return char(c);
}
void TextTokenizer::UndoNextChar_(ArrayList<char> *token) {
char c = *token->PopBackPtr();
if (c != 0) { /* don't put EOF back on the stream */
Unget_(c);
}
}
void Sanitize(const String& src, String* dest) {
dest->Init();
for (index_t i = 0; i < src.length(); i++) {
char c = src[i];
if (isgraph(c) || c == ' ' || c == '\t') {
*dest += c;
} else if (isspace(c)) {
*dest += "<whitespace>";
} else {
*dest += "<nonprint>";
}
}
}
void TextTokenizer::Error(const char *format, ...) {
va_list vl;
String cur_sanitized;
String next_sanitized;
Sanitize(cur_, &cur_sanitized);
Sanitize(next_, &next_sanitized);
// TODO: Use a warning propagation system
fprintf(stderr, ".| %d: %s <-HERE-> %s\nX| `-> ", line_,
cur_sanitized.c_str(), next_sanitized.c_str());
va_start(vl, format);
vfprintf(stderr, format, vl);
va_end(vl);
fprintf(stderr, "\n");
}
void TextTokenizer::Error_(const char *msg, const ArrayList<char>& token) {
next_type_ = INVALID;
printf("size is %"LI"d, token[0] = %d\n", token.size(), token[0]);
next_.Copy(token.begin(), token.size());
Error("%s", msg);
next_.Destruct();
}
void TextTokenizer::ScanNumber_(char c, ArrayList<char> *token) {
bool dot = false;
bool floating = false;
while (1) {
if (unlikely(c == '.')) {
/* handle a period */
if (unlikely(dot)) {
Error_("Multiple decimal points in a float", *token);
return;
}
dot = true;
floating = true;
} else if (likely(isdigit(c))) {
/* keep on processing digits */
} else if (unlikely(c == 'e' || c == 'E')) {
/* exponent - read exponent and finish */
c = NextChar_(token);
if (c == '+' || c == '-') {
c = NextChar_(token);
}
while (isdigit(c)) {
c = NextChar_(token);
}
floating = true;
break;
} else {
/* non numeric */
break;
}
c = NextChar_(token);
}
if (c == 'f' || c == 'F') {
// It's labelled a float. Gobble and go.
floating = true;
} else if (isspace(c) || ispunct(c)) {
UndoNextChar_(token);
} else {
Error_("Invalid character while parsing number", *token);
}
if (floating) {
next_type_ = DOUBLE;
} else {
next_type_ = INTEGER;
}
}
void TextTokenizer::ScanString_(char ending, ArrayList<char> *token) {
int c;
while (1) {
c = NextChar_(token);
if (c == 0) {
Error_("Unterminated String", *token);
UndoNextChar_(token);
return;
}
if (c == ending) {
next_type_ = STRING;
return;
}
}
}
void TextTokenizer::Scan_(ArrayList<char> *token) {
char c = Skip_(token);
if (c == 0) {
token->Clear();
next_type_ = END;
return;
} else if (c == '.' || isdigit(c)) {
ScanNumber_(c, token);
} else if (isident_begin_(c)) {
while (isident_rest_(NextChar_(token))) {}
UndoNextChar_(token);
next_type_ = IDENTIFIER;
} else if (ispunct(c) || isspace(c)) {
if (c == '"' || c == '\'') {
ScanString_(c, token);
} else if (c == '+' || c == '-') {
c = NextChar_(token);
if (c == '.' || isdigit(c)) {
ScanNumber_(c, token);
} else {
UndoNextChar_(token);
}
} else {
next_type_ = PUNCT;
}
} else {
Error_("Unknown Character", *token);
}
}
void TextTokenizer::Gobble() {
cur_.Destruct();
cur_.StealDestruct(&next_);
cur_type_ = next_type_;
ArrayList<char> token;
token.Init();
Scan_(&token);
*token.AddBack() = '\0';
next_.Steal(&token);
DEBUG_ASSERT(next_.length() == index_t(strlen(next_.c_str())));
}
success_t TextWriter::Printf(const char *format, ...) {
int rv;
va_list vl;
va_start(vl, format);
rv = vfprintf(f_, format, vl);
va_end(vl);
return SUCCESS_FROM_C(rv);
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
//______________________________________________________________________________________________________________
// includes of other projects
//______________________________________________________________________________________________________________
#include <cppuhelper/factory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/container/XSet.hpp>
#include <stdio.h>
//______________________________________________________________________________________________________________
// includes of my own project
//______________________________________________________________________________________________________________
//=============================================================================
// Add new include line to use new services.
//=============================================================================
#include "framecontrol.hxx"
#include "progressbar.hxx"
#include "progressmonitor.hxx"
#include "statusindicator.hxx"
//=============================================================================
//______________________________________________________________________________________________________________
// defines
//______________________________________________________________________________________________________________
// If you will debug macros of this file ... you must define follow constant!
// Ths switch on another macro AS_DBG_OUT(...), which will print text to "stdout".
//#define AS_DBG_SWITCH
//______________________________________________________________________________________________________________
// namespaces
//______________________________________________________________________________________________________________
using namespace ::rtl ;
using namespace ::cppu ;
using namespace ::unocontrols ;
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::container ;
using namespace ::com::sun::star::lang ;
using namespace ::com::sun::star::registry ;
//______________________________________________________________________________________________________________
// macros
//______________________________________________________________________________________________________________
//******************************************************************************************************************************
// See AS_DBG_SWITCH below !!!
#ifdef AS_DBG_SWITCH
#define AS_DBG_OUT(OUTPUT) printf( OUTPUT );
#else
#define AS_DBG_OUT(OUTPUT)
#endif
//******************************************************************************************************************************
#define CREATEINSTANCE(CLASS) \
\
static Reference< XInterface > SAL_CALL CLASS##_createInstance ( const Reference< XMultiServiceFactory >& rServiceManager ) throw ( Exception ) \
{ \
AS_DBG_OUT ( "\tCREATEINSTANCE():\tOK\n" ) \
return Reference< XInterface >( *(OWeakObject*)(new CLASS( rServiceManager )) ); \
}
//******************************************************************************************************************************
#define COMPONENT_INFO(CLASS) \
\
AS_DBG_OUT ( "\tCOMPONENT_INFO():\t[start]\n" ) \
try \
{ \
/* Set default result of follow operations !!! */ \
bReturn = sal_False ; \
\
/* Do the follow only, if given key is valid ! */ \
if ( xKey.is () ) \
{ \
AS_DBG_OUT ( "\tCOMPONENT_INFO():\t\txkey is valid ...\n" ) \
/* Build new keyname */ \
sKeyName = OUString(RTL_CONSTASCII_USTRINGPARAM("/")) ; \
sKeyName += CLASS::impl_getStaticImplementationName() ; \
sKeyName += OUString(RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES")); \
\
/* Create new key with new name. */ \
xNewKey = xKey->createKey( sKeyName ); \
\
/* If this new key valid ... */ \
if ( xNewKey.is () ) \
{ \
AS_DBG_OUT ( "\tCOMPONENT_INFO():\t\txNewkey is valid ...\n" ) \
/* Get information about supported services. */ \
seqServiceNames = CLASS::impl_getStaticSupportedServiceNames() ; \
pArray = seqServiceNames.getArray() ; \
nLength = seqServiceNames.getLength() ; \
nCounter = 0 ; \
\
AS_DBG_OUT ( "\tCOMPONENT_INFO():\t\tloop ..." ) \
/* Then set this information on this key. */ \
for ( nCounter = 0; nCounter < nLength; ++nCounter ) \
{ \
xNewKey->createKey( pArray [nCounter] ); \
} \
AS_DBG_OUT ( " OK\n" ) \
\
/* Result of this operations = OK. */ \
bReturn = sal_True ; \
} \
AS_DBG_OUT ( "\tCOMPONENT_INFO():\t\t... leave xNewKey\n" ) \
} \
AS_DBG_OUT ( "\tCOMPONENT_INFO():\t\t... leave xKey\n" ) \
} \
catch( InvalidRegistryException& ) \
{ \
AS_DBG_OUT ( "\tCOMPONENT_INFO():\t\tInvalidRegistryException detected!!!\n" ) \
bReturn = sal_False ; \
} \
AS_DBG_OUT ( "\tCOMPONENT_INFO():\t[end]\n" )
//******************************************************************************************************************************
#define CREATEFACTORY_ONEINSTANCE(CLASS) \
\
AS_DBG_OUT ( "\tCREATEFACTORY_ONEINSTANCE():\t[start]\n" ) \
/* Create right factory ... */ \
xFactory = Reference< XSingleServiceFactory > \
( \
cppu::createOneInstanceFactory ( xServiceManager , \
CLASS::impl_getStaticImplementationName () , \
CLASS##_createInstance , \
CLASS::impl_getStaticSupportedServiceNames () ) \
) ; \
AS_DBG_OUT ( "\tCREATEFACTORY_ONEINSTANCE():\t[end]\n" )
//******************************************************************************************************************************
#define CREATEFACTORY_SINGLE(CLASS) \
\
AS_DBG_OUT ( "\tCREATEFACTORY_SINGLE():\t[start]\n" ) \
/* Create right factory ... */ \
xFactory = Reference< XSingleServiceFactory > \
( \
cppu::createSingleFactory ( xServiceManager , \
CLASS::impl_getStaticImplementationName () , \
CLASS##_createInstance , \
CLASS::impl_getStaticSupportedServiceNames () ) \
) ; \
AS_DBG_OUT ( "\tCREATEFACTORY_SINGLE():\t[end]\n" )
//******************************************************************************************************************************
#define IF_NAME_CREATECOMPONENTFACTORY_ONEINSTANCE(CLASS) \
\
if ( CLASS::impl_getStaticImplementationName().equals( OUString::createFromAscii( pImplementationName ) ) ) \
{ \
AS_DBG_OUT ( "\tIF_NAME_CREATECOMPONENTFACTORY_ONEINSTANCE():\timplementationname found\n" ) \
CREATEFACTORY_ONEINSTANCE ( CLASS ) \
}
//******************************************************************************************************************************
#define IF_NAME_CREATECOMPONENTFACTORY_SINGLE(CLASS) \
\
if ( CLASS::impl_getStaticImplementationName().equals( OUString::createFromAscii( pImplementationName ) ) ) \
{ \
AS_DBG_OUT ( "\tIF_NAME_CREATECOMPONENTFACTORY_SINGLE():\timplementationname found\n" ) \
CREATEFACTORY_SINGLE ( CLASS ) \
}
//______________________________________________________________________________________________________________
// declare functions to create a new instance of service
//______________________________________________________________________________________________________________
//=============================================================================
// Add new macro line to use new services.
//
// !!! ATTENTION !!!
// Write no ";" at end of line! (see macro)
//=============================================================================
CREATEINSTANCE ( FrameControl )
CREATEINSTANCE ( ProgressBar )
CREATEINSTANCE ( ProgressMonitor )
CREATEINSTANCE ( StatusIndicator )
//=============================================================================
//______________________________________________________________________________________________________________
// return environment
//______________________________________________________________________________________________________________
extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvironmentTypeName ,
uno_Environment** /*ppEnvironment*/ )
{
*ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
//______________________________________________________________________________________________________________
// write component info to registry
//______________________________________________________________________________________________________________
extern "C" sal_Bool SAL_CALL component_writeInfo( void* /*pServiceManager*/ ,
void* pRegistryKey )
{
AS_DBG_OUT ( "component_writeInfo():\t[start]\n" )
// Set default return value for this operation - if it failed.
sal_Bool bReturn = sal_False ;
if ( pRegistryKey != NULL )
{
AS_DBG_OUT ( "component_writeInfo():\t\tpRegistryKey is valid ... enter scope\n" )
// Define variables for following macros!
// bReturn is set automaticly.
Reference< XRegistryKey > xKey( reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ;
Reference< XRegistryKey > xNewKey ;
Sequence< OUString > seqServiceNames ;
const OUString* pArray ;
sal_Int32 nLength ;
sal_Int32 nCounter ;
OUString sKeyName ;
//=============================================================================
// Add new macro line to register new services.
//
// !!! ATTENTION !!!
// Write no ";" at end of line! (see macro)
//=============================================================================
COMPONENT_INFO ( FrameControl )
COMPONENT_INFO ( ProgressBar )
COMPONENT_INFO ( ProgressMonitor )
COMPONENT_INFO ( StatusIndicator )
//=============================================================================
AS_DBG_OUT ( "component_writeInfo():\t\t... leave pRegistryKey scope\n" )
}
AS_DBG_OUT ( "component_writeInfo():\t[end]\n" )
// Return with result of this operation.
return bReturn ;
}
//______________________________________________________________________________________________________________
// create right component factory
//______________________________________________________________________________________________________________
extern "C" void* SAL_CALL component_getFactory( const sal_Char* pImplementationName ,
void* pServiceManager ,
void* /*pRegistryKey*/ )
{
AS_DBG_OUT( "component_getFactory():\t[start]\n" )
// Set default return value for this operation - if it failed.
void* pReturn = NULL ;
if (
( pImplementationName != NULL ) &&
( pServiceManager != NULL )
)
{
AS_DBG_OUT( "component_getFactory():\t\t... enter scope - pointer are valid\n" )
// Define variables which are used in following macros.
Reference< XSingleServiceFactory > xFactory ;
Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
//=============================================================================
// Add new macro line to handle new service.
//
// !!! ATTENTION !!!
// Write no ";" at end of line and dont forget "else" ! (see macro)
//=============================================================================
IF_NAME_CREATECOMPONENTFACTORY_SINGLE( FrameControl )
else
IF_NAME_CREATECOMPONENTFACTORY_SINGLE( ProgressBar )
else
IF_NAME_CREATECOMPONENTFACTORY_SINGLE( ProgressMonitor )
else
IF_NAME_CREATECOMPONENTFACTORY_SINGLE( StatusIndicator )
//=============================================================================
// Factory is valid - service was found.
if ( xFactory.is() )
{
AS_DBG_OUT( "component_getFactory():\t\t\t... xFactory valid - service was found\n" )
xFactory->acquire();
pReturn = xFactory.get();
}
AS_DBG_OUT( "component_getFactory():\t\t... leave scope\n" )
}
AS_DBG_OUT ( "component_getFactory():\t[end]\n" )
// Return with result of this operation.
return pReturn ;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove AS_DBG_SWITCH<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
//______________________________________________________________________________________________________________
// includes of other projects
//______________________________________________________________________________________________________________
#include <cppuhelper/factory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/container/XSet.hpp>
#include <stdio.h>
//______________________________________________________________________________________________________________
// includes of my own project
//______________________________________________________________________________________________________________
//=============================================================================
// Add new include line to use new services.
//=============================================================================
#include "framecontrol.hxx"
#include "progressbar.hxx"
#include "progressmonitor.hxx"
#include "statusindicator.hxx"
//=============================================================================
//______________________________________________________________________________________________________________
// namespaces
//______________________________________________________________________________________________________________
using namespace ::rtl ;
using namespace ::cppu ;
using namespace ::unocontrols ;
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::container ;
using namespace ::com::sun::star::lang ;
using namespace ::com::sun::star::registry ;
//______________________________________________________________________________________________________________
// macros
//______________________________________________________________________________________________________________
//******************************************************************************************************************************
#define CREATEINSTANCE(CLASS) \
\
static Reference< XInterface > SAL_CALL CLASS##_createInstance ( const Reference< XMultiServiceFactory >& rServiceManager ) throw ( Exception ) \
{ \
return Reference< XInterface >( *(OWeakObject*)(new CLASS( rServiceManager )) ); \
}
//******************************************************************************************************************************
#define COMPONENT_INFO(CLASS) \
\
try \
{ \
/* Set default result of follow operations !!! */ \
bReturn = sal_False ; \
\
/* Do the follow only, if given key is valid ! */ \
if ( xKey.is () ) \
{ \
/* Build new keyname */ \
sKeyName = OUString(RTL_CONSTASCII_USTRINGPARAM("/")) ; \
sKeyName += CLASS::impl_getStaticImplementationName() ; \
sKeyName += OUString(RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES")); \
\
/* Create new key with new name. */ \
xNewKey = xKey->createKey( sKeyName ); \
\
/* If this new key valid ... */ \
if ( xNewKey.is () ) \
{ \
/* Get information about supported services. */ \
seqServiceNames = CLASS::impl_getStaticSupportedServiceNames() ; \
pArray = seqServiceNames.getArray() ; \
nLength = seqServiceNames.getLength() ; \
nCounter = 0 ; \
\
/* Then set this information on this key. */ \
for ( nCounter = 0; nCounter < nLength; ++nCounter ) \
{ \
xNewKey->createKey( pArray [nCounter] ); \
} \
\
/* Result of this operations = OK. */ \
bReturn = sal_True ; \
} \
} \
} \
catch( InvalidRegistryException& ) \
{ \
bReturn = sal_False ; \
} \
//******************************************************************************************************************************
#define CREATEFACTORY_ONEINSTANCE(CLASS) \
\
/* Create right factory ... */ \
xFactory = Reference< XSingleServiceFactory > \
( \
cppu::createOneInstanceFactory ( xServiceManager , \
CLASS::impl_getStaticImplementationName () , \
CLASS##_createInstance , \
CLASS::impl_getStaticSupportedServiceNames () ) \
) ; \
//******************************************************************************************************************************
#define CREATEFACTORY_SINGLE(CLASS) \
\
/* Create right factory ... */ \
xFactory = Reference< XSingleServiceFactory > \
( \
cppu::createSingleFactory ( xServiceManager , \
CLASS::impl_getStaticImplementationName () , \
CLASS##_createInstance , \
CLASS::impl_getStaticSupportedServiceNames () ) \
) ; \
//******************************************************************************************************************************
#define IF_NAME_CREATECOMPONENTFACTORY_ONEINSTANCE(CLASS) \
\
if ( CLASS::impl_getStaticImplementationName().equals( OUString::createFromAscii( pImplementationName ) ) ) \
{ \
CREATEFACTORY_ONEINSTANCE ( CLASS ) \
}
//******************************************************************************************************************************
#define IF_NAME_CREATECOMPONENTFACTORY_SINGLE(CLASS) \
\
if ( CLASS::impl_getStaticImplementationName().equals( OUString::createFromAscii( pImplementationName ) ) ) \
{ \
CREATEFACTORY_SINGLE ( CLASS ) \
}
//______________________________________________________________________________________________________________
// declare functions to create a new instance of service
//______________________________________________________________________________________________________________
//=============================================================================
// Add new macro line to use new services.
//
// !!! ATTENTION !!!
// Write no ";" at end of line! (see macro)
//=============================================================================
CREATEINSTANCE ( FrameControl )
CREATEINSTANCE ( ProgressBar )
CREATEINSTANCE ( ProgressMonitor )
CREATEINSTANCE ( StatusIndicator )
//=============================================================================
//______________________________________________________________________________________________________________
// return environment
//______________________________________________________________________________________________________________
extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvironmentTypeName ,
uno_Environment** /*ppEnvironment*/ )
{
*ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
//______________________________________________________________________________________________________________
// write component info to registry
//______________________________________________________________________________________________________________
extern "C" sal_Bool SAL_CALL component_writeInfo( void* /*pServiceManager*/ ,
void* pRegistryKey )
{
// Set default return value for this operation - if it failed.
sal_Bool bReturn = sal_False ;
if ( pRegistryKey != NULL )
{
// Define variables for following macros!
// bReturn is set automaticly.
Reference< XRegistryKey > xKey( reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ;
Reference< XRegistryKey > xNewKey ;
Sequence< OUString > seqServiceNames ;
const OUString* pArray ;
sal_Int32 nLength ;
sal_Int32 nCounter ;
OUString sKeyName ;
//=============================================================================
// Add new macro line to register new services.
//
// !!! ATTENTION !!!
// Write no ";" at end of line! (see macro)
//=============================================================================
COMPONENT_INFO ( FrameControl )
COMPONENT_INFO ( ProgressBar )
COMPONENT_INFO ( ProgressMonitor )
COMPONENT_INFO ( StatusIndicator )
//=============================================================================
}
// Return with result of this operation.
return bReturn ;
}
//______________________________________________________________________________________________________________
// create right component factory
//______________________________________________________________________________________________________________
extern "C" void* SAL_CALL component_getFactory( const sal_Char* pImplementationName ,
void* pServiceManager ,
void* /*pRegistryKey*/ )
{
// Set default return value for this operation - if it failed.
void* pReturn = NULL ;
if (
( pImplementationName != NULL ) &&
( pServiceManager != NULL )
)
{
// Define variables which are used in following macros.
Reference< XSingleServiceFactory > xFactory ;
Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
//=============================================================================
// Add new macro line to handle new service.
//
// !!! ATTENTION !!!
// Write no ";" at end of line and dont forget "else" ! (see macro)
//=============================================================================
IF_NAME_CREATECOMPONENTFACTORY_SINGLE( FrameControl )
else
IF_NAME_CREATECOMPONENTFACTORY_SINGLE( ProgressBar )
else
IF_NAME_CREATECOMPONENTFACTORY_SINGLE( ProgressMonitor )
else
IF_NAME_CREATECOMPONENTFACTORY_SINGLE( StatusIndicator )
//=============================================================================
// Factory is valid - service was found.
if ( xFactory.is() )
{
xFactory->acquire();
pReturn = xFactory.get();
}
}
// Return with result of this operation.
return pReturn ;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* 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 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Heiko Strathmann
*/
#include <shogun/statistics/TwoSampleTestStatistic.h>
#include <shogun/features/Features.h>
using namespace shogun;
CTwoSampleTestStatistic::CTwoSampleTestStatistic() : CTestStatistic()
{
init();
}
CTwoSampleTestStatistic::CTwoSampleTestStatistic(CFeatures* p_and_q,
index_t q_start) : CTestStatistic()
{
init();
m_p_and_q=p_and_q;
SG_REF(m_p_and_q);
m_q_start=q_start;
}
CTwoSampleTestStatistic::CTwoSampleTestStatistic(CFeatures* p, CFeatures* q) :
CTestStatistic()
{
init();
/* TODO append features */
}
CTwoSampleTestStatistic::~CTwoSampleTestStatistic()
{
SG_UNREF(m_p_and_q);
}
void CTwoSampleTestStatistic::init()
{
SG_ADD((CSGObject**)&m_p_and_q, "p_and_q", "Concatenated samples p and q",
MS_NOT_AVAILABLE);
SG_ADD(&m_q_start, "q_start", "Index of first sample of q",
MS_NOT_AVAILABLE);
SG_ADD(&m_bootstrap_iterations, "bootstrap_iterations",
"Number of iterations for bootstrapping", MS_NOT_AVAILABLE);
SG_ADD((machine_int_t*)&m_p_value_method, "p_value_method",
"Method for computing p-value", MS_NOT_AVAILABLE);
m_p_and_q=NULL;
m_q_start=0;
m_bootstrap_iterations=250;
m_p_value_method=BOOTSTRAP;
}
void CTwoSampleTestStatistic::set_p_value_method(EPValueMethod p_value_method)
{
m_p_value_method=p_value_method;
}
SGVector<float64_t> CTwoSampleTestStatistic::bootstrap_null()
{
/* compute bootstrap statistics for null distribution */
SGVector<float64_t> results(m_bootstrap_iterations);
/* memory for index permutations, (would slow down loop) */
SGVector<index_t> ind_permutation(m_p_and_q->get_num_vectors());
ind_permutation.range_fill();
m_p_and_q->add_subset(ind_permutation);
for (index_t i=0; i<m_bootstrap_iterations; ++i)
{
/* idea: merge features of p and q, shuffle, and compute statistic.
* This is done using subsets here */
/* create index permutation and add as subset. This will mix samples
* from p and q */
SGVector<int32_t>::permute_vector(ind_permutation);
/* compute statistic for this permutation of mixed samples */
results[i]=compute_statistic();
}
/* clean up */
m_p_and_q->remove_subset();
/* clean up and return */
return results;
}
void CTwoSampleTestStatistic::set_bootstrap_iterations(index_t bootstrap_iterations)
{
m_bootstrap_iterations=bootstrap_iterations;
}
float64_t CTwoSampleTestStatistic::compute_p_value(float64_t statistic)
{
float64_t result=0;
if (m_p_value_method==BOOTSTRAP)
{
/* bootstrap a bunch of MMD values from null distribution */
SGVector<float64_t> values=bootstrap_null();
/* find out percentile of parameter "statistic" in null distribution */
CMath::qsort(values);
float64_t i=CMath::find_position_to_insert(values, statistic);
/* return corresponding p-value */
result=1.0-i/values.vlen;
}
else
{
SG_ERROR("%s::compute_p_value(): Unknown method to compute"
" p-value!\n");
}
return result;
}
<commit_msg>filled convienience constructor with content<commit_after>/*
* 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 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2012 Heiko Strathmann
*/
#include <shogun/statistics/TwoSampleTestStatistic.h>
#include <shogun/features/Features.h>
using namespace shogun;
CTwoSampleTestStatistic::CTwoSampleTestStatistic() : CTestStatistic()
{
init();
}
CTwoSampleTestStatistic::CTwoSampleTestStatistic(CFeatures* p_and_q,
index_t q_start) : CTestStatistic()
{
init();
m_p_and_q=p_and_q;
SG_REF(m_p_and_q);
m_q_start=q_start;
}
CTwoSampleTestStatistic::CTwoSampleTestStatistic(CFeatures* p, CFeatures* q) :
CTestStatistic()
{
init();
m_p_and_q=p->create_merged_copy(q);
SG_REF(m_p_and_q);
m_q_start=p->get_num_vectors();
}
CTwoSampleTestStatistic::~CTwoSampleTestStatistic()
{
SG_UNREF(m_p_and_q);
}
void CTwoSampleTestStatistic::init()
{
SG_ADD((CSGObject**)&m_p_and_q, "p_and_q", "Concatenated samples p and q",
MS_NOT_AVAILABLE);
SG_ADD(&m_q_start, "q_start", "Index of first sample of q",
MS_NOT_AVAILABLE);
SG_ADD(&m_bootstrap_iterations, "bootstrap_iterations",
"Number of iterations for bootstrapping", MS_NOT_AVAILABLE);
SG_ADD((machine_int_t*)&m_p_value_method, "p_value_method",
"Method for computing p-value", MS_NOT_AVAILABLE);
m_p_and_q=NULL;
m_q_start=0;
m_bootstrap_iterations=250;
m_p_value_method=BOOTSTRAP;
}
void CTwoSampleTestStatistic::set_p_value_method(EPValueMethod p_value_method)
{
m_p_value_method=p_value_method;
}
SGVector<float64_t> CTwoSampleTestStatistic::bootstrap_null()
{
/* compute bootstrap statistics for null distribution */
SGVector<float64_t> results(m_bootstrap_iterations);
/* memory for index permutations, (would slow down loop) */
SGVector<index_t> ind_permutation(m_p_and_q->get_num_vectors());
ind_permutation.range_fill();
m_p_and_q->add_subset(ind_permutation);
for (index_t i=0; i<m_bootstrap_iterations; ++i)
{
/* idea: merge features of p and q, shuffle, and compute statistic.
* This is done using subsets here */
/* create index permutation and add as subset. This will mix samples
* from p and q */
SGVector<int32_t>::permute_vector(ind_permutation);
/* compute statistic for this permutation of mixed samples */
results[i]=compute_statistic();
}
/* clean up */
m_p_and_q->remove_subset();
/* clean up and return */
return results;
}
void CTwoSampleTestStatistic::set_bootstrap_iterations(index_t bootstrap_iterations)
{
m_bootstrap_iterations=bootstrap_iterations;
}
float64_t CTwoSampleTestStatistic::compute_p_value(float64_t statistic)
{
float64_t result=0;
if (m_p_value_method==BOOTSTRAP)
{
/* bootstrap a bunch of MMD values from null distribution */
SGVector<float64_t> values=bootstrap_null();
/* find out percentile of parameter "statistic" in null distribution */
CMath::qsort(values);
float64_t i=CMath::find_position_to_insert(values, statistic);
/* return corresponding p-value */
result=1.0-i/values.vlen;
}
else
{
SG_ERROR("%s::compute_p_value(): Unknown method to compute"
" p-value!\n");
}
return result;
}
<|endoftext|> |
<commit_before>#ifndef TELEGRAM_DECLARATIVE_AUTH_OPERATION_HPP
#define TELEGRAM_DECLARATIVE_AUTH_OPERATION_HPP
#include <QObject>
#include "DeclarativeOperation.hpp"
namespace Telegram {
namespace Client {
class DeclarativeClient;
class DeclarativeSettings;
class AuthOperation;
class TELEGRAMQT_QML_EXPORT DeclarativeAuthOperation : public DeclarativeOperation
{
Q_OBJECT
Q_PROPERTY(QString phoneNumber READ phoneNumber WRITE setPhoneNumber NOTIFY phoneNumberChanged)
Q_PROPERTY(bool registered READ isRegistered NOTIFY registeredChanged)
Q_PROPERTY(QString passwordHint READ passwordHint NOTIFY passwordHintChanged)
Q_PROPERTY(bool hasRecovery READ hasRecovery NOTIFY hasRecoveryChanged)
// Q_PROPERTY(bool callAvailable READ isCallAvailable NOTIFY callAvailableChanged)
Q_PROPERTY(AuthStatus status READ status NOTIFY statusChanged)
Q_PROPERTY(bool busy READ isBusy NOTIFY busyChanged)
// Q_PROPERTY(bool passwordParamsKnown READ passwordParamsKnown)
public:
explicit DeclarativeAuthOperation(QObject *parent = nullptr);
enum AuthStatus {
Idle,
Connecting,
Handshake,
PhoneNumberRequired,
AuthCodeRequired,
PasswordRequired,
SignedIn
};
Q_ENUM(AuthStatus)
bool isBusy() const;
AuthStatus status() const;
QString phoneNumber() const;
bool isRegistered() const;
QString passwordHint() const;
bool hasRecovery() const;
public slots:
void startAuthentication();
void checkIn();
void abort();
void submitPhoneNumber(const QString &phoneNumber);
bool submitAuthCode(const QString &code);
bool submitPassword(const QString &password);
bool submitName(const QString &firstName, const QString &lastName);
void setPhoneNumber(const QString &phoneNumber);
bool recovery();
bool requestCall();
bool requestSms();
Q_SIGNALS:
void busyChanged(bool busy);
void checkInFinished(bool signedIn);
void signInFinished(bool signedIn);
void passwordHintChanged(const QString &hint);
void hasRecoveryChanged();
void phoneNumberRequired();
void authCodeRequired();
void authCodeCheckFailed();
void passwordRequired();
void passwordCheckFailed();
void phoneNumberChanged();
void registeredChanged(bool registered); // Always emitted before authCodeRequired()
// void callAvailable();
void statusChanged(AuthStatus status);
// Error message description: https://core.telegram.org/api/errors#400-bad-request
void errorOccurred(Telegram::Namespace::AuthenticationError errorCode, const QByteArray &errorMessage);
void authorizationErrorReceived(Telegram::Namespace::UnauthorizedError errorCode, const QString &errorMessage);
public slots:
Q_DECL_DEPRECATED void checkRegistration() { return startAuthentication(); }
Q_DECL_DEPRECATED void signIn() { startAuthentication(); }
protected:
void setStatus(const DeclarativeAuthOperation::AuthStatus status);
void setBusy(bool busy);
void unsetBusy();
void onPasswordRequired();
void onPasswordCheckFailed();
AuthOperation *m_authOperation = nullptr;
void startEvent() override;
bool m_busy = false;
AuthStatus m_status = AuthStatus::Idle;
QString m_phoneNumber;
};
} // Client
} // Telegram
#endif // TELEGRAM_DECLARATIVE_AUTH_OPERATION_HPP
<commit_msg>Declarative/AuthOperation: Remove deprecated API<commit_after>#ifndef TELEGRAM_DECLARATIVE_AUTH_OPERATION_HPP
#define TELEGRAM_DECLARATIVE_AUTH_OPERATION_HPP
#include <QObject>
#include "DeclarativeOperation.hpp"
namespace Telegram {
namespace Client {
class DeclarativeClient;
class DeclarativeSettings;
class AuthOperation;
class TELEGRAMQT_QML_EXPORT DeclarativeAuthOperation : public DeclarativeOperation
{
Q_OBJECT
Q_PROPERTY(QString phoneNumber READ phoneNumber WRITE setPhoneNumber NOTIFY phoneNumberChanged)
Q_PROPERTY(bool registered READ isRegistered NOTIFY registeredChanged)
Q_PROPERTY(QString passwordHint READ passwordHint NOTIFY passwordHintChanged)
Q_PROPERTY(bool hasRecovery READ hasRecovery NOTIFY hasRecoveryChanged)
// Q_PROPERTY(bool callAvailable READ isCallAvailable NOTIFY callAvailableChanged)
Q_PROPERTY(AuthStatus status READ status NOTIFY statusChanged)
Q_PROPERTY(bool busy READ isBusy NOTIFY busyChanged)
// Q_PROPERTY(bool passwordParamsKnown READ passwordParamsKnown)
public:
explicit DeclarativeAuthOperation(QObject *parent = nullptr);
enum AuthStatus {
Idle,
Connecting,
Handshake,
PhoneNumberRequired,
AuthCodeRequired,
PasswordRequired,
SignedIn
};
Q_ENUM(AuthStatus)
bool isBusy() const;
AuthStatus status() const;
QString phoneNumber() const;
bool isRegistered() const;
QString passwordHint() const;
bool hasRecovery() const;
public slots:
void startAuthentication();
void checkIn();
void abort();
void submitPhoneNumber(const QString &phoneNumber);
bool submitAuthCode(const QString &code);
bool submitPassword(const QString &password);
bool submitName(const QString &firstName, const QString &lastName);
void setPhoneNumber(const QString &phoneNumber);
bool recovery();
bool requestCall();
bool requestSms();
Q_SIGNALS:
void busyChanged(bool busy);
void checkInFinished(bool signedIn);
void signInFinished(bool signedIn);
void passwordHintChanged(const QString &hint);
void hasRecoveryChanged();
void phoneNumberRequired();
void authCodeRequired();
void authCodeCheckFailed();
void passwordRequired();
void passwordCheckFailed();
void phoneNumberChanged();
void registeredChanged(bool registered); // Always emitted before authCodeRequired()
// void callAvailable();
void statusChanged(AuthStatus status);
// Error message description: https://core.telegram.org/api/errors#400-bad-request
void errorOccurred(Telegram::Namespace::AuthenticationError errorCode, const QByteArray &errorMessage);
void authorizationErrorReceived(Telegram::Namespace::UnauthorizedError errorCode, const QString &errorMessage);
protected:
void setStatus(const DeclarativeAuthOperation::AuthStatus status);
void setBusy(bool busy);
void unsetBusy();
void onPasswordRequired();
void onPasswordCheckFailed();
AuthOperation *m_authOperation = nullptr;
void startEvent() override;
bool m_busy = false;
AuthStatus m_status = AuthStatus::Idle;
QString m_phoneNumber;
};
} // Client
} // Telegram
#endif // TELEGRAM_DECLARATIVE_AUTH_OPERATION_HPP
<|endoftext|> |
<commit_before>#include <highgui.h>
#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include "human_robot_collaboration_msgs/ArmState.h"
using namespace std;
using namespace human_robot_collaboration_msgs;
#define DEFAULT_DURATION 10.0 // [s]
class BaxterDisplay
{
private:
ros::NodeHandle nh;
int print_level; // Print level to be used throughout the code
std::string name; // Name of the node
ros::Subscriber l_sub; // Subscriber for the left arm state
ros::Subscriber r_sub; // Subscriber for the right arm state
ros::Subscriber s_sub; // Subscriber for the speech output
ArmState l_state;
ArmState r_state;
std::string speech; // Text to display
ros::Timer speech_timer; // Timer remove the speech pop-up after specific duration
double speech_duration; // Duration of the speech pop-up
image_transport::ImageTransport it;
image_transport::Publisher im_pub;
int h; // height of the image to be shown (equal to the height of the baxter display)
int w; // width of the image to be shown (equal to the width of the baxter display)
int w_d; // width of the delimiter between sub-screens
int w_b; // width of the bottom sub-screen
cv::Scalar red;
cv::Scalar green;
cv::Scalar blue;
void armStateCbL(const ArmState& msg)
{
armStateCb(msg, "left");
};
void armStateCbR(const ArmState& msg)
{
armStateCb(msg, "right");
};
void armStateCb(const ArmState& msg, std::string _limb)
{
ROS_INFO_COND(print_level>=2, "Arm %s", _limb.c_str());
if (_limb == "left")
{
l_state = msg;
}
else if (_limb == "right")
{
r_state = msg;
}
displayArmStates();
};
void displaySpeech(cv::Mat& in)
{
if (speech !="")
{
ROS_INFO_COND(print_level>=3, "Displaying speech: %s", speech.c_str());
int thickness = 3;
int baseline = 0;
int fontFace = cv::FONT_HERSHEY_SIMPLEX;
int fontScale = 2;
int border = 20;
int max_width = 800; // max width of a text line
cv::Size textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
int numLines = int(textSize.width/max_width)+1;
if (numLines>5)
{
fontScale = 1.6;
thickness = 2;
textSize = cv::getTextSize( speech, fontFace, fontScale, thickness, &baseline);
numLines = int(textSize.width/max_width);
}
ROS_INFO_COND(print_level>=4, "Size of the text %i %i numLines %i", textSize.height, textSize.width, numLines);
std::vector<std::string> line;
std::vector<cv::Size> size;
int interline = 20; // Number of pixels between a line and the next one
int rec_height = -interline; // Height of the rectangle container (line_heigth + interline)
int rec_width = 0; // Width of the rectangle container (max of the width of each of the lines)
int line_length = int(speech.size()/numLines);
for (int i = 0; i < numLines; ++i)
{
// The last line gets also the remainder of the splitting
if (i==numLines-1)
{
line.push_back(speech.substr(i*line_length,speech.size()-i*line_length));
}
else
{
line.push_back(speech.substr(i*line_length,line_length));
}
size.push_back(cv::getTextSize( line.back(), fontFace, fontScale, thickness, &baseline));
if (size.back().width>rec_width) { rec_width=size.back().width; }
rec_height += interline + size.back().height;
ROS_INFO_COND(print_level>=6, " Line %i: size: %i %i\ttext: %s", i,
size.back().height, size.back().width, line.back().c_str());
}
rec_height += 2*border;
rec_width += 2*border;
cv::Point rectOrg((in.cols-rec_width)/2, (in.rows-w_d/2-w_b-rec_height)/2);
cv::Point rectEnd((in.cols+rec_width)/2, (in.rows-w_d/2-w_b+rec_height)/2);
rectangle(in, rectOrg, rectEnd, blue, -1);
int textOrgy = rectOrg.y + border;
for (int i = 0; i < numLines; ++i)
{
textOrgy += size[i].height;
cv::Point textOrg((in.cols - size[i].width)/2, textOrgy);
putText(in, line[i], textOrg, fontFace, fontScale, cv::Scalar::all(255), thickness, CV_AA);
textOrgy += interline;
}
}
};
// Creates sub-image for either arm
cv::Mat createArmImage(std::string _limb)
{
ArmState state = _limb=="LEFT"?l_state:r_state;
cv::Mat img(h-w_d/2-w_b,(w-w_d)/2,CV_8UC3,cv::Scalar::all(255));
ROS_INFO_COND(print_level>=4, "Created %s image with size %i %i", _limb.c_str(), img.rows, img.cols);
cv::Scalar col = cv::Scalar::all(60);
cv::Scalar col_state = green;
if (state.state == "ERROR" || state.state == "RECOVER" ||
state.state == "KILLED" || state.state == "DONE" ||
state.state == "START" )
{
col = cv::Scalar::all(240);
col_state = col;
img.setTo(red);
if (state.state == "DONE" || state.state == "TEST" || state.state == "START")
{
img.setTo(green);
}
}
int thickness = 3;
int baseline = 0;
int fontFace = cv::FONT_HERSHEY_SIMPLEX;
int fontScale = 2;
// Place a centered title on top
string title = _limb + " ARM";
cv::Size textSize = cv::getTextSize( title, fontFace, fontScale, thickness, &baseline);
cv::Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/6);
putText(img, title, textOrg, fontFace, fontScale, col, thickness, CV_AA);
if (state.state !=" ")
{
putText(img, "state:", cv::Point( 20,300-60), fontFace, fontScale/2, col, 2, 8);
putText(img, state.state, cv::Point(150,300-60), fontFace, fontScale, col_state, thickness, CV_AA);
}
if (state.action !=" ")
{
putText(img, "action:", cv::Point( 20,400-60), fontFace, fontScale/2, col, 2, 8);
putText(img, state.action, cv::Point(150,400-60), fontFace, fontScale/1.25, col, thickness, CV_AA);
}
if (state.object !=" ")
{
putText(img, "object:", cv::Point( 20,500-60), fontFace, fontScale/2, col, 2, 8);
putText(img, state.object, cv::Point(150,500-60), fontFace, fontScale/1.25, col, thickness, CV_AA);
}
return img;
};
// Creates sub-image for the bottom bar
cv::Mat createBtmImage()
{
cv::Mat img(w_b-w_d/2,w,CV_8UC3,cv::Scalar::all(255));
ROS_INFO_COND(print_level>=4, "Created BOTTOM image with size %i %i", img.rows, img.cols);
return img;
}
public:
explicit BaxterDisplay(string _name) : print_level(0), name(_name), speech(""), it(nh)
{
im_pub = it.advertise("/robot/xdisplay", 1);
l_sub = nh.subscribe( "/action_provider/left/state", 1, &BaxterDisplay::armStateCbL, this);
r_sub = nh.subscribe("/action_provider/right/state", 1, &BaxterDisplay::armStateCbR, this);
s_sub = nh.subscribe("/svox_tts/speech_output",1, &BaxterDisplay::speechCb, this);
nh.param<int> ("/print_level", print_level, 0);
h = 600;
w = 1024;
w_d = 8;
w_b = 80;
l_state.state = "START";
l_state.action = "";
l_state.object = "";
r_state.state = "START";
r_state.action = "";
r_state.object = "";
red = cv::Scalar( 44, 48, 201); // BGR color code
green = cv::Scalar( 60, 160, 60);
blue = cv::Scalar( 200, 162, 77);
nh.param<double>("baxter_display/speech_duration", speech_duration, DEFAULT_DURATION);
displayArmStates();
ROS_INFO_COND(print_level>=1, "Ready");
};
void setSpeech(const std::string &s)
{
speech = s;
}
void speechCb(const std_msgs::String& msg)
{
ROS_INFO_COND(print_level>=2, "Text: %s", msg.data.c_str());
setSpeech(msg.data);
speech_timer = nh.createTimer(ros::Duration(speech_duration),
&BaxterDisplay::deleteSpeechCb, this, true);
displayArmStates();
};
void deleteSpeechCb(const ros::TimerEvent&)
{
ROS_INFO_COND(print_level>=2, "Deleting speech");
setSpeech("");
displayArmStates();
};
bool displayArmStates()
{
cv::Mat l = createArmImage("LEFT");
cv::Mat r = createArmImage("RIGHT");
cv::Mat b = createBtmImage();
cv::Mat d_v(r.rows,w_d,CV_8UC3,cv::Scalar::all(80)); // Vertical delimiter
cv::Mat d_h(w_d,w,CV_8UC3,cv::Scalar::all(80)); // Horizontal delimiter
ROS_INFO_COND(print_level>=5, "d_v size %i %i", d_v.rows, d_v.cols);
ROS_INFO_COND(print_level>=5, "d_h size %i %i", d_h.rows, d_h.cols);
cv::Mat res(h,w,CV_8UC3,cv::Scalar(255,100,255));
res.locateROI(size,offs);
// Draw sub-image for right arm
r.copyTo(res(cv::Rect(0, 0, r.cols, r.rows)));
// Draw sub-image for the vertical delimiter
d_v.copyTo(res(cv::Rect(r.cols, 0, d_v.cols, d_v.rows)));
// Draw sub-image for left arm
l.copyTo(res(cv::Rect(r.cols+d_v.cols, 0, l.cols, l.rows)));
// Draw sub-image for horizontal delimiter
d_h.copyTo(res(cv::Rect(0, r.rows, d_h.cols, d_h.rows)));
// Draw sub-image for bottom bar
b.copyTo(res(cv::Rect(0, r.rows+d_h.rows, b.cols, b.rows)));
// Eventually draw the speech on top of everything
displaySpeech(res);
// Publish the resulting image
cv_bridge::CvImage msg;
msg.encoding = sensor_msgs::image_encodings::BGR8;
msg.image = res;
im_pub.publish(msg.toImageMsg());
// cv::imshow("res", res);
// cv::waitKey(20);
return true;
};
};
int main(int argc, char ** argv)
{
ros::init(argc, argv, "baxter_display");
BaxterDisplay bd("baxter_display");
ros::Duration(0.2).sleep();
bd.displayArmStates();
ros::spin();
return 0;
}
<commit_msg>[baxter_display] Fixed late night commit, plus added some documentation<commit_after>#include <highgui.h>
#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/String.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include "human_robot_collaboration_msgs/ArmState.h"
using namespace std;
using namespace human_robot_collaboration_msgs;
#define DEFAULT_DURATION 10.0 // [s]
/**
* Class that manages the output to the baxter display. By default, it publishes an image
*/
class BaxterDisplay
{
private:
ros::NodeHandle nh;
int print_level; // Print level to be used throughout the code
std::string name; // Name of the node
ros::Subscriber l_sub; // Subscriber for the left arm state
ros::Subscriber r_sub; // Subscriber for the right arm state
ros::Subscriber s_sub; // Subscriber for the speech output
ArmState l_state;
ArmState r_state;
std::string speech; // Text to display
ros::Timer speech_timer; // Timer remove the speech pop-up after specific duration
double speech_duration; // Duration of the speech pop-up
image_transport::ImageTransport it;
image_transport::Publisher im_pub;
int h; // height of the image to be shown (equal to the height of the baxter display)
int w; // width of the image to be shown (equal to the width of the baxter display)
int w_d; // width of the delimiter between sub-screens
int w_b; // width of the bottom sub-screen
cv::Scalar red;
cv::Scalar green;
cv::Scalar blue;
/**
* Callback for the left arm state
* @param msg the left arm state
*/
void armStateCbL(const ArmState& msg)
{
armStateCb(msg, "left");
};
/**
* Callback for the right arm state
* @param msg the right arm state
*/
void armStateCbR(const ArmState& msg)
{
armStateCb(msg, "right");
};
/**
* Unified callback manager for both arm states
* @param msg the arm state
* @param _limb the arm it is referred to
*/
void armStateCb(const ArmState& msg, std::string _limb)
{
ROS_INFO_COND(print_level>=2, "Arm %s", _limb.c_str());
if (_limb == "left")
{
l_state = msg;
}
else if (_limb == "right")
{
r_state = msg;
}
displayArmStates();
};
/**
* Callback from the speech
* @param msg the speech
*/
void speechCb(const std_msgs::String& msg)
{
ROS_INFO_COND(print_level>=2, "Text: %s", msg.data.c_str());
setSpeech(msg.data);
speech_timer = nh.createTimer(ros::Duration(speech_duration),
&BaxterDisplay::deleteSpeechCb, this, true);
displayArmStates();
};
/**
* Callback to delete the speech from the screen (after t=speech_duration)
*/
void deleteSpeechCb(const ros::TimerEvent&)
{
ROS_INFO_COND(print_level>=2, "Deleting speech");
setSpeech("");
displayArmStates();
};
/**
* Function to display speech on top of the generated image
* @param in the already generated image ready to be sent to the robot
*/
void displaySpeech(cv::Mat& in)
{
if (speech !="")
{
ROS_INFO_COND(print_level>=3, "Displaying speech: %s", speech.c_str());
int thickn = 3; // thickness
int bsline = 0; // baseline
int fontFc = cv::FONT_HERSHEY_SIMPLEX; // fontFace
int fontSc = 2; // fontScale
int border = 20;
int max_width = 800; // max width of a text line
cv::Size textSize = cv::getTextSize( speech, fontFc, fontSc, thickn, &bsline);
int numLines = int(textSize.width/max_width)+1;
if (numLines>5)
{
fontSc = 1.6;
thickn = 2;
textSize = cv::getTextSize( speech, fontFc, fontSc, thickn, &bsline);
numLines = int(textSize.width/max_width);
}
ROS_INFO_COND(print_level>=4, "Size of the text %i %i numLines %i",
textSize.height, textSize.width, numLines);
std::vector<std::string> line;
std::vector<cv::Size> size;
int interline = 20; // Number of pixels between a line and the next one
int rec_height = -interline; // Height of the container (line_heigth + interline)
int rec_width = 0; // Width of the container (max width of each line)
int line_length = int(speech.size()/numLines);
for (int i = 0; i < numLines; ++i)
{
// The last line gets also the remainder of the splitting
if (i==numLines-1)
{
line.push_back(speech.substr(i*line_length,speech.size()-i*line_length));
}
else
{
line.push_back(speech.substr(i*line_length,line_length));
}
size.push_back(cv::getTextSize( line.back(), fontFc, fontSc, thickn, &bsline));
if (size.back().width>rec_width) { rec_width=size.back().width; }
rec_height += interline + size.back().height;
ROS_INFO_COND(print_level>=6, " Line %i: size: %i %i\ttext: %s", i,
size.back().height, size.back().width, line.back().c_str());
}
rec_height += 2*border;
rec_width += 2*border;
cv::Point rectOrg((in.cols-rec_width)/2, (in.rows-w_d/2-w_b-rec_height)/2);
cv::Point rectEnd((in.cols+rec_width)/2, (in.rows-w_d/2-w_b+rec_height)/2);
rectangle(in, rectOrg, rectEnd, blue, -1);
int textOrgy = rectOrg.y + border;
for (int i = 0; i < numLines; ++i)
{
textOrgy += size[i].height;
cv::Point textOrg((in.cols - size[i].width)/2, textOrgy);
putText(in, line[i], textOrg, fontFc, fontSc, cv::Scalar::all(255), thickn, CV_AA);
textOrgy += interline;
}
}
};
/**
* Function to create sub-image for either arm
* @param _limb the arm to create the image for
* @return the sub-image
*/
cv::Mat createArmImage(std::string _limb)
{
ArmState state = _limb=="LEFT"?l_state:r_state;
cv::Mat img(h-w_d/2-w_b,(w-w_d)/2,CV_8UC3,cv::Scalar::all(255));
ROS_INFO_COND(print_level>=4, "Created %s image with size %i %i",
_limb.c_str(), img.rows, img.cols);
cv::Scalar col = cv::Scalar::all(60);
cv::Scalar col_s = green;
if (state.state == "ERROR" || state.state == "RECOVER" ||
state.state == "KILLED" || state.state == "DONE" ||
state.state == "START" )
{
col = cv::Scalar::all(240);
col_s = col;
img.setTo(red);
if (state.state == "DONE" || state.state == "TEST" || state.state == "START")
{
img.setTo(green);
}
}
int thickn = 3; // thickness
int bsline = 0; // baseline
int fontFc = cv::FONT_HERSHEY_SIMPLEX; // fontFace
int fontSc = 2; // fontScale
// Place a centered title on top
string title = _limb + " ARM";
cv::Size textSize = cv::getTextSize( title, fontFc, fontSc, thickn, &bsline);
cv::Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/6);
putText(img, title, textOrg, fontFc, fontSc, col, thickn, CV_AA);
if (state.state !=" ")
{
putText(img, "state:", cv::Point( 20,300-60), fontFc, fontSc/2, col, 2, 8);
putText(img, state.state, cv::Point(150,300-60), fontFc, fontSc, col, thickn, CV_AA);
}
if (state.action !=" ")
{
putText(img, "action:", cv::Point( 20,400-60), fontFc, fontSc/2, col, 2, 8);
putText(img, state.action, cv::Point(150,400-60), fontFc, fontSc/1.25, col, thickn, CV_AA);
}
if (state.object !=" ")
{
putText(img, "object:", cv::Point( 20,500-60), fontFc, fontSc/2, col, 2, 8);
putText(img, state.object, cv::Point(150,500-60), fontFc, fontSc/1.25, col, thickn, CV_AA);
}
return img;
};
/**
* Function to create sub-image for the bottom bar (to be filled with status icons)
* @return the sub-image
*/
cv::Mat createBtmImage()
{
cv::Mat img(w_b-w_d/2,w,CV_8UC3,cv::Scalar::all(255));
ROS_INFO_COND(print_level>=4, "Created BOTTOM image with size %i %i", img.rows, img.cols);
return img;
}
public:
/**
* Constructor
*/
explicit BaxterDisplay(string _name) : print_level(0), name(_name), speech(""), it(nh)
{
im_pub = it.advertise("/robot/xdisplay", 1);
l_sub = nh.subscribe( "/action_provider/left/state", 1, &BaxterDisplay::armStateCbL, this);
r_sub = nh.subscribe("/action_provider/right/state", 1, &BaxterDisplay::armStateCbR, this);
s_sub = nh.subscribe("/svox_tts/speech_output",1, &BaxterDisplay::speechCb, this);
nh.param<int> ("/print_level", print_level, 0);
h = 600;
w = 1024;
w_d = 8;
w_b = 80;
l_state.state = "START";
l_state.action = "";
l_state.object = "";
r_state.state = "START";
r_state.action = "";
r_state.object = "";
red = cv::Scalar( 44, 48, 201); // BGR color code
green = cv::Scalar( 60, 160, 60);
blue = cv::Scalar( 200, 162, 77);
nh.param<double>("baxter_display/speech_duration", speech_duration, DEFAULT_DURATION);
displayArmStates();
ROS_INFO_COND(print_level>=3, "Subscribing to %s and %s", l_sub.getTopic().c_str(),
r_sub.getTopic().c_str());
ROS_INFO_COND(print_level>=3, "Subscribing to %s", s_sub.getTopic().c_str());
ROS_INFO_COND(print_level>=3, "Publishing to %s", im_pub.getTopic().c_str());
ROS_INFO_COND(print_level>=1, "Print Level set to %i", print_level);
ROS_INFO_COND(print_level>=1, "Speech Duration set to %g", speech_duration);
ROS_INFO_COND(print_level>=1, "Ready!!");
};
/**
* Function to set the speech to a specific value
* @param s the speech text
*/
void setSpeech(const std::string &s)
{
speech = s;
}
/**
* Function to display arm states into a single image. It combines each individual sub-image
* (the one for the left arm, the one for the right arm, and the bottom status bar)
* @return true/false if success/failure
*/
bool displayArmStates()
{
cv::Mat l = createArmImage("LEFT");
cv::Mat r = createArmImage("RIGHT");
cv::Mat b = createBtmImage();
cv::Mat d_v(r.rows,w_d,CV_8UC3,cv::Scalar::all(80)); // Vertical delimiter
cv::Mat d_h(w_d,w,CV_8UC3,cv::Scalar::all(80)); // Horizontal delimiter
ROS_INFO_COND(print_level>=5, "d_v size %i %i", d_v.rows, d_v.cols);
ROS_INFO_COND(print_level>=5, "d_h size %i %i", d_h.rows, d_h.cols);
cv::Mat res(h,w,CV_8UC3,cv::Scalar(255,100,255));
// Draw sub-image for right arm
r.copyTo(res(cv::Rect(0, 0, r.cols, r.rows)));
// Draw sub-image for the vertical delimiter
d_v.copyTo(res(cv::Rect(r.cols, 0, d_v.cols, d_v.rows)));
// Draw sub-image for left arm
l.copyTo(res(cv::Rect(r.cols+d_v.cols, 0, l.cols, l.rows)));
// Draw sub-image for horizontal delimiter
d_h.copyTo(res(cv::Rect(0, r.rows, d_h.cols, d_h.rows)));
// Draw sub-image for bottom bar
b.copyTo(res(cv::Rect(0, r.rows+d_h.rows, b.cols, b.rows)));
// Eventually draw the speech on top of everything
displaySpeech(res);
// Publish the resulting image
cv_bridge::CvImage msg;
msg.encoding = sensor_msgs::image_encodings::BGR8;
msg.image = res;
im_pub.publish(msg.toImageMsg());
// cv::imshow("res", res);
// cv::waitKey(20);
return true;
};
};
int main(int argc, char ** argv)
{
ros::init(argc, argv, "baxter_display");
BaxterDisplay bd("baxter_display");
ros::Duration(0.2).sleep();
bd.displayArmStates();
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014-2016 Daniel Nicoletti <dantti12@gmail.com>
*
* 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; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "upload_p.h"
#include "common.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTemporaryFile>
using namespace Cutelyst;
QString Upload::filename() const
{
Q_D(const Upload);
return d->filename;
}
QString Upload::contentType() const
{
Q_D(const Upload);
return d->headers.contentType();
}
Headers Upload::headers() const
{
Q_D(const Upload);
return d->headers;
}
bool Upload::save(const QString &newName)
{
Q_D(Upload);
auto temp = qobject_cast<QTemporaryFile *>(d->device);
if (temp && temp->rename(newName)) {
temp->setAutoRemove(false);
return true;
}
bool error = false;
QString fileTemplate = QStringLiteral("%1/qt_temp.XXXXXX");
#ifdef QT_NO_TEMPORARYFILE
QFile out(fileTemplate.arg(QFileInfo(newName).path()));
if (!out.open(QIODevice::ReadWrite)) {
error = true;
}
#else
QTemporaryFile out(fileTemplate.arg(QFileInfo(newName).path()));
if (!out.open()) {
out.setFileTemplate(fileTemplate.arg(QDir::tempPath()));
if (!out.open()) {
error = true;
}
}
#endif
if (error) {
out.close();
setErrorString(QLatin1String("Failed to open file for saving: ") + out.errorString());
qCWarning(CUTELYST_UPLOAD) << errorString();
} else {
qint64 posOrig = d->pos;
seek(0);
char block[4096];
qint64 totalRead = 0;
while (!atEnd()) {
qint64 in = read(block, sizeof(block));
if (in <= 0)
break;
totalRead += in;
if (in != out.write(block, in)) {
setErrorString(QStringLiteral("Failure to write block"));
qCWarning(CUTELYST_UPLOAD) << errorString();
error = true;
break;
}
}
if (error) {
out.remove();
}
if (!error && !out.rename(newName)) {
error = true;
setErrorString(QStringLiteral("Cannot create %1 for output").arg(newName));
qCWarning(CUTELYST_UPLOAD) << errorString();
}
#ifdef QT_NO_TEMPORARYFILE
if (error) {
out.remove();
}
#else
if (!error) {
out.setAutoRemove(false);
}
#endif
seek(posOrig);
}
return !error;
}
QTemporaryFile *Upload::createTemporaryFile(const QString &templateName)
{
#ifndef QT_NO_TEMPORARYFILE
Q_D(Upload);
QTemporaryFile *ret;
if (templateName.isEmpty()) {
ret = new QTemporaryFile(this);
} else {
ret = new QTemporaryFile(templateName, this);
}
if (ret->open()) {
bool error = false;
qint64 posOrig = d->pos;
seek(0);
char block[4096];
qint64 totalRead = 0;
while (!atEnd()) {
qint64 in = read(block, sizeof(block));
if (in <= 0)
break;
totalRead += in;
if (in != ret->write(block, in)) {
setErrorString(QStringLiteral("Failure to write block"));
qCWarning(CUTELYST_UPLOAD) << errorString();
error = true;
break;
}
}
if (error) {
ret->remove();
}
ret->seek(0);
seek(posOrig);
return ret;
} else {
qCWarning(CUTELYST_UPLOAD) << "Failed to open temporary file.";
}
delete ret;
#else
Q_UNUSED(templateName)
#endif
return 0;
}
qint64 Upload::pos() const
{
Q_D(const Upload);
return d->pos;
}
qint64 Upload::size() const
{
Q_D(const Upload);
return d->endOffset - d->startOffset;
}
bool Upload::seek(qint64 pos)
{
Q_D(Upload);
if (pos <= size()) {
QIODevice::seek(pos);
d->pos = pos;
return true;
}
return false;
}
Upload::Upload(UploadPrivate *prv) :
d_ptr(prv)
{
Q_D(Upload);
open(prv->device->openMode());
const QString disposition = prv->headers.header(QStringLiteral("CONTENT_DISPOSITION"));
int start = disposition.indexOf(QLatin1String("name=\""));
if (start != -1) {
start += 6;
int end = disposition.indexOf(QLatin1Char('"'), start);
if (end != -1) {
d->name = disposition.mid(start, end - start);
}
}
start = disposition.indexOf(QLatin1String("filename=\""));
if (start != -1) {
start += 10;
int end = disposition.indexOf(QLatin1Char('"'), start);
if (end != -1) {
d->filename = disposition.mid(start, end - start);
}
}
}
Upload::~Upload()
{
delete d_ptr;
}
QString Upload::name() const
{
Q_D(const Upload);
return d->name;
}
qint64 Upload::readData(char *data, qint64 maxlen)
{
Q_D(Upload);
qint64 posOrig = d->device->pos();
d->device->seek(d->startOffset + d->pos);
qint64 len = d->device->read(data,
qMin(size() - d->pos, maxlen));
d->device->seek(posOrig);
d->pos += len;
return len;
}
qint64 Upload::readLineData(char *data, qint64 maxlen)
{
Q_D(Upload);
qint64 posOrig = d->device->pos();
d->device->seek(d->startOffset + d->pos);
qint64 len = d->device->readLine(data,
qMin(size() - d->pos, maxlen));
d->device->seek(posOrig);
d->pos += len;
return len;
}
qint64 Upload::writeData(const char *data, qint64 maxSize)
{
return -1;
}
#include "moc_upload.cpp"
<commit_msg>Fix Upload not properly saving when it's a QTemporaryFile<commit_after>/*
* Copyright (C) 2014-2016 Daniel Nicoletti <dantti12@gmail.com>
*
* 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; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "upload_p.h"
#include "common.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTemporaryFile>
using namespace Cutelyst;
QString Upload::filename() const
{
Q_D(const Upload);
return d->filename;
}
QString Upload::contentType() const
{
Q_D(const Upload);
return d->headers.contentType();
}
Headers Upload::headers() const
{
Q_D(const Upload);
return d->headers;
}
bool Upload::save(const QString &newName)
{
Q_D(Upload);
bool error = false;
QString fileTemplate = QStringLiteral("%1/qt_temp.XXXXXX");
#ifdef QT_NO_TEMPORARYFILE
QFile out(fileTemplate.arg(QFileInfo(newName).path()));
if (!out.open(QIODevice::ReadWrite)) {
error = true;
}
#else
QTemporaryFile out(fileTemplate.arg(QFileInfo(newName).path()));
if (!out.open()) {
out.setFileTemplate(fileTemplate.arg(QDir::tempPath()));
if (!out.open()) {
error = true;
}
}
#endif
if (error) {
out.close();
setErrorString(QLatin1String("Failed to open file for saving: ") + out.errorString());
qCWarning(CUTELYST_UPLOAD) << errorString();
} else {
qint64 posOrig = d->pos;
seek(0);
char block[4096];
qint64 totalRead = 0;
while (!atEnd()) {
qint64 in = read(block, sizeof(block));
if (in <= 0)
break;
totalRead += in;
if (in != out.write(block, in)) {
setErrorString(QStringLiteral("Failure to write block"));
qCWarning(CUTELYST_UPLOAD) << errorString();
error = true;
break;
}
}
if (error) {
out.remove();
}
if (!error && !out.rename(newName)) {
error = true;
setErrorString(QStringLiteral("Cannot create %1 for output").arg(newName));
qCWarning(CUTELYST_UPLOAD) << errorString();
}
#ifdef QT_NO_TEMPORARYFILE
if (error) {
out.remove();
}
#else
if (!error) {
out.setAutoRemove(false);
}
#endif
seek(posOrig);
}
return !error;
}
QTemporaryFile *Upload::createTemporaryFile(const QString &templateName)
{
#ifndef QT_NO_TEMPORARYFILE
Q_D(Upload);
QTemporaryFile *ret;
if (templateName.isEmpty()) {
ret = new QTemporaryFile(this);
} else {
ret = new QTemporaryFile(templateName, this);
}
if (ret->open()) {
bool error = false;
qint64 posOrig = d->pos;
seek(0);
char block[4096];
qint64 totalRead = 0;
while (!atEnd()) {
qint64 in = read(block, sizeof(block));
if (in <= 0)
break;
totalRead += in;
if (in != ret->write(block, in)) {
setErrorString(QStringLiteral("Failure to write block"));
qCWarning(CUTELYST_UPLOAD) << errorString();
error = true;
break;
}
}
if (error) {
ret->remove();
}
ret->seek(0);
seek(posOrig);
return ret;
} else {
qCWarning(CUTELYST_UPLOAD) << "Failed to open temporary file.";
}
delete ret;
#else
Q_UNUSED(templateName)
#endif
return 0;
}
qint64 Upload::pos() const
{
Q_D(const Upload);
return d->pos;
}
qint64 Upload::size() const
{
Q_D(const Upload);
return d->endOffset - d->startOffset;
}
bool Upload::seek(qint64 pos)
{
Q_D(Upload);
if (pos <= size()) {
QIODevice::seek(pos);
d->pos = pos;
return true;
}
return false;
}
Upload::Upload(UploadPrivate *prv) :
d_ptr(prv)
{
Q_D(Upload);
open(prv->device->openMode());
const QString disposition = prv->headers.header(QStringLiteral("CONTENT_DISPOSITION"));
int start = disposition.indexOf(QLatin1String("name=\""));
if (start != -1) {
start += 6;
int end = disposition.indexOf(QLatin1Char('"'), start);
if (end != -1) {
d->name = disposition.mid(start, end - start);
}
}
start = disposition.indexOf(QLatin1String("filename=\""));
if (start != -1) {
start += 10;
int end = disposition.indexOf(QLatin1Char('"'), start);
if (end != -1) {
d->filename = disposition.mid(start, end - start);
}
}
}
Upload::~Upload()
{
delete d_ptr;
}
QString Upload::name() const
{
Q_D(const Upload);
return d->name;
}
qint64 Upload::readData(char *data, qint64 maxlen)
{
Q_D(Upload);
qint64 posOrig = d->device->pos();
d->device->seek(d->startOffset + d->pos);
qint64 len = d->device->read(data,
qMin(size() - d->pos, maxlen));
d->device->seek(posOrig);
d->pos += len;
return len;
}
qint64 Upload::readLineData(char *data, qint64 maxlen)
{
Q_D(Upload);
qint64 posOrig = d->device->pos();
d->device->seek(d->startOffset + d->pos);
qint64 len = d->device->readLine(data,
qMin(size() - d->pos, maxlen));
d->device->seek(posOrig);
d->pos += len;
return len;
}
qint64 Upload::writeData(const char *data, qint64 maxSize)
{
return -1;
}
#include "moc_upload.cpp"
<|endoftext|> |
<commit_before>#include <zombye/gameplay/states/menu_state.hpp>
#include <zombye/rendering/camera_component.hpp>
using namespace std::string_literals;
zombye::menu_state::menu_state(zombye::state_machine *sm) : sm_(sm) {
}
void zombye::menu_state::enter() {
zombye::log("enter menu state");
auto& camera = sm_->get_game()->entity_manager().emplace(glm::vec3{-2.f, 2.f, -3.0f}, glm::quat{}, glm::vec3{});
camera.emplace<camera_component>(glm::vec3{}, glm::vec3{0.f, 1.f, 0.f});
sm_->get_game()->rendering_system().activate_camera(camera.id());
sm_->get_game()->entity_manager().emplace("dummy", glm::vec3{}, glm::quat{}, glm::vec3{1});
}
void zombye::menu_state::leave() {
zombye::log("leave menu state");
}
void zombye::menu_state::update(float delta_time) {
sm_->use(GAME_STATE_PLAY);
}<commit_msg>remove georgs fancy camera and mesh stuff<commit_after>#include <zombye/gameplay/states/menu_state.hpp>
#include <zombye/rendering/camera_component.hpp>
using namespace std::string_literals;
zombye::menu_state::menu_state(zombye::state_machine *sm) : sm_(sm) {
}
void zombye::menu_state::enter() {
zombye::log("enter menu state");
}
void zombye::menu_state::leave() {
zombye::log("leave menu state");
}
void zombye::menu_state::update(float delta_time) {
sm_->use(GAME_STATE_PLAY);
}
<|endoftext|> |
<commit_before>//
// inpal_algorithm.cpp
// Inverse Palindrome Library
//
// Created by Bryan Triana on 7/22/16.
// Copyright © 2016 Inverse Palindrome. All rights reserved.
//
#include "inpal_algorithm.hpp"
std::size_t inpal::algorithm::gcd(std::size_t a, std::size_t b)
{
while(b!=0)
{
std::size_t r = a%b;
a=b;
b=r;
}
return a;
}
std::size_t inpal::algorithm::modulo(std::size_t a, std::size_t b, std::size_t c)
{
std::size_t x = 1;
while(b>0)
{
if(b%2==1) x=(x*a%c);
a=(a*a)%c;
b/=2;
}
return x%c;
}
std::size_t inpal::algorithm::mulmod(std::size_t a, std::size_t b, std::size_t c)
{
std::size_t x = 0;
std::size_t y = a%c;
while(b>0)
{
if(b%2==1) x=(x+y)%c;
y=(y*2)%c;
b/=2;
}
return x%c;
}
std::size_t inpal::algorithm::pollard_rho(std::size_t num)
{
const std::size_t m = 1000;
std::size_t a, x, y, ys, r, q, d;
do a = rand()%num;
while(a==0||a==num-2);
y = rand()%num;
d = 1;
q = 1;
r = 1;
do
{
x=y;
for(std::size_t i=0; i<=r; i++) y=mulmod(y,a,num);
std::size_t j = 0;
do
{
ys = y;
for(std::size_t i=0; i<=std::min(m, r-j); i++)
{
y=mulmod(y,a,num);
q *= (std::max(x,y)-std::min(x,y))%num;
}
d=gcd(q,num);
j+=m;
}
while(j<r && d==1);
r*=2;
}
while(d==1);
if(d==num)
{
do
{
ys=mulmod(ys,a,num);
d=gcd(std::max(x, ys)-std::min(x,ys), num);
}
while(d==1);
}
return d;
}
std::vector<std::size_t> inpal::algorithm::trial_division(std::size_t num)
{
std::vector<std::size_t> p_fac;
std::size_t prime_factor = 2;
while(prime_factor<=num)
{
if(num%prime_factor==0)
{
p_fac.push_back(prime_factor);
num=num/prime_factor;
}
prime_factor += prime_factor==2 ? 1 : 2;
}
return p_fac;
}
bool inpal::algorithm::pal_test(std::size_t num)
{
std::string rev = std::to_string(num);
//checks if half the reverse of rev is equal to the other half of rev
if(std::equal(rev.begin(), rev.begin()+rev.size()/2, rev.rbegin()))
{
return true;
}
return false;
}
<commit_msg>Update inpal_algorithm.cpp<commit_after>//
// inpal_algorithm.cpp
// Inverse Palindrome Library
//
// Created by Bryan Triana on 7/22/16.
// Copyright © 2016 Inverse Palindrome. All rights reserved.
//
#include "inpal_algorithm.hpp"
std::size_t inpal::algorithm::gcd(std::size_t a, std::size_t b)
{
while(b!=0)
{
std::size_t r = a%b;
a=b;
b=r;
}
return a;
}
std::size_t inpal::algorithm::modulo(std::size_t a, std::size_t b, std::size_t c)
{
std::size_t x = 1;
while(b>0)
{
if(b%2==1) x=(x*a%c);
a=(a*a)%c;
b/=2;
}
return x%c;
}
std::size_t inpal::algorithm::mulmod(std::size_t a, std::size_t b, std::size_t c)
{
std::size_t x = 0;
std::size_t y = a%c;
while(b>0)
{
if(b%2==1) x=(x+y)%c;
y=(y*2)%c;
b/=2;
}
return x%c;
}
std::size_t inpal::algorithm::pollard_rho(std::size_t num)
{
const std::size_t m = 1000;
std::size_t a, x, ys;
do a = rand()%num;
while(a==0||a==num-2);
std::size_t y = rand()%num;
std::size_t d = 1;
std::size_t q = 1;
std::size_t r = 1;
do
{
x=y;
for(std::size_t i=0; i<=r; i++) y=mulmod(y,a,num);
std::size_t j = 0;
do
{
ys = y;
for(std::size_t i=0; i<=std::min(m, r-j); i++)
{
y=mulmod(y,a,num);
q *= (std::max(x,y)-std::min(x,y))%num;
}
d=gcd(q,num);
j+=m;
}
while(j<r && d==1);
r*=2;
}
while(d==1);
if(d==num)
{
do
{
ys=mulmod(ys,a,num);
d=gcd(std::max(x, ys)-std::min(x,ys), num);
}
while(d==1);
}
return d;
}
std::vector<std::size_t> inpal::algorithm::trial_division(std::size_t num)
{
std::vector<std::size_t> p_fac;
std::size_t prime_factor = 2;
while(prime_factor<=num)
{
if(num%prime_factor==0)
{
p_fac.push_back(prime_factor);
num=num/prime_factor;
}
prime_factor += prime_factor==2 ? 1 : 2;
}
return p_fac;
}
bool inpal::algorithm::pal_test(std::size_t num)
{
std::string rev = std::to_string(num);
//checks if half the reverse of rev is equal to the other half of rev
if(std::equal(rev.begin(), rev.begin()+rev.size()/2, rev.rbegin()))
{
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/*
* HashWorker.cpp
*
* Created on: 20 Aug 2013
* Author: nicholas
*/
#include "../include/HashWorker.hpp"
#include "../../commoncpp/src/include/commoncpp.hpp"
#include <GraphicsMagick/Magick++.h>
#include <GraphicsMagick/Magick++/Exception.h>
using std::list;
HashWorker::HashWorker(list<path> *imagePaths,int numOfWorkers = 1) : numOfWorkers(numOfWorkers), imagePaths(*imagePaths) {
if (numOfWorkers > 0) {
} else {
throw "Number of workers must be greater than 0";
}
logger = Logger::getInstance(LOG4CPLUS_TEXT("HashWorker"));
}
void HashWorker::start() {
boost::thread_group tg;
LOG4CPLUS_INFO(logger, "Starting " << numOfWorkers << " worker thread(s)");
for(int i = 0; i < numOfWorkers; i++) {
boost::thread *t = new boost::thread(&HashWorker::doWork, this);
tg.add_thread(t);
LOG4CPLUS_INFO(logger, "Worker thread " << i << " started");
}
tg.join_all();
LOG4CPLUS_INFO(logger, "All worker thread(s) have terminated");
}
void HashWorker::clear() {
boost::mutex::scoped_lock(workQueueMutex);
imagePaths.clear();
}
path HashWorker::getWork() {
boost::mutex::scoped_lock(workQueueMutex);
if (!imagePaths.empty()) {
path next = imagePaths.back();
imagePaths.pop_back();
return next;
} else {
return NULL;
}
}
void HashWorker::doWork() {
ImagePHash iph(32, 9);
int64_t pHash = 0;
std::string filepath;
Database::db_data data;
while (!imagePaths.empty()) {
path image = getWork();
if (image.empty() || !boost::filesystem::exists(image)) {break;}
try {
filepath = image.string();
data = Database::db_data(image);
pHash = iph.getLongHash(filepath);
data.pHash = pHash;
data.status = Database::OK;
LOG4CPLUS_DEBUG(logger, pHash << " - " << image);
db.add(data);
} catch (Magick::Exception &e) {
LOG4CPLUS_WARN(logger, "Failed to process image " << filepath << " : " << e.what());
}
}
}
<commit_msg>Changed get work to return empty path instead of NULL<commit_after>/*
* HashWorker.cpp
*
* Created on: 20 Aug 2013
* Author: nicholas
*/
#include "../include/HashWorker.hpp"
#include "../../commoncpp/src/include/commoncpp.hpp"
#include <GraphicsMagick/Magick++.h>
#include <GraphicsMagick/Magick++/Exception.h>
using std::list;
HashWorker::HashWorker(list<path> *imagePaths,int numOfWorkers = 1) : numOfWorkers(numOfWorkers), imagePaths(*imagePaths) {
if (numOfWorkers > 0) {
} else {
throw "Number of workers must be greater than 0";
}
logger = Logger::getInstance(LOG4CPLUS_TEXT("HashWorker"));
}
void HashWorker::start() {
boost::thread_group tg;
LOG4CPLUS_INFO(logger, "Starting " << numOfWorkers << " worker thread(s)");
for(int i = 0; i < numOfWorkers; i++) {
boost::thread *t = new boost::thread(&HashWorker::doWork, this);
tg.add_thread(t);
LOG4CPLUS_INFO(logger, "Worker thread " << i << " started");
}
tg.join_all();
LOG4CPLUS_INFO(logger, "All worker thread(s) have terminated");
}
void HashWorker::clear() {
boost::mutex::scoped_lock(workQueueMutex);
imagePaths.clear();
}
path HashWorker::getWork() {
boost::mutex::scoped_lock(workQueueMutex);
if (!imagePaths.empty()) {
path next = imagePaths.back();
imagePaths.pop_back();
return next;
} else {
return path();
}
}
void HashWorker::doWork() {
ImagePHash iph(32, 9);
int64_t pHash = 0;
std::string filepath;
Database::db_data data;
while (!imagePaths.empty()) {
path image = getWork();
if (image.empty() || !boost::filesystem::exists(image)) {break;}
try {
filepath = image.string();
data = Database::db_data(image);
pHash = iph.getLongHash(filepath);
data.pHash = pHash;
data.status = Database::OK;
LOG4CPLUS_DEBUG(logger, pHash << " - " << image);
db.add(data);
} catch (Magick::Exception &e) {
LOG4CPLUS_WARN(logger, "Failed to process image " << filepath << " : " << e.what());
}
}
LOG4CPLUS_INFO(logger, "No more work, worker thread shutting down");
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstddef>
#include <string>
#include <initializer_list>
#include <sstream>
#include <iostream>
#include <chrono>
#include "nifty/tools/timer.hxx"
#include "nifty/tools/logging.hxx"
namespace nifty {
namespace graph {
namespace opt{
namespace common{
template<class SOLVER>
class VisitorBase{
public:
typedef SOLVER SolverType;
// maybe the solver ptr will become a shared ptr
virtual void begin(SolverType * solver) = 0;
virtual bool visit(SolverType * solver) = 0;
virtual void end(SolverType * solver) = 0;
virtual void clearLogNames(){
}
virtual void addLogNames(std::initializer_list<std::string> logNames){
}
virtual void setLogValue(const std::size_t logIndex, double logValue){
}
virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){
}
};
/*
template<class SOLVER>
class VerboseVisitor : public VisitorBase<SOLVER>{
public:
typedef SOLVER SolverType;
typedef std::chrono::seconds TimeType;
typedef std::chrono::time_point<std::chrono::steady_clock> TimePointType;
VerboseVisitor(
const int printNth = 1,
const double timeLimit = std::numeric_limits<double>::infinity()
)
: printNth_(printNth),
runOpt_(true),
iter_(1),
timeLimit_(timeLimit),
runtime_(0)
{}
virtual void begin(SolverType * ) {
std::cout<<"begin inference\n";
if(timeLimit_ > 0) {
std::cout << "With Time Limit: \n";
std::cout << timeLimit_ << std::endl;
}
startTime_ = std::chrono::steady_clock::now();
}
virtual bool visit(SolverType * solver) {
runtime_ = std::chrono::duration_cast<TimeType>(std::chrono::steady_clock::now() - startTime_).count();
if(iter_%printNth_ == 0){
auto runtime = std::chrono::duration_cast<TimeType>(
std::chrono::steady_clock::now() - startTime_);
std::stringstream ss;
ss.precision(12);
ss << "Energy: " << std::scientific << solver->currentBestEnergy()<<" ";
ss << "Runtime: " << runtime_ << " ";
for(size_t i=0; i<logNames_.size(); ++i){
ss<<logNames_[i]<<" "<<logValues_[i]<<" ";
}
ss<<"\n";
std::cout<<ss.str();
}
checkRuntime();
++iter_;
return runOpt_;
}
virtual void end(SolverType * ) {
std::cout<<"end inference\n";
}
virtual void clearLogNames(){
logNames_.clear();
logValues_.clear();
}
virtual void addLogNames(std::initializer_list<std::string> logNames){
logNames_.assign(logNames.begin(), logNames.end());
logValues_.resize(logNames.size());
}
virtual void setLogValue(const size_t logIndex, double logValue){
logValues_[logIndex] = logValue;
}
virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){
std::cout<<"LOG["<<int(logLevel)<<"]: "<<logString<<"\n";
}
void stopOptimize(){
runOpt_ = false;
}
private:
bool runOpt_;
int printNth_;
int iter_;
double timeLimit_;
TimePointType startTime_;
size_t runtime_;
std::vector<std::string> logNames_;
std::vector<double> logValues_;
inline void checkRuntime() {
if(runtime_ > timeLimit_) {
std::cout << runtime_ << " " << timeLimit_ << std::endl;
std::cout << "Inference has exceeded time limit and is stopped \n";
stopOptimize();
}
}
};
*/
template<class SOLVER>
class VerboseVisitor : public VisitorBase<SOLVER>{
public:
typedef SOLVER SolverType;
typedef nifty::tools::Timer TimerType;
VerboseVisitor(
const int printNth = 1,
const double timeLimitSolver = std::numeric_limits<double>::infinity(),
const double timeLimitTotal = std::numeric_limits<double>::infinity(),
const nifty::logging::LogLevel logLevel = nifty::logging::LogLevel::WARN
)
: printNth_(printNth),
runOpt_(true),
iter_(1),
timeLimitSolver_(timeLimitSolver),
timeLimitTotal_(timeLimitTotal),
runtimeSolver_(0.0),
runtimeTotal_(0.0),
logLevel_(logLevel)
{}
virtual void begin(SolverType * ) {
std::cout<<"begin inference\n";
timerSolver_.start();
timerTotal_.start();
}
virtual bool visit(SolverType * solver) {
timerSolver_.stop();
timerTotal_.stop();
runtimeTotal_ += timerTotal_.elapsedSeconds();
timerTotal_.reset().start();
runtimeSolver_ += timerSolver_.elapsedSeconds();
if(iter_%printNth_ == 0){
std::stringstream ss;
ss << "E: " << solver->currentBestEnergy() << " ";
ss << "t[s]: " << runtimeSolver_ << " ";
ss << "/ " << runtimeTotal_ << " ";
for(std::size_t i=0; i<logNames_.size(); ++i){
ss<<logNames_[i]<<" "<<logValues_[i]<<" ";
}
ss<<"\n";
std::cout<<ss.str();
}
checkRuntime();
++iter_;
timerSolver_.reset().start();
return runOpt_;
}
virtual void end(SolverType * ) {
std::cout<<"end inference\n";
timerSolver_.stop();
}
virtual void clearLogNames(){
logNames_.clear();
logValues_.clear();
}
virtual void addLogNames(std::initializer_list<std::string> logNames){
logNames_.assign(logNames.begin(), logNames.end());
logValues_.resize(logNames.size());
}
virtual void setLogValue(const std::size_t logIndex, double logValue){
logValues_[logIndex] = logValue;
}
virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){
if(int(logLevel) <= int(logLevel_)){
std::cout<<"LOG["<<nifty::logging::logLevelName(logLevel)<<"]: "<<logString<<"\n";\
}
}
void stopOptimize(){
runOpt_ = false;
}
double runtimeSolver() const{
return runtimeSolver_;
}
double runtimeTotal() const{
return runtimeTotal_;
}
double timeLimitTotal() const{
return timeLimitTotal_;
}
double timeLimitSolver() const{
return timeLimitSolver_;
}
private:
bool runOpt_;
int printNth_;
int iter_;
double timeLimitTotal_;
double timeLimitSolver_;
double runtimeSolver_;
double runtimeTotal_;
nifty::logging::LogLevel logLevel_;
TimerType timerSolver_;
TimerType timerTotal_;
std::vector<std::string> logNames_;
std::vector<double> logValues_;
inline void checkRuntime() {
if(runtimeSolver_ > timeLimitSolver_) {
std::cout << runtimeSolver_ << " " << timeLimitSolver_ << std::endl;
std::cout << "Inference has exceeded solver time limit and is stopped \n";
runOpt_ = false;
}
if(runtimeTotal_ > timeLimitTotal_) {
std::cout << runtimeTotal_ << " " << timeLimitTotal_ << std::endl;
std::cout << "Inference has exceeded total time limit and is stopped \n";
runOpt_ = false;
}
}
};
template<class SOLVER>
class EmptyVisitor : public VisitorBase<SOLVER>{
public:
typedef SOLVER SolverType;
virtual void begin(SolverType * solver) {}
virtual bool visit(SolverType * solver) {return true;}
virtual void end(SolverType * solver) {}
private:
};
template<class SOLVER>
class VisitorProxy{
public:
typedef SOLVER SolverType;
typedef VisitorBase<SOLVER> VisitorBaseTpe;
VisitorProxy(VisitorBaseTpe * visitor)
: visitor_(visitor){
}
void addLogNames(std::initializer_list<std::string> logNames){
if(visitor_ != nullptr){
visitor_->addLogNames(logNames);
}
}
void begin(SolverType * solver) {
if(visitor_ != nullptr){
visitor_->begin(solver);
}
}
bool visit(SolverType * solver) {
if(visitor_ != nullptr){
return visitor_->visit(solver);
}
return true;
}
void end(SolverType * solver) {
if(visitor_ != nullptr){
visitor_->end(solver);
}
}
void clearLogNames() {
if(visitor_ != nullptr){
visitor_->clearLogNames();
}
}
void setLogValue(const std::size_t logIndex, const double logValue) {
if(visitor_ != nullptr){
visitor_->setLogValue(logIndex, logValue);
}
}
void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){
if(visitor_ != nullptr){
visitor_->printLog(logLevel, logString);
}
}
operator bool() const{
return visitor_ != nullptr;
}
private:
VisitorBaseTpe * visitor_;
};
} // namespace nifty::graph::opt::common
} // namespace nifty::graph::opt
} // namespace nifty::graph
} // namespace nifty
<commit_msg>Disable some multicut visitor output<commit_after>#pragma once
#include <cstddef>
#include <string>
#include <initializer_list>
#include <sstream>
#include <iostream>
#include <chrono>
#include "nifty/tools/timer.hxx"
#include "nifty/tools/logging.hxx"
namespace nifty {
namespace graph {
namespace opt{
namespace common{
template<class SOLVER>
class VisitorBase{
public:
typedef SOLVER SolverType;
// maybe the solver ptr will become a shared ptr
virtual void begin(SolverType * solver) = 0;
virtual bool visit(SolverType * solver) = 0;
virtual void end(SolverType * solver) = 0;
virtual void clearLogNames(){
}
virtual void addLogNames(std::initializer_list<std::string> logNames){
}
virtual void setLogValue(const std::size_t logIndex, double logValue){
}
virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){
}
};
/*
template<class SOLVER>
class VerboseVisitor : public VisitorBase<SOLVER>{
public:
typedef SOLVER SolverType;
typedef std::chrono::seconds TimeType;
typedef std::chrono::time_point<std::chrono::steady_clock> TimePointType;
VerboseVisitor(
const int printNth = 1,
const double timeLimit = std::numeric_limits<double>::infinity()
)
: printNth_(printNth),
runOpt_(true),
iter_(1),
timeLimit_(timeLimit),
runtime_(0)
{}
virtual void begin(SolverType * ) {
std::cout<<"begin inference\n";
if(timeLimit_ > 0) {
std::cout << "With Time Limit: \n";
std::cout << timeLimit_ << std::endl;
}
startTime_ = std::chrono::steady_clock::now();
}
virtual bool visit(SolverType * solver) {
runtime_ = std::chrono::duration_cast<TimeType>(std::chrono::steady_clock::now() - startTime_).count();
if(iter_%printNth_ == 0){
auto runtime = std::chrono::duration_cast<TimeType>(
std::chrono::steady_clock::now() - startTime_);
std::stringstream ss;
ss.precision(12);
ss << "Energy: " << std::scientific << solver->currentBestEnergy()<<" ";
ss << "Runtime: " << runtime_ << " ";
for(size_t i=0; i<logNames_.size(); ++i){
ss<<logNames_[i]<<" "<<logValues_[i]<<" ";
}
ss<<"\n";
std::cout<<ss.str();
}
checkRuntime();
++iter_;
return runOpt_;
}
virtual void end(SolverType * ) {
std::cout<<"end inference\n";
}
virtual void clearLogNames(){
logNames_.clear();
logValues_.clear();
}
virtual void addLogNames(std::initializer_list<std::string> logNames){
logNames_.assign(logNames.begin(), logNames.end());
logValues_.resize(logNames.size());
}
virtual void setLogValue(const size_t logIndex, double logValue){
logValues_[logIndex] = logValue;
}
virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){
std::cout<<"LOG["<<int(logLevel)<<"]: "<<logString<<"\n";
}
void stopOptimize(){
runOpt_ = false;
}
private:
bool runOpt_;
int printNth_;
int iter_;
double timeLimit_;
TimePointType startTime_;
size_t runtime_;
std::vector<std::string> logNames_;
std::vector<double> logValues_;
inline void checkRuntime() {
if(runtime_ > timeLimit_) {
std::cout << runtime_ << " " << timeLimit_ << std::endl;
std::cout << "Inference has exceeded time limit and is stopped \n";
stopOptimize();
}
}
};
*/
template<class SOLVER>
class VerboseVisitor : public VisitorBase<SOLVER>{
public:
typedef SOLVER SolverType;
typedef nifty::tools::Timer TimerType;
VerboseVisitor(
const int printNth = 1,
const double timeLimitSolver = std::numeric_limits<double>::infinity(),
const double timeLimitTotal = std::numeric_limits<double>::infinity(),
const nifty::logging::LogLevel logLevel = nifty::logging::LogLevel::WARN
)
: printNth_(printNth),
runOpt_(true),
iter_(1),
timeLimitSolver_(timeLimitSolver),
timeLimitTotal_(timeLimitTotal),
runtimeSolver_(0.0),
runtimeTotal_(0.0),
logLevel_(logLevel)
{}
virtual void begin(SolverType * ) {
timerSolver_.start();
timerTotal_.start();
}
virtual bool visit(SolverType * solver) {
timerSolver_.stop();
timerTotal_.stop();
runtimeTotal_ += timerTotal_.elapsedSeconds();
timerTotal_.reset().start();
runtimeSolver_ += timerSolver_.elapsedSeconds();
if(iter_%printNth_ == 0){
std::stringstream ss;
ss << "E: " << solver->currentBestEnergy() << " ";
ss << "t[s]: " << runtimeSolver_ << " ";
ss << "/ " << runtimeTotal_ << " ";
for(std::size_t i=0; i<logNames_.size(); ++i){
ss<<logNames_[i]<<" "<<logValues_[i]<<" ";
}
ss<<"\n";
std::cout<<ss.str();
}
checkRuntime();
++iter_;
timerSolver_.reset().start();
return runOpt_;
}
virtual void end(SolverType * ) {
timerSolver_.stop();
}
virtual void clearLogNames(){
logNames_.clear();
logValues_.clear();
}
virtual void addLogNames(std::initializer_list<std::string> logNames){
logNames_.assign(logNames.begin(), logNames.end());
logValues_.resize(logNames.size());
}
virtual void setLogValue(const std::size_t logIndex, double logValue){
logValues_[logIndex] = logValue;
}
virtual void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){
if(int(logLevel) <= int(logLevel_)){
std::cout<<"LOG["<<nifty::logging::logLevelName(logLevel)<<"]: "<<logString<<"\n";\
}
}
void stopOptimize(){
runOpt_ = false;
}
double runtimeSolver() const{
return runtimeSolver_;
}
double runtimeTotal() const{
return runtimeTotal_;
}
double timeLimitTotal() const{
return timeLimitTotal_;
}
double timeLimitSolver() const{
return timeLimitSolver_;
}
private:
bool runOpt_;
int printNth_;
int iter_;
double timeLimitTotal_;
double timeLimitSolver_;
double runtimeSolver_;
double runtimeTotal_;
nifty::logging::LogLevel logLevel_;
TimerType timerSolver_;
TimerType timerTotal_;
std::vector<std::string> logNames_;
std::vector<double> logValues_;
inline void checkRuntime() {
if(runtimeSolver_ > timeLimitSolver_) {
std::cout << runtimeSolver_ << " " << timeLimitSolver_ << std::endl;
std::cout << "Inference has exceeded solver time limit and is stopped \n";
runOpt_ = false;
}
if(runtimeTotal_ > timeLimitTotal_) {
std::cout << runtimeTotal_ << " " << timeLimitTotal_ << std::endl;
std::cout << "Inference has exceeded total time limit and is stopped \n";
runOpt_ = false;
}
}
};
template<class SOLVER>
class EmptyVisitor : public VisitorBase<SOLVER>{
public:
typedef SOLVER SolverType;
virtual void begin(SolverType * solver) {}
virtual bool visit(SolverType * solver) {return true;}
virtual void end(SolverType * solver) {}
private:
};
template<class SOLVER>
class VisitorProxy{
public:
typedef SOLVER SolverType;
typedef VisitorBase<SOLVER> VisitorBaseTpe;
VisitorProxy(VisitorBaseTpe * visitor)
: visitor_(visitor){
}
void addLogNames(std::initializer_list<std::string> logNames){
if(visitor_ != nullptr){
visitor_->addLogNames(logNames);
}
}
void begin(SolverType * solver) {
if(visitor_ != nullptr){
visitor_->begin(solver);
}
}
bool visit(SolverType * solver) {
if(visitor_ != nullptr){
return visitor_->visit(solver);
}
return true;
}
void end(SolverType * solver) {
if(visitor_ != nullptr){
visitor_->end(solver);
}
}
void clearLogNames() {
if(visitor_ != nullptr){
visitor_->clearLogNames();
}
}
void setLogValue(const std::size_t logIndex, const double logValue) {
if(visitor_ != nullptr){
visitor_->setLogValue(logIndex, logValue);
}
}
void printLog(const nifty::logging::LogLevel logLevel, const std::string & logString){
if(visitor_ != nullptr){
visitor_->printLog(logLevel, logString);
}
}
operator bool() const{
return visitor_ != nullptr;
}
private:
VisitorBaseTpe * visitor_;
};
} // namespace nifty::graph::opt::common
} // namespace nifty::graph::opt
} // namespace nifty::graph
} // namespace nifty
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <Halide.h>
using namespace Halide;
int main(int argc, char **argv) {
//int W = 64*3, H = 64*3;
const int W = 16, H = 16;
Image<uint16_t> in(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
in(x, y) = rand() & 0xff;
}
}
Var x("x"), y("y");
Image<uint16_t> tent(3, 3);
tent(0, 0) = 1;
tent(0, 1) = 2;
tent(0, 2) = 1;
tent(1, 0) = 2;
tent(1, 1) = 4;
tent(1, 2) = 2;
tent(2, 0) = 1;
tent(2, 1) = 2;
tent(2, 2) = 1;
Func input("input");
input(x, y) = in(clamp(x, 0, W-1), clamp(y, 0, H-1));
input.compute_root();
RDom r(tent);
/* This iterates over r outermost. I.e. the for loop looks like:
* for y:
* for x:
* blur1(x, y) = 0
* for r.y:
* for r.x:
* for y:
* for x:
* blur1(x, y) += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1)
*
* In general, reductions iterate over the reduction domain outermost.
*/
Func blur1("blur1");
blur1(x, y) += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1);
/* This uses an inline reduction, and is the more traditional way
* of scheduling a convolution. "sum" creates an anonymous
* reduction function that is computed within the for loop over x
* in blur2. blur2 isn't actually a reduction. The loop nest looks like:
* for y:
* for x:
* tmp = 0
* for r.y:
* for r.x:
* tmp += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1)
* blur(x, y) = tmp
*/
Func blur2("blur2");
blur2(x, y) = sum(tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1));
Target target = get_target_from_environment();
if (target.features & Target::CUDA) {
// Initialization (basically memset) done in a cuda kernel
blur1.cuda_tile(x, y, 16, 16);
// Summation is done as an outermost loop is done on the cpu
blur1.update().cuda_tile(x, y, 16, 16);
// Summation is done as a sequential loop within each gpu thread
blur2.cuda_tile(x, y, 16, 16);
} else if (target.features & Target::OpenCL) {
printf("using opencl!");
// Initialization (basically memset) done in a cuda kernel
blur1.cuda_tile(x, y, 16, 16);
// Summation is done as an outermost loop is done on the cpu
blur1.update().cuda_tile(x, y, 16, 16);
// Summation is done as a sequential loop within each gpu thread
blur2.cuda_tile(x, y, 16, 16);
} else {
// Take this opportunity to test scheduling the pure dimensions in a reduction
Var xi("xi"), yi("yi");
blur1.tile(x, y, xi, yi, 6, 6);
blur1.update().tile(x, y, xi, yi, 4, 4).vectorize(xi).parallel(y);
blur2.vectorize(x, 4).parallel(y);
}
Image<uint16_t> out1 = blur1.realize(W, H, target);
Image<uint16_t> out2 = blur2.realize(W, H, target);
for (int y = 1; y < H-1; y++) {
for (int x = 1; x < W-1; x++) {
uint16_t correct = (1*in(x-1, y-1) + 2*in(x, y-1) + 1*in(x+1, y-1) +
2*in(x-1, y) + 4*in(x, y) + 2*in(x+1, y) +
1*in(x-1, y+1) + 2*in(x, y+1) + 1*in(x+1, y+1));
if (out1(x, y) != correct) {
printf("out1(%d, %d) = %d instead of %d\n", x, y, out1(x, y), correct);
return -1;
}
if (out2(x, y) != correct) {
printf("out2(%d, %d) = %d instead of %d\n", x, y, out2(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
<commit_msg>Removed debugging code<commit_after>#include <stdio.h>
#include <Halide.h>
using namespace Halide;
int main(int argc, char **argv) {
//int W = 64*3, H = 64*3;
const int W = 16, H = 16;
Image<uint16_t> in(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
in(x, y) = rand() & 0xff;
}
}
Var x("x"), y("y");
Image<uint16_t> tent(3, 3);
tent(0, 0) = 1;
tent(0, 1) = 2;
tent(0, 2) = 1;
tent(1, 0) = 2;
tent(1, 1) = 4;
tent(1, 2) = 2;
tent(2, 0) = 1;
tent(2, 1) = 2;
tent(2, 2) = 1;
Func input("input");
input(x, y) = in(clamp(x, 0, W-1), clamp(y, 0, H-1));
input.compute_root();
RDom r(tent);
/* This iterates over r outermost. I.e. the for loop looks like:
* for y:
* for x:
* blur1(x, y) = 0
* for r.y:
* for r.x:
* for y:
* for x:
* blur1(x, y) += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1)
*
* In general, reductions iterate over the reduction domain outermost.
*/
Func blur1("blur1");
blur1(x, y) += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1);
/* This uses an inline reduction, and is the more traditional way
* of scheduling a convolution. "sum" creates an anonymous
* reduction function that is computed within the for loop over x
* in blur2. blur2 isn't actually a reduction. The loop nest looks like:
* for y:
* for x:
* tmp = 0
* for r.y:
* for r.x:
* tmp += tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1)
* blur(x, y) = tmp
*/
Func blur2("blur2");
blur2(x, y) = sum(tent(r.x, r.y) * input(x + r.x - 1, y + r.y - 1));
Target target = get_target_from_environment();
if (target.features & Target::CUDA) {
// Initialization (basically memset) done in a cuda kernel
blur1.cuda_tile(x, y, 16, 16);
// Summation is done as an outermost loop is done on the cpu
blur1.update().cuda_tile(x, y, 16, 16);
// Summation is done as a sequential loop within each gpu thread
blur2.cuda_tile(x, y, 16, 16);
} else if (target.features & Target::OpenCL) {
// Initialization (basically memset) done in a cuda kernel
blur1.cuda_tile(x, y, 16, 16);
// Summation is done as an outermost loop is done on the cpu
blur1.update().cuda_tile(x, y, 16, 16);
// Summation is done as a sequential loop within each gpu thread
blur2.cuda_tile(x, y, 16, 16);
} else {
// Take this opportunity to test scheduling the pure dimensions in a reduction
Var xi("xi"), yi("yi");
blur1.tile(x, y, xi, yi, 6, 6);
blur1.update().tile(x, y, xi, yi, 4, 4).vectorize(xi).parallel(y);
blur2.vectorize(x, 4).parallel(y);
}
Image<uint16_t> out1 = blur1.realize(W, H, target);
Image<uint16_t> out2 = blur2.realize(W, H, target);
for (int y = 1; y < H-1; y++) {
for (int x = 1; x < W-1; x++) {
uint16_t correct = (1*in(x-1, y-1) + 2*in(x, y-1) + 1*in(x+1, y-1) +
2*in(x-1, y) + 4*in(x, y) + 2*in(x+1, y) +
1*in(x-1, y+1) + 2*in(x, y+1) + 1*in(x+1, y+1));
if (out1(x, y) != correct) {
printf("out1(%d, %d) = %d instead of %d\n", x, y, out1(x, y), correct);
return -1;
}
if (out2(x, y) != correct) {
printf("out2(%d, %d) = %d instead of %d\n", x, y, out2(x, y), correct);
return -1;
}
}
}
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "gtest/gtest.h"
#include "angle_gl.h"
#include "common/utilities.h"
#include "common/angleutils.h"
#include "compiler/translator/VariablePacker.h"
static sh::GLenum types[] = {
GL_FLOAT_MAT4, // 0
GL_FLOAT_MAT2, // 1
GL_FLOAT_VEC4, // 2
GL_INT_VEC4, // 3
GL_BOOL_VEC4, // 4
GL_FLOAT_MAT3, // 5
GL_FLOAT_VEC3, // 6
GL_INT_VEC3, // 7
GL_BOOL_VEC3, // 8
GL_FLOAT_VEC2, // 9
GL_INT_VEC2, // 10
GL_BOOL_VEC2, // 11
GL_FLOAT, // 12
GL_INT, // 13
GL_BOOL, // 14
GL_SAMPLER_2D, // 15
GL_SAMPLER_CUBE, // 16
GL_SAMPLER_EXTERNAL_OES, // 17
GL_SAMPLER_2D_RECT_ARB, // 18
GL_UNSIGNED_INT, // 19
GL_UNSIGNED_INT_VEC2, // 20
GL_UNSIGNED_INT_VEC3, // 21
GL_UNSIGNED_INT_VEC4, // 22
GL_FLOAT_MAT2x3, // 23
GL_FLOAT_MAT2x4, // 24
GL_FLOAT_MAT3x2, // 25
GL_FLOAT_MAT3x4, // 26
GL_FLOAT_MAT4x2, // 27
GL_FLOAT_MAT4x3, // 28
GL_SAMPLER_3D, // 29
GL_SAMPLER_2D_ARRAY, // 30
GL_SAMPLER_2D_SHADOW, // 31
GL_SAMPLER_CUBE_SHADOW, // 32
GL_SAMPLER_2D_ARRAY_SHADOW, // 33
GL_INT_SAMPLER_2D, // 34
GL_INT_SAMPLER_CUBE, // 35
GL_INT_SAMPLER_3D, // 36
GL_INT_SAMPLER_2D_ARRAY, // 37
GL_UNSIGNED_INT_SAMPLER_2D, // 38
GL_UNSIGNED_INT_SAMPLER_CUBE, // 39
GL_UNSIGNED_INT_SAMPLER_3D, // 40
GL_UNSIGNED_INT_SAMPLER_2D_ARRAY, // 41
};
static sh::GLenum nonSqMatTypes[] = {
GL_FLOAT_MAT2x3,
GL_FLOAT_MAT2x4,
GL_FLOAT_MAT3x2,
GL_FLOAT_MAT3x4,
GL_FLOAT_MAT4x2,
GL_FLOAT_MAT4x3
};
TEST(VariablePacking, Pack) {
VariablePacker packer;
std::vector<sh::ShaderVariable> vars;
const int kMaxRows = 16;
// test no vars.
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
for (size_t tt = 0; tt < ArraySize(types); ++tt) {
sh::GLenum type = types[tt];
int num_rows = VariablePacker::GetNumRows(type);
int num_components_per_row = VariablePacker::GetNumComponentsPerRow(type);
// Check 1 of the type.
vars.clear();
vars.push_back(sh::ShaderVariable(type, 0));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// Check exactly the right amount of 1 type as an array.
int num_vars = kMaxRows / num_rows;
vars.clear();
vars.push_back(sh::ShaderVariable(type, num_vars == 1 ? 0 : num_vars));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// test too many
vars.clear();
vars.push_back(sh::ShaderVariable(type, num_vars == 0 ? 0 : (num_vars + 1)));
EXPECT_FALSE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// Check exactly the right amount of 1 type as individual vars.
num_vars = kMaxRows / num_rows *
((num_components_per_row > 2) ? 1 : (4 / num_components_per_row));
vars.clear();
for (int ii = 0; ii < num_vars; ++ii) {
vars.push_back(sh::ShaderVariable(type, 0));
}
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// Check 1 too many.
vars.push_back(sh::ShaderVariable(type, 0));
EXPECT_FALSE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
}
// Test example from GLSL ES 3.0 spec chapter 11.
vars.clear();
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC4, 0));
vars.push_back(sh::ShaderVariable(GL_FLOAT_MAT3, 0));
vars.push_back(sh::ShaderVariable(GL_FLOAT_MAT3, 0));
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC2, 6));
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC2, 4));
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC2, 0));
vars.push_back(sh::ShaderVariable(GL_FLOAT, 3));
vars.push_back(sh::ShaderVariable(GL_FLOAT, 2));
vars.push_back(sh::ShaderVariable(GL_FLOAT, 0));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
}
TEST(VariablePacking, PackSizes) {
for (size_t tt = 0; tt < ArraySize(types); ++tt) {
GLenum type = types[tt];
int expectedComponents = gl::VariableComponentCount(type);
int expectedRows = gl::VariableRowCount(type);
if (type == GL_FLOAT_MAT2) {
expectedComponents = 4;
} else if (gl::IsMatrixType(type)) {
int squareSize = std::max(gl::VariableRowCount(type),
gl::VariableColumnCount(type));
expectedComponents = squareSize;
expectedRows = squareSize;
}
EXPECT_EQ(expectedComponents,
VariablePacker::GetNumComponentsPerRow(type));
EXPECT_EQ(expectedRows, VariablePacker::GetNumRows(type));
}
}
// Check special assumptions about packing non-square mats
TEST(VariablePacking, NonSquareMats) {
for (size_t mt = 0; mt < ArraySize(nonSqMatTypes); ++mt) {
GLenum type = nonSqMatTypes[mt];
int rows = gl::VariableRowCount(type);
int cols = gl::VariableColumnCount(type);
int squareSize = std::max(rows, cols);
std::vector<sh::ShaderVariable> vars;
vars.push_back(sh::ShaderVariable(type, 0));
// Fill columns
for (int row = 0; row < squareSize; row++) {
for (int col = squareSize; col < 4; ++col) {
vars.push_back(sh::ShaderVariable(GL_FLOAT, 0));
}
}
VariablePacker packer;
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(squareSize, vars));
// and one scalar and packing should fail
vars.push_back(sh::ShaderVariable(GL_FLOAT, 0));
EXPECT_FALSE(packer.CheckVariablesWithinPackingLimits(squareSize, vars));
}
}
// Scalar type variables can be packed sharing rows with other variables.
TEST(VariablePacking, ReuseRows)
{
VariablePacker packer;
std::vector<sh::ShaderVariable> vars;
const int kMaxRows = 512;
// uniform bool u0[129];
// uniform bool u1[129];
// uniform bool u2[129];
// uniform bool u3[129];
int num_arrays = 4;
int num_elements_per_array = kMaxRows / num_arrays + 1;
for (int ii = 0; ii < num_arrays; ++ii)
{
vars.push_back(sh::ShaderVariable(GL_BOOL, num_elements_per_array));
}
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
vars.clear();
// uniform vec2 u0[257];
// uniform float u1[257];
// uniform int u1[257];
int num_elements_per_array = kMaxRows / 2 + 1;
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC2, num_elements_per_array));
vars.push_back(sh::ShaderVariable(GL_FLOAT, num_elements_per_array));
vars.push_back(sh::ShaderVariable(GL_INT, num_elements_per_array));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
}
<commit_msg>Fix Chromium compilation error in VariablePack_test.cpp<commit_after>//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "gtest/gtest.h"
#include "angle_gl.h"
#include "common/utilities.h"
#include "common/angleutils.h"
#include "compiler/translator/VariablePacker.h"
static sh::GLenum types[] = {
GL_FLOAT_MAT4, // 0
GL_FLOAT_MAT2, // 1
GL_FLOAT_VEC4, // 2
GL_INT_VEC4, // 3
GL_BOOL_VEC4, // 4
GL_FLOAT_MAT3, // 5
GL_FLOAT_VEC3, // 6
GL_INT_VEC3, // 7
GL_BOOL_VEC3, // 8
GL_FLOAT_VEC2, // 9
GL_INT_VEC2, // 10
GL_BOOL_VEC2, // 11
GL_FLOAT, // 12
GL_INT, // 13
GL_BOOL, // 14
GL_SAMPLER_2D, // 15
GL_SAMPLER_CUBE, // 16
GL_SAMPLER_EXTERNAL_OES, // 17
GL_SAMPLER_2D_RECT_ARB, // 18
GL_UNSIGNED_INT, // 19
GL_UNSIGNED_INT_VEC2, // 20
GL_UNSIGNED_INT_VEC3, // 21
GL_UNSIGNED_INT_VEC4, // 22
GL_FLOAT_MAT2x3, // 23
GL_FLOAT_MAT2x4, // 24
GL_FLOAT_MAT3x2, // 25
GL_FLOAT_MAT3x4, // 26
GL_FLOAT_MAT4x2, // 27
GL_FLOAT_MAT4x3, // 28
GL_SAMPLER_3D, // 29
GL_SAMPLER_2D_ARRAY, // 30
GL_SAMPLER_2D_SHADOW, // 31
GL_SAMPLER_CUBE_SHADOW, // 32
GL_SAMPLER_2D_ARRAY_SHADOW, // 33
GL_INT_SAMPLER_2D, // 34
GL_INT_SAMPLER_CUBE, // 35
GL_INT_SAMPLER_3D, // 36
GL_INT_SAMPLER_2D_ARRAY, // 37
GL_UNSIGNED_INT_SAMPLER_2D, // 38
GL_UNSIGNED_INT_SAMPLER_CUBE, // 39
GL_UNSIGNED_INT_SAMPLER_3D, // 40
GL_UNSIGNED_INT_SAMPLER_2D_ARRAY, // 41
};
static sh::GLenum nonSqMatTypes[] = {
GL_FLOAT_MAT2x3,
GL_FLOAT_MAT2x4,
GL_FLOAT_MAT3x2,
GL_FLOAT_MAT3x4,
GL_FLOAT_MAT4x2,
GL_FLOAT_MAT4x3
};
TEST(VariablePacking, Pack) {
VariablePacker packer;
std::vector<sh::ShaderVariable> vars;
const int kMaxRows = 16;
// test no vars.
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
for (size_t tt = 0; tt < ArraySize(types); ++tt) {
sh::GLenum type = types[tt];
int num_rows = VariablePacker::GetNumRows(type);
int num_components_per_row = VariablePacker::GetNumComponentsPerRow(type);
// Check 1 of the type.
vars.clear();
vars.push_back(sh::ShaderVariable(type, 0));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// Check exactly the right amount of 1 type as an array.
int num_vars = kMaxRows / num_rows;
vars.clear();
vars.push_back(sh::ShaderVariable(type, num_vars == 1 ? 0 : num_vars));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// test too many
vars.clear();
vars.push_back(sh::ShaderVariable(type, num_vars == 0 ? 0 : (num_vars + 1)));
EXPECT_FALSE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// Check exactly the right amount of 1 type as individual vars.
num_vars = kMaxRows / num_rows *
((num_components_per_row > 2) ? 1 : (4 / num_components_per_row));
vars.clear();
for (int ii = 0; ii < num_vars; ++ii) {
vars.push_back(sh::ShaderVariable(type, 0));
}
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// Check 1 too many.
vars.push_back(sh::ShaderVariable(type, 0));
EXPECT_FALSE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
}
// Test example from GLSL ES 3.0 spec chapter 11.
vars.clear();
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC4, 0));
vars.push_back(sh::ShaderVariable(GL_FLOAT_MAT3, 0));
vars.push_back(sh::ShaderVariable(GL_FLOAT_MAT3, 0));
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC2, 6));
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC2, 4));
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC2, 0));
vars.push_back(sh::ShaderVariable(GL_FLOAT, 3));
vars.push_back(sh::ShaderVariable(GL_FLOAT, 2));
vars.push_back(sh::ShaderVariable(GL_FLOAT, 0));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
}
TEST(VariablePacking, PackSizes) {
for (size_t tt = 0; tt < ArraySize(types); ++tt) {
GLenum type = types[tt];
int expectedComponents = gl::VariableComponentCount(type);
int expectedRows = gl::VariableRowCount(type);
if (type == GL_FLOAT_MAT2) {
expectedComponents = 4;
} else if (gl::IsMatrixType(type)) {
int squareSize = std::max(gl::VariableRowCount(type),
gl::VariableColumnCount(type));
expectedComponents = squareSize;
expectedRows = squareSize;
}
EXPECT_EQ(expectedComponents,
VariablePacker::GetNumComponentsPerRow(type));
EXPECT_EQ(expectedRows, VariablePacker::GetNumRows(type));
}
}
// Check special assumptions about packing non-square mats
TEST(VariablePacking, NonSquareMats) {
for (size_t mt = 0; mt < ArraySize(nonSqMatTypes); ++mt) {
GLenum type = nonSqMatTypes[mt];
int rows = gl::VariableRowCount(type);
int cols = gl::VariableColumnCount(type);
int squareSize = std::max(rows, cols);
std::vector<sh::ShaderVariable> vars;
vars.push_back(sh::ShaderVariable(type, 0));
// Fill columns
for (int row = 0; row < squareSize; row++) {
for (int col = squareSize; col < 4; ++col) {
vars.push_back(sh::ShaderVariable(GL_FLOAT, 0));
}
}
VariablePacker packer;
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(squareSize, vars));
// and one scalar and packing should fail
vars.push_back(sh::ShaderVariable(GL_FLOAT, 0));
EXPECT_FALSE(packer.CheckVariablesWithinPackingLimits(squareSize, vars));
}
}
// Scalar type variables can be packed sharing rows with other variables.
TEST(VariablePacking, ReuseRows)
{
VariablePacker packer;
std::vector<sh::ShaderVariable> vars;
const int kMaxRows = 512;
// uniform bool u0[129];
// uniform bool u1[129];
// uniform bool u2[129];
// uniform bool u3[129];
{
int num_arrays = 4;
int num_elements_per_array = kMaxRows / num_arrays + 1;
for (int ii = 0; ii < num_arrays; ++ii)
{
vars.push_back(sh::ShaderVariable(GL_BOOL, num_elements_per_array));
}
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
}
vars.clear();
// uniform vec2 u0[257];
// uniform float u1[257];
// uniform int u1[257];
{
int num_elements_per_array = kMaxRows / 2 + 1;
vars.push_back(sh::ShaderVariable(GL_FLOAT_VEC2, num_elements_per_array));
vars.push_back(sh::ShaderVariable(GL_FLOAT, num_elements_per_array));
vars.push_back(sh::ShaderVariable(GL_INT, num_elements_per_array));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
}
}
<|endoftext|> |
<commit_before>#include <utility>
#include "api/halley_api.h"
#include <halley/plugin/plugin.h>
#include "halley/audio/audio_facade.h"
#include "halley/support/logger.h"
#include "entry/entry_point.h"
using namespace Halley;
void HalleyAPI::assign()
{
Expects(coreInternal != nullptr);
Expects(systemInternal != nullptr);
core = coreInternal;
system = systemInternal.get();
if (videoInternal) {
video = videoInternal.get();
}
if (inputInternal) {
input = inputInternal.get();
}
if (audioInternal) {
audio = audioInternal.get();
}
if (platformInternal) {
platform = platformInternal.get();
}
if (networkInternal) {
network = networkInternal.get();
}
if (movieInternal) {
movie = movieInternal.get();
}
}
void HalleyAPI::init()
{
if (systemInternal) {
systemInternal->init();
}
if (videoInternal) {
videoInternal->init();
}
if (inputInternal) {
inputInternal->init();
}
if (audioOutputInternal) {
audioOutputInternal->init();
}
if (audioInternal) {
audioInternal->init();
}
if (platformInternal) {
platformInternal->init();
}
if (networkInternal) {
networkInternal->init();
}
if (movieInternal) {
movieInternal->init();
}
}
void HalleyAPI::deInit()
{
if (movieInternal) {
movieInternal->deInit();
}
if (networkInternal) {
networkInternal->deInit();
}
if (platformInternal) {
platformInternal->deInit();
}
if (audioInternal) {
audioInternal->deInit();
}
if (audioOutputInternal) {
audioOutputInternal->deInit();
}
if (inputInternal) {
inputInternal->deInit();
}
if (videoInternal) {
videoInternal->deInit();
}
if (systemInternal) {
systemInternal->deInit();
}
}
std::unique_ptr<HalleyAPI> HalleyAPI::create(CoreAPIInternal* core, int flags)
{
auto api = std::make_unique<HalleyAPI>();
api->coreInternal = core;
HalleyAPIFlags::Flags flagList[] = { HalleyAPIFlags::System, HalleyAPIFlags::Video, HalleyAPIFlags::Input, HalleyAPIFlags::Audio, HalleyAPIFlags::Network, HalleyAPIFlags::Platform, HalleyAPIFlags::Movie };
PluginType pluginTypes[] = { PluginType::SystemAPI, PluginType::GraphicsAPI, PluginType::InputAPI, PluginType::AudioOutputAPI, PluginType::NetworkAPI, PluginType::PlatformAPI, PluginType::MovieAPI };
String names[] = { "System", "Graphics", "Input", "AudioOutput", "Network", "Platform", "Movie" };
constexpr size_t n = std::end(flagList) - std::begin(flagList);
for (size_t i = 0; i < n; ++i) {
if (flags & flagList[i] || flagList[i] == HalleyAPIFlags::System) {
auto plugins = core->getPlugins(pluginTypes[i]);
if (!plugins.empty()) {
Logger::logInfo(names[i] + " plugin: " + plugins[0]->getName());
api->setAPI(pluginTypes[i], plugins[0]->createAPI(api->systemInternal.get()));
} else {
throw Exception("No suitable " + names[i] + " plugins found.", HalleyExceptions::Core);
}
}
}
api->assign();
return api;
}
void HalleyAPI::setAPI(PluginType pluginType, HalleyAPIInternal* api)
{
switch (pluginType) {
case PluginType::SystemAPI:
systemInternal.reset(dynamic_cast<SystemAPIInternal*>(api));
return;
case PluginType::InputAPI:
inputInternal.reset(dynamic_cast<InputAPIInternal*>(api));
return;
case PluginType::GraphicsAPI:
videoInternal.reset(dynamic_cast<VideoAPIInternal*>(api));
return;
case PluginType::AudioOutputAPI:
audioOutputInternal.reset(dynamic_cast<AudioOutputAPIInternal*>(api));
audioInternal = std::make_unique<AudioFacade>(*audioOutputInternal, *systemInternal);
return;
case PluginType::PlatformAPI:
platformInternal.reset(dynamic_cast<PlatformAPIInternal*>(api));
return;
case PluginType::NetworkAPI:
networkInternal.reset(dynamic_cast<NetworkAPIInternal*>(api));
return;
case PluginType::MovieAPI:
movieInternal.reset(dynamic_cast<MovieAPIInternal*>(api));
return;
}
}
HalleyAPI& HalleyAPI::operator=(const HalleyAPI& other) = default;
std::unique_ptr<HalleyAPI> HalleyAPI::clone() const
{
auto api = std::make_unique<HalleyAPI>();
*api = *this;
return api;
}
void HalleyAPI::replaceCoreAPI(CoreAPIInternal* coreAPI)
{
coreInternal = coreAPI;
core = coreAPI;
}
uint32_t Halley::getHalleyDLLAPIVersion()
{
return 204;
}
<commit_msg>Bump version<commit_after>#include <utility>
#include "api/halley_api.h"
#include <halley/plugin/plugin.h>
#include "halley/audio/audio_facade.h"
#include "halley/support/logger.h"
#include "entry/entry_point.h"
using namespace Halley;
void HalleyAPI::assign()
{
Expects(coreInternal != nullptr);
Expects(systemInternal != nullptr);
core = coreInternal;
system = systemInternal.get();
if (videoInternal) {
video = videoInternal.get();
}
if (inputInternal) {
input = inputInternal.get();
}
if (audioInternal) {
audio = audioInternal.get();
}
if (platformInternal) {
platform = platformInternal.get();
}
if (networkInternal) {
network = networkInternal.get();
}
if (movieInternal) {
movie = movieInternal.get();
}
}
void HalleyAPI::init()
{
if (systemInternal) {
systemInternal->init();
}
if (videoInternal) {
videoInternal->init();
}
if (inputInternal) {
inputInternal->init();
}
if (audioOutputInternal) {
audioOutputInternal->init();
}
if (audioInternal) {
audioInternal->init();
}
if (platformInternal) {
platformInternal->init();
}
if (networkInternal) {
networkInternal->init();
}
if (movieInternal) {
movieInternal->init();
}
}
void HalleyAPI::deInit()
{
if (movieInternal) {
movieInternal->deInit();
}
if (networkInternal) {
networkInternal->deInit();
}
if (platformInternal) {
platformInternal->deInit();
}
if (audioInternal) {
audioInternal->deInit();
}
if (audioOutputInternal) {
audioOutputInternal->deInit();
}
if (inputInternal) {
inputInternal->deInit();
}
if (videoInternal) {
videoInternal->deInit();
}
if (systemInternal) {
systemInternal->deInit();
}
}
std::unique_ptr<HalleyAPI> HalleyAPI::create(CoreAPIInternal* core, int flags)
{
auto api = std::make_unique<HalleyAPI>();
api->coreInternal = core;
HalleyAPIFlags::Flags flagList[] = { HalleyAPIFlags::System, HalleyAPIFlags::Video, HalleyAPIFlags::Input, HalleyAPIFlags::Audio, HalleyAPIFlags::Network, HalleyAPIFlags::Platform, HalleyAPIFlags::Movie };
PluginType pluginTypes[] = { PluginType::SystemAPI, PluginType::GraphicsAPI, PluginType::InputAPI, PluginType::AudioOutputAPI, PluginType::NetworkAPI, PluginType::PlatformAPI, PluginType::MovieAPI };
String names[] = { "System", "Graphics", "Input", "AudioOutput", "Network", "Platform", "Movie" };
constexpr size_t n = std::end(flagList) - std::begin(flagList);
for (size_t i = 0; i < n; ++i) {
if (flags & flagList[i] || flagList[i] == HalleyAPIFlags::System) {
auto plugins = core->getPlugins(pluginTypes[i]);
if (!plugins.empty()) {
Logger::logInfo(names[i] + " plugin: " + plugins[0]->getName());
api->setAPI(pluginTypes[i], plugins[0]->createAPI(api->systemInternal.get()));
} else {
throw Exception("No suitable " + names[i] + " plugins found.", HalleyExceptions::Core);
}
}
}
api->assign();
return api;
}
void HalleyAPI::setAPI(PluginType pluginType, HalleyAPIInternal* api)
{
switch (pluginType) {
case PluginType::SystemAPI:
systemInternal.reset(dynamic_cast<SystemAPIInternal*>(api));
return;
case PluginType::InputAPI:
inputInternal.reset(dynamic_cast<InputAPIInternal*>(api));
return;
case PluginType::GraphicsAPI:
videoInternal.reset(dynamic_cast<VideoAPIInternal*>(api));
return;
case PluginType::AudioOutputAPI:
audioOutputInternal.reset(dynamic_cast<AudioOutputAPIInternal*>(api));
audioInternal = std::make_unique<AudioFacade>(*audioOutputInternal, *systemInternal);
return;
case PluginType::PlatformAPI:
platformInternal.reset(dynamic_cast<PlatformAPIInternal*>(api));
return;
case PluginType::NetworkAPI:
networkInternal.reset(dynamic_cast<NetworkAPIInternal*>(api));
return;
case PluginType::MovieAPI:
movieInternal.reset(dynamic_cast<MovieAPIInternal*>(api));
return;
}
}
HalleyAPI& HalleyAPI::operator=(const HalleyAPI& other) = default;
std::unique_ptr<HalleyAPI> HalleyAPI::clone() const
{
auto api = std::make_unique<HalleyAPI>();
*api = *this;
return api;
}
void HalleyAPI::replaceCoreAPI(CoreAPIInternal* coreAPI)
{
coreInternal = coreAPI;
core = coreAPI;
}
uint32_t Halley::getHalleyDLLAPIVersion()
{
return 205;
}
<|endoftext|> |
<commit_before>#include <string>
#include <array>
#include <vector>
#include <memory>
#include <functional>
#include <algorithm>
#include "Vec2i.h"
#include "IMapElement.h"
#include "CDoorway.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "CCharacterArchetype.h"
#include "CCharacter.h"
#include "CMonster.h"
#include "CElixirFountain.h"
#include "CDoorway.h"
#include "CItem.h"
#include <iostream>
#include <sstream>
#include <CMonsterGenerator.h>
#include "CStorageItem.h"
#include "CRandomWorldGenerator.h"
namespace Knights {
void CMap::endOfTurn() {
for (int y = 0; y < kMapSize; ++y) {
for (int x = 0; x < kMapSize; ++x) {
if (mActors[y][x] != nullptr) {
mActors[y][x]->endOfTurn();
}
}
}
actors.erase(std::remove_if(actors.begin(), actors.end(),
[](std::shared_ptr<CActor> actor) { return !actor->isAlive(); }
), actors.end());
}
CMap::CMap(const std::string &mapData, std::shared_ptr<CGameDelegate> aGameDelegate)
: mGameDelegate(aGameDelegate) {
char element;
std::shared_ptr<CActor> actor = nullptr;
auto heroArchetype = std::make_shared<CCharacterArchetype>( 5, 2, 20, 7, '^', "Hero");
auto monsterArchetype = std::make_shared<CCharacterArchetype>( 4, 1, 10, 3, '@', "Monster");
auto friends = std::make_shared<CTeam>("Heroes");
auto foes = std::make_shared<CTeam>("Enemies");
int pos = 0;
for (int y = 0; y < kMapSize; ++y) {
for (int x = 0; x < kMapSize; ++x) {
element = mapData[ pos ];
block[y][x] = false;
map[y][x] = nullptr;
mElement[y][x] = element;
mItems[ y ][ x ] = nullptr;
switch (element) {
default:
case '0':
case 'O':
case '=':
case '_':
case '-':
case '(':
case ')':
case '2':
case '{':
case '}':
case '7':
case '!':
case 'H':
block[y][x] = false;
break;
case 't':
block[y][x] = false;
mElement[ y ][ x ] = '.';
mItems[ y ][ x ] = std::make_shared<CItem>("Sword of sorrow", 't', false, [&](std::shared_ptr<CActor> aActor, std::shared_ptr<CMap> aMap){
auto target = getActorTargetPosition(aActor);
attack( aActor, target, true );
});
break;
case 'u':
block[y][x] = false;
mElement[ y ][ x ] = '.';
mItems[ y ][ x ] = std::make_shared<CStorageItem>("Quiver", 'u', false, [&](std::shared_ptr<CActor> aActor, std::shared_ptr<CMap> aMap){}, 5);
break;
case '+':
block[y][x] = false;
mElement[ y ][ x ] = '.';
mItems[ y ][ x ] = std::make_shared<CItem>("The holy health", '+', true, [&](std::shared_ptr<CActor> aActor, std::shared_ptr<CMap> aMap){
aActor->addHP(5);
});
break;
case 'y':
block[y][x] = false;
mElement[ y ][ x ] = '.';
//The need for RTTI creeps again...
mItems[ y ][ x ] = std::make_shared<CItem>("Crossbow of damnation", 'y', false, [&](std::shared_ptr<CActor> aActor, std::shared_ptr<CMap> aMap){
auto quiver = aActor->getItemWithSymbol('u');
if ( quiver == nullptr || (static_cast<CStorageItem*>(&(*quiver)))->getAmount() == 0 ) {
return;
}
auto target = projectLineOfSight( getActorTargetPosition(aActor), aActor->getDirection() );
if ( !( target == aActor->getPosition() ) ) {
attack( aActor, target, false );
}
mGameDelegate->onProjectileHit( target);
if ( static_cast<CStorageItem*>(&(*quiver))->add( -1 ) == 0) {
aActor->removeItemFromInventory( quiver );
}
});
break;
case '1':
case '#':
case '/':
case '\\':
case '%':
case 'X':
case '|':
case 'Y':
case 'Z':
case 'S':
case '>':
case '<':
case '\'':
block[y][x] = true;
break;
case '~':
block[y][x] = false;
break;
case '4':
actor = mAvatar = std::make_shared<CCharacter>( heroArchetype, friends, getLastestId());
mElement[ y ][ x ] = '.';
break;
case '9':
case '*':
{
std::shared_ptr<CDoorway> doorway = std::make_shared<CDoorway>(
element == '9' ? EDoorwayFunction::kExit
: EDoorwayFunction::kEntry);
map[y][x] = doorway;
char elementView = map[y][x]->getView();
mElement[y][x] = elementView;
}
break;
case 'J':
case '6':
case '5':
actor = std::make_shared<CMonster>( monsterArchetype, foes, getLastestId());
mElement[ y ][ x ] = '.';
break;
case 'G':
actor = std::make_shared<CMonsterGenerator>(getLastestId(), 5);
mElement[ y ][ x ] = '.';
break;
}
if (actor != nullptr) {
actors.push_back(actor);
mActors[y][x] = actor;
actor->setPosition({x, y});
actor = nullptr;
}
++pos;
}
//skip \n
++pos;
}
}
std::shared_ptr<CActor> CMap::attack(std::shared_ptr<CActor> actor, Vec2i position,
bool mutual) {
std::shared_ptr<CActor> otherActor = getActorAt(position);
if (otherActor == nullptr) {
return nullptr;
}
if (actor->getTeam() != otherActor->getTeam()) {
actor->performAttack(otherActor);
if (actor == mAvatar) {
mGameDelegate->onPlayerAttacked(actor->getPosition());
mGameDelegate->onMonsterDamaged(otherActor->getPosition());
} else {
mGameDelegate->onMonsterAttacked(actor->getPosition());
mGameDelegate->onPlayerDamaged(otherActor->getPosition());
}
if (mutual) {
otherActor->performAttack(actor);
if (otherActor == mAvatar) {
mGameDelegate->onPlayerAttacked(otherActor->getPosition());
mGameDelegate->onMonsterDamaged(otherActor->getPosition());
} else {
mGameDelegate->onMonsterAttacked(otherActor->getPosition());
mGameDelegate->onPlayerDamaged(otherActor->getPosition());
}
}
if (!actor->isAlive()) {
auto position = actor->getPosition();
mActors[position.y][position.x] = nullptr;
if (actor == mAvatar) {
mGameDelegate->onPlayerDied(actor->getPosition());
} else {
mGameDelegate->onMonsterDied(actor->getPosition());
}
}
if (!otherActor->isAlive()) {
auto position = otherActor->getPosition();
mActors[position.y][position.x] = nullptr;
if (otherActor == mAvatar) {
mGameDelegate->onPlayerDied(otherActor->getPosition());
} else {
mGameDelegate->onMonsterDied(otherActor->getPosition());
}
}
}
return otherActor;
}
Vec2i CMap::getActorTargetPosition(std::shared_ptr<CActor> actor) {
auto position = actor->getPosition();
auto offset = mapOffsetForDirection( actor->getDirection() );
return { position.x + offset.x, position.y + offset.y };
}
void CMap::move(EDirection d, std::shared_ptr<CActor> actor) {
if (!actor->canMove()) {
return;
}
auto position = actor->getPosition();
auto offset = mapOffsetForDirection( d );
auto newPosition = Vec2i{ position.x + offset.x, position.y + offset.y };
if (!isBlockAt(newPosition)) {
moveActor(position, newPosition, actor);
actor->onMove();
}
}
bool CMap::isValid(const Vec2i& p) {
if (p.x < 0 || p.x >= kMapSize || p.y < 0 || p.y >= kMapSize) {
return false;
}
return true;
}
bool CMap::isBlockAt(const Vec2i& p) {
if (!isValid(p)) {
return true;
}
if (mActors[p.y][p.x] != nullptr) {
return true;
}
return block[p.y][p.x];
}
std::shared_ptr<CActor> CMap::getActorAt(Vec2i position) {
if ( isValid( position ) ) {
return mActors[position.y][position.x];
} else {
return nullptr;
}
}
char CMap::getElementAt(const Vec2i& p) {
if ( mItems[ p.y ][ p.x ] != nullptr ) {
return mItems[ p.y ][ p.x ]->getView();
}
return mElement[p.y][p.x];
}
std::vector<std::shared_ptr<CActor>> CMap::getActors() {
return actors;
}
std::shared_ptr<CActor> CMap::getAvatar() {
return mAvatar;
}
void CMap::setActorAt(Vec2i position, std::shared_ptr<CActor> actor) {
mActors[position.y][position.x] = actor;
}
bool CMap::isLevelFinished() {
auto position = this->getAvatar()->getPosition();
return mElement[position.y][position.x] == 'E';
}
void CMap::moveActor(Vec2i from, Vec2i to, std::shared_ptr<CActor> actor) {
mActors[from.y][from.x] = nullptr;
mActors[to.y][to.x] = actor;
actor->setPosition(to);
}
Vec2i CMap::projectLineOfSight(Vec2i aPosition, EDirection aDirection) {
auto offset = mapOffsetForDirection( aDirection );
auto position = aPosition;
std::shared_ptr<CActor> toReturn = nullptr;
auto previous = position;
while ( isValid( position ) && !isBlockAt( position ) ) {
previous = position;
position.x += offset.x;
position.y += offset.y;
auto actor = getActorAt( position );
if ( actor != nullptr ) {
return actor->getPosition();
}
}
return previous;
}
void CMap::giveItemAt(Vec2i from, std::shared_ptr<CActor> actor) {
if ( mItems[ from.y ][ from.x ] != nullptr ) {
auto item = mItems[ from.y ][ from.x ];
mItems[ from.y ][ from.x ] = nullptr;
actor->giveItem( item );
}
}
std::shared_ptr<Knights::CItem> CMap::getItemAt( Vec2i from ) {
return mItems[ from.y ][ from.x ];
}
void CMap::putItemAt(std::shared_ptr<CItem> aItem, Vec2i aDestination) {
if ( mItems[ aDestination.y ][ aDestination.x ] == nullptr ) {
mItems[ aDestination.y ][ aDestination.x ] = aItem;
}
}
void CMap::addActorAt(std::shared_ptr<CActor> actor, const Vec2i &position) {
mElement[ position.y ][ position.x ] = '.';
actors.push_back(actor);
mActors[ position.y][ position.x] = actor;
actor->setPosition( position );
}
int CMap::getLastestId() {
return ++mCurrentId;
}
}
<commit_msg>Select back the crossbow when the actor empties a quiver<commit_after>#include <string>
#include <array>
#include <vector>
#include <memory>
#include <functional>
#include <algorithm>
#include "Vec2i.h"
#include "IMapElement.h"
#include "CDoorway.h"
#include "CTeam.h"
#include "CItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "CCharacterArchetype.h"
#include "CCharacter.h"
#include "CMonster.h"
#include "CElixirFountain.h"
#include "CDoorway.h"
#include "CItem.h"
#include <iostream>
#include <sstream>
#include <CMonsterGenerator.h>
#include "CStorageItem.h"
#include "CRandomWorldGenerator.h"
namespace Knights {
void CMap::endOfTurn() {
for (int y = 0; y < kMapSize; ++y) {
for (int x = 0; x < kMapSize; ++x) {
if (mActors[y][x] != nullptr) {
mActors[y][x]->endOfTurn();
}
}
}
actors.erase(std::remove_if(actors.begin(), actors.end(),
[](std::shared_ptr<CActor> actor) { return !actor->isAlive(); }
), actors.end());
}
CMap::CMap(const std::string &mapData, std::shared_ptr<CGameDelegate> aGameDelegate)
: mGameDelegate(aGameDelegate) {
char element;
std::shared_ptr<CActor> actor = nullptr;
auto heroArchetype = std::make_shared<CCharacterArchetype>( 5, 2, 20, 7, '^', "Hero");
auto monsterArchetype = std::make_shared<CCharacterArchetype>( 4, 1, 10, 3, '@', "Monster");
auto friends = std::make_shared<CTeam>("Heroes");
auto foes = std::make_shared<CTeam>("Enemies");
int pos = 0;
for (int y = 0; y < kMapSize; ++y) {
for (int x = 0; x < kMapSize; ++x) {
element = mapData[ pos ];
block[y][x] = false;
map[y][x] = nullptr;
mElement[y][x] = element;
mItems[ y ][ x ] = nullptr;
switch (element) {
default:
case '0':
case 'O':
case '=':
case '_':
case '-':
case '(':
case ')':
case '2':
case '{':
case '}':
case '7':
case '!':
case 'H':
block[y][x] = false;
break;
case 't':
block[y][x] = false;
mElement[ y ][ x ] = '.';
mItems[ y ][ x ] = std::make_shared<CItem>("Sword of sorrow", 't', false, [&](std::shared_ptr<CActor> aActor, std::shared_ptr<CMap> aMap){
auto target = getActorTargetPosition(aActor);
attack( aActor, target, true );
});
break;
case 'u':
block[y][x] = false;
mElement[ y ][ x ] = '.';
mItems[ y ][ x ] = std::make_shared<CStorageItem>("Quiver", 'u', false, [&](std::shared_ptr<CActor> aActor, std::shared_ptr<CMap> aMap){}, 5);
break;
case '+':
block[y][x] = false;
mElement[ y ][ x ] = '.';
mItems[ y ][ x ] = std::make_shared<CItem>("The holy health", '+', true, [&](std::shared_ptr<CActor> aActor, std::shared_ptr<CMap> aMap){
aActor->addHP(5);
});
break;
case 'y':
block[y][x] = false;
mElement[ y ][ x ] = '.';
//The need for RTTI creeps again...
mItems[ y ][ x ] = std::make_shared<CItem>("Crossbow of damnation", 'y', false, [&](std::shared_ptr<CActor> aActor, std::shared_ptr<CMap> aMap){
auto quiver = aActor->getItemWithSymbol('u');
if ( quiver == nullptr || (static_cast<CStorageItem*>(&(*quiver)))->getAmount() == 0 ) {
return;
}
auto target = projectLineOfSight( getActorTargetPosition(aActor), aActor->getDirection() );
if ( !( target == aActor->getPosition() ) ) {
attack( aActor, target, false );
}
mGameDelegate->onProjectileHit( target);
if ( static_cast<CStorageItem*>(&(*quiver))->add( -1 ) == 0) {
aActor->removeItemFromInventory( quiver );
aActor->suggestCurrentItem('y');
}
});
break;
case '1':
case '#':
case '/':
case '\\':
case '%':
case 'X':
case '|':
case 'Y':
case 'Z':
case 'S':
case '>':
case '<':
case '\'':
block[y][x] = true;
break;
case '~':
block[y][x] = false;
break;
case '4':
actor = mAvatar = std::make_shared<CCharacter>( heroArchetype, friends, getLastestId());
mElement[ y ][ x ] = '.';
break;
case '9':
case '*':
{
std::shared_ptr<CDoorway> doorway = std::make_shared<CDoorway>(
element == '9' ? EDoorwayFunction::kExit
: EDoorwayFunction::kEntry);
map[y][x] = doorway;
char elementView = map[y][x]->getView();
mElement[y][x] = elementView;
}
break;
case 'J':
case '6':
case '5':
actor = std::make_shared<CMonster>( monsterArchetype, foes, getLastestId());
mElement[ y ][ x ] = '.';
break;
case 'G':
actor = std::make_shared<CMonsterGenerator>(getLastestId(), 5);
mElement[ y ][ x ] = '.';
break;
}
if (actor != nullptr) {
actors.push_back(actor);
mActors[y][x] = actor;
actor->setPosition({x, y});
actor = nullptr;
}
++pos;
}
//skip \n
++pos;
}
}
std::shared_ptr<CActor> CMap::attack(std::shared_ptr<CActor> actor, Vec2i position,
bool mutual) {
std::shared_ptr<CActor> otherActor = getActorAt(position);
if (otherActor == nullptr) {
return nullptr;
}
if (actor->getTeam() != otherActor->getTeam()) {
actor->performAttack(otherActor);
if (actor == mAvatar) {
mGameDelegate->onPlayerAttacked(actor->getPosition());
mGameDelegate->onMonsterDamaged(otherActor->getPosition());
} else {
mGameDelegate->onMonsterAttacked(actor->getPosition());
mGameDelegate->onPlayerDamaged(otherActor->getPosition());
}
if (mutual) {
otherActor->performAttack(actor);
if (otherActor == mAvatar) {
mGameDelegate->onPlayerAttacked(otherActor->getPosition());
mGameDelegate->onMonsterDamaged(otherActor->getPosition());
} else {
mGameDelegate->onMonsterAttacked(otherActor->getPosition());
mGameDelegate->onPlayerDamaged(otherActor->getPosition());
}
}
if (!actor->isAlive()) {
auto position = actor->getPosition();
mActors[position.y][position.x] = nullptr;
if (actor == mAvatar) {
mGameDelegate->onPlayerDied(actor->getPosition());
} else {
mGameDelegate->onMonsterDied(actor->getPosition());
}
}
if (!otherActor->isAlive()) {
auto position = otherActor->getPosition();
mActors[position.y][position.x] = nullptr;
if (otherActor == mAvatar) {
mGameDelegate->onPlayerDied(otherActor->getPosition());
} else {
mGameDelegate->onMonsterDied(otherActor->getPosition());
}
}
}
return otherActor;
}
Vec2i CMap::getActorTargetPosition(std::shared_ptr<CActor> actor) {
auto position = actor->getPosition();
auto offset = mapOffsetForDirection( actor->getDirection() );
return { position.x + offset.x, position.y + offset.y };
}
void CMap::move(EDirection d, std::shared_ptr<CActor> actor) {
if (!actor->canMove()) {
return;
}
auto position = actor->getPosition();
auto offset = mapOffsetForDirection( d );
auto newPosition = Vec2i{ position.x + offset.x, position.y + offset.y };
if (!isBlockAt(newPosition)) {
moveActor(position, newPosition, actor);
actor->onMove();
}
}
bool CMap::isValid(const Vec2i& p) {
if (p.x < 0 || p.x >= kMapSize || p.y < 0 || p.y >= kMapSize) {
return false;
}
return true;
}
bool CMap::isBlockAt(const Vec2i& p) {
if (!isValid(p)) {
return true;
}
if (mActors[p.y][p.x] != nullptr) {
return true;
}
return block[p.y][p.x];
}
std::shared_ptr<CActor> CMap::getActorAt(Vec2i position) {
if ( isValid( position ) ) {
return mActors[position.y][position.x];
} else {
return nullptr;
}
}
char CMap::getElementAt(const Vec2i& p) {
if ( mItems[ p.y ][ p.x ] != nullptr ) {
return mItems[ p.y ][ p.x ]->getView();
}
return mElement[p.y][p.x];
}
std::vector<std::shared_ptr<CActor>> CMap::getActors() {
return actors;
}
std::shared_ptr<CActor> CMap::getAvatar() {
return mAvatar;
}
void CMap::setActorAt(Vec2i position, std::shared_ptr<CActor> actor) {
mActors[position.y][position.x] = actor;
}
bool CMap::isLevelFinished() {
auto position = this->getAvatar()->getPosition();
return mElement[position.y][position.x] == 'E';
}
void CMap::moveActor(Vec2i from, Vec2i to, std::shared_ptr<CActor> actor) {
mActors[from.y][from.x] = nullptr;
mActors[to.y][to.x] = actor;
actor->setPosition(to);
}
Vec2i CMap::projectLineOfSight(Vec2i aPosition, EDirection aDirection) {
auto offset = mapOffsetForDirection( aDirection );
auto position = aPosition;
std::shared_ptr<CActor> toReturn = nullptr;
auto previous = position;
while ( isValid( position ) && !isBlockAt( position ) ) {
previous = position;
position.x += offset.x;
position.y += offset.y;
auto actor = getActorAt( position );
if ( actor != nullptr ) {
return actor->getPosition();
}
}
return previous;
}
void CMap::giveItemAt(Vec2i from, std::shared_ptr<CActor> actor) {
if ( mItems[ from.y ][ from.x ] != nullptr ) {
auto item = mItems[ from.y ][ from.x ];
mItems[ from.y ][ from.x ] = nullptr;
actor->giveItem( item );
}
}
std::shared_ptr<Knights::CItem> CMap::getItemAt( Vec2i from ) {
return mItems[ from.y ][ from.x ];
}
void CMap::putItemAt(std::shared_ptr<CItem> aItem, Vec2i aDestination) {
if ( mItems[ aDestination.y ][ aDestination.x ] == nullptr ) {
mItems[ aDestination.y ][ aDestination.x ] = aItem;
}
}
void CMap::addActorAt(std::shared_ptr<CActor> actor, const Vec2i &position) {
mElement[ position.y ][ position.x ] = '.';
actors.push_back(actor);
mActors[ position.y][ position.x] = actor;
actor->setPosition( position );
}
int CMap::getLastestId() {
return ++mCurrentId;
}
}
<|endoftext|> |
<commit_before>/**
* This contains all the "unit"-tests for making sure that everything works.
*/
#define FPL_IMPLEMENTATION
#define FPL_NO_WINDOW
#define FPL_NO_VIDEO
#define FPL_NO_AUDIO
#define FPL_AUTO_NAMESPACE
// @NOTE(final): Any assert should fire immediatly, regardless of the configuration
#define FPL_FORCE_ASSERTIONS
#include "final_platform_layer.hpp"
// @NOTE(final): C++ Standard Library (We dont want to use fpl here, because we want to test it from independent systems)
#include <iostream> // cout
#include <string> // string
#include <stdarg.h> // va_list, va_start, va_end
#include <typeinfo> // typeid
#define ASSERTION_CRASH() {*(int *)0 = 0xBAD;}
#if defined(FPL_COMPILER_GCC)
# define __FUNCTION__ ""
#endif
struct TestLineAssertionInfo {
char *filename;
char *functionName;
int line;
};
template <typename T>
static void TestAssert(const T &expected, const T &actual, const TestLineAssertionInfo &lineInfo, const std::string &message = "") {
bool success = (expected == actual);
if (!success) {
std::cerr << "Failed assertion in file '" << lineInfo.filename << "', function '" << lineInfo.functionName << "', line " << lineInfo.line;
if (message.size() > 0) {
std::cerr << " -> " << message;
}
std::cerr << std::endl;
std::cerr << "Expected type '" << typeid(T).name() << "' of '" << expected << "' but got '" << actual << "'!" << std::endl;
ASSERTION_CRASH();
}
}
template <typename T>
static void TestNotAssert(const T ¬Expected, const T &actual, const TestLineAssertionInfo &lineInfo, const std::string &message = "") {
bool success = (notExpected != actual);
if (!success) {
std::cerr << "Failed assertion in file '" << lineInfo.filename << "', function '" << lineInfo.functionName << "', line " << lineInfo.line;
if (message.size() > 0) {
std::cerr << " -> " << message;
}
std::cerr << std::endl;
std::cerr << "Expected type '" << typeid(T).name() << "' of not '" << notExpected << "' but got '" << actual << "'!" << std::endl;
ASSERTION_CRASH();
}
}
static void TestLog(const char *section, const char *format, ...) {
char buffer[2048];
va_list argList;
va_start(argList, format);
#if defined(__STDC_WANT_SECURE_LIB__) && __STDC_WANT_SECURE_LIB__
vsprintf_s(buffer, FPL_ARRAYCOUNT(buffer), format, argList);
#else
vsprintf(buffer, format, argList);
#endif
va_end(argList);
std::cout << "[" << section << "] " << buffer << std::endl;
}
#define LAI {__FILE__, __FUNCTION__, __LINE__}
#define FN __FUNCTION__
static void MemoryTests() {
TestLog(FN, "Test size macros");
{
TestAssert<size_t>(0ull, FPL_KILOBYTES(0), LAI, "0 KB");
TestAssert<size_t>(0ull, FPL_MEGABYTES(0), LAI, "0 MB");
TestAssert<size_t>(0ull, FPL_GIGABYTES(0), LAI, "0 GB");
TestAssert<size_t>(0ull, FPL_TERABYTES(0), LAI, "0 TB");
TestAssert<size_t>(13ull * 1024ull, FPL_KILOBYTES(13), LAI, "13 KB");
TestAssert<size_t>(137ull * 1024ull * 1024ull, FPL_MEGABYTES(137), LAI, "137 MB");
TestAssert<size_t>(3ull * 1024ull * 1024ull * 1024ull, FPL_GIGABYTES(3), LAI, "3 GB");
#if defined(FPL_ARCH_X64)
TestAssert<size_t>(813ull * 1024ull * 1024ull * 1024ull, FPL_GIGABYTES(813), LAI, "813 GB");
TestAssert<size_t>(2ull * 1024ull * 1024ull * 1024ull * 1024ull, FPL_TERABYTES(2), LAI, "2 TB");
#endif
}
TestLog(FN, "Test normal allocation and deallocation");
{
size_t memSize = FPL_KILOBYTES(42);
uint8_t *mem = (uint8_t *)MemoryAllocate(memSize);
for (size_t i = 0; i < memSize; ++i) {
uint8_t value = *mem++;
TestAssert<uint8_t>(0, value, LAI, "42 KB must be zero");
}
MemoryFree(mem);
}
{
size_t memSize = FPL_MEGABYTES(512);
void *mem = MemoryAllocate(memSize);
TestNotAssert<void *>(mem, nullptr, LAI, "512 MB of memory must be allocatd");
MemoryFree(mem);
}
TestLog(FN, "Test aligned allocation and deallocation");
{
size_t memSize = FPL_KILOBYTES(42);
uint8_t *mem = (uint8_t *)MemoryAlignedAllocate(memSize, 16);
for (size_t i = 0; i < memSize; ++i) {
uint8_t value = *(mem + i);
TestAssert<uint8_t>(0, value, LAI, "42 KB must be zero");
}
MemoryAlignedFree(mem);
}
{
size_t memSize = FPL_MEGABYTES(512);
void *mem = MemoryAlignedAllocate(memSize, 16);
TestNotAssert<void *>(mem, nullptr, LAI, "512 MB of memory must be allocatd");
MemoryAlignedFree(mem);
}
}
static void PathTests() {
char homePathBuffer[1024] = {};
GetHomePath(homePathBuffer, FPL_ARRAYCOUNT(homePathBuffer));
ConsoleFormatOut("Home Path:\n%s\n", homePathBuffer);
char exeFilePathBuffer[1024] = {};
GetExecutableFilePath(exeFilePathBuffer, FPL_ARRAYCOUNT(exeFilePathBuffer));
ConsoleFormatOut("Executable file Path:\n%s\n", exeFilePathBuffer);
char extractedPathBuffer[1024] = {};
ExtractFilePath(exeFilePathBuffer, extractedPathBuffer, FPL_ARRAYCOUNT(extractedPathBuffer));
ConsoleFormatOut("Extracted path:\n%s\n", extractedPathBuffer);
char *exeFileName = ExtractFileName(exeFilePathBuffer);
ConsoleFormatOut("Extracted filename:\n%s\n", exeFileName);
char *exeFileExt = ExtractFileExtension(exeFilePathBuffer);
ConsoleFormatOut("Extracted extension:\n%s\n", exeFileExt);
char combinedPathBuffer[1024 * 10] = {};
CombinePath(combinedPathBuffer, FPL_ARRAYCOUNT(combinedPathBuffer), 4, "Hallo", "Welt", "der", "Programmierer");
ConsoleFormatOut("Combined path:\n%s\n", combinedPathBuffer);
char changedFileExtBuffer[1024] = {};
ChangeFileExtension(exeFilePathBuffer, ".obj", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 1:\n%s\n", changedFileExtBuffer);
ChangeFileExtension(exeFileName, ".obj", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 2:\n%s\n", changedFileExtBuffer);
ChangeFileExtension(".dll", ".obj", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 3:\n%s\n", changedFileExtBuffer);
ChangeFileExtension("", ".obj", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 4:\n%s\n", changedFileExtBuffer);
ChangeFileExtension(".dll", "", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 5:\n%s\n", changedFileExtBuffer);
ChangeFileExtension("", "", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 5:\n%s\n", changedFileExtBuffer);
}
static void HardwareTest() {
char cpuNameBuffer[1024] = {};
GetProcessorName(cpuNameBuffer, FPL_ARRAYCOUNT(cpuNameBuffer));
ConsoleFormatOut("Processor name:\n%s\n", cpuNameBuffer);
uint32_t coreCount = GetProcessorCoreCount();
ConsoleFormatOut("Processor cores:%d\n", coreCount);
}
static void FilesTest() {
bool nonExisting = FileExists("C:\\Windows\\i_am_not_existing.lib");
FPL_ASSERT(!nonExisting);
bool notepadExists = FileExists("C:\\Windows\\notepad.exe");
FPL_ASSERT(notepadExists);
uint32_t emptySize = GetFileSize32("C:\\Windows\\i_am_not_existing.lib");
FPL_ASSERT(emptySize == 0);
uint32_t notepadSize = GetFileSize32("C:\\Windows\\notepad.exe");
FPL_ASSERT(notepadSize > 0);
FileEntry fileEntry;
if (ListFilesBegin("C:\\*", &fileEntry)) {
ConsoleFormatOut("%s\n", fileEntry.path);
while (ListFilesNext(&fileEntry)) {
ConsoleFormatOut("%s\n", fileEntry.path);
}
ListFilesEnd(&fileEntry);
}
}
static void TestThreadProc(const ThreadContext &context, void *data) {
uint32_t ms = (uint32_t)(intptr_t)(data) * 1000;
ConsoleFormatOut("Thread '%llu' started\n", context.id);
ThreadSleep(ms);
ConsoleFormatOut("Thread '%llu' finished\n", context.id);
}
static void ThreadingTest() {
ThreadContext *threads[3];
threads[0] = ThreadCreate(TestThreadProc, (void *)1);
threads[1] = ThreadCreate(TestThreadProc, (void *)2);
threads[2] = ThreadCreate(TestThreadProc, (void *)3);
ThreadWaitForAll(threads, FPL_ARRAYCOUNT(threads));
}
int main(int argc, char **args) {
InitPlatform(InitFlags::None);
MemoryTests();
ThreadingTest();
HardwareTest();
PathTests();
FilesTest();
ReleasePlatform();
}
<commit_msg>Missing console demo due to some small api changes<commit_after>/**
* This contains all the "unit"-tests for making sure that everything works.
*/
#define FPL_IMPLEMENTATION
#define FPL_NO_WINDOW
#define FPL_NO_VIDEO
#define FPL_NO_AUDIO
#define FPL_AUTO_NAMESPACE
// @NOTE(final): Any assert should fire immediatly, regardless of the configuration
#define FPL_FORCE_ASSERTIONS
#include "final_platform_layer.hpp"
// @NOTE(final): C++ Standard Library (We dont want to use fpl here, because we want to test it from independent systems)
#include <iostream> // cout
#include <string> // string
#include <stdarg.h> // va_list, va_start, va_end
#include <typeinfo> // typeid
#define ASSERTION_CRASH() {*(int *)0 = 0xBAD;}
#if defined(FPL_COMPILER_GCC)
# define __FUNCTION__ ""
#endif
struct TestLineAssertionInfo {
char *filename;
char *functionName;
int line;
};
template <typename T>
static void TestAssert(const T &expected, const T &actual, const TestLineAssertionInfo &lineInfo, const std::string &message = "") {
bool success = (expected == actual);
if (!success) {
std::cerr << "Failed assertion in file '" << lineInfo.filename << "', function '" << lineInfo.functionName << "', line " << lineInfo.line;
if (message.size() > 0) {
std::cerr << " -> " << message;
}
std::cerr << std::endl;
std::cerr << "Expected type '" << typeid(T).name() << "' of '" << expected << "' but got '" << actual << "'!" << std::endl;
ASSERTION_CRASH();
}
}
template <typename T>
static void TestNotAssert(const T ¬Expected, const T &actual, const TestLineAssertionInfo &lineInfo, const std::string &message = "") {
bool success = (notExpected != actual);
if (!success) {
std::cerr << "Failed assertion in file '" << lineInfo.filename << "', function '" << lineInfo.functionName << "', line " << lineInfo.line;
if (message.size() > 0) {
std::cerr << " -> " << message;
}
std::cerr << std::endl;
std::cerr << "Expected type '" << typeid(T).name() << "' of not '" << notExpected << "' but got '" << actual << "'!" << std::endl;
ASSERTION_CRASH();
}
}
static void TestLog(const char *section, const char *format, ...) {
char buffer[2048];
va_list argList;
va_start(argList, format);
#if defined(__STDC_WANT_SECURE_LIB__) && __STDC_WANT_SECURE_LIB__
vsprintf_s(buffer, FPL_ARRAYCOUNT(buffer), format, argList);
#else
vsprintf(buffer, format, argList);
#endif
va_end(argList);
std::cout << "[" << section << "] " << buffer << std::endl;
}
#define LAI {__FILE__, __FUNCTION__, __LINE__}
#define FN __FUNCTION__
static void MemoryTests() {
TestLog(FN, "Test size macros");
{
TestAssert<size_t>(0ull, FPL_KILOBYTES(0), LAI, "0 KB");
TestAssert<size_t>(0ull, FPL_MEGABYTES(0), LAI, "0 MB");
TestAssert<size_t>(0ull, FPL_GIGABYTES(0), LAI, "0 GB");
TestAssert<size_t>(0ull, FPL_TERABYTES(0), LAI, "0 TB");
TestAssert<size_t>(13ull * 1024ull, FPL_KILOBYTES(13), LAI, "13 KB");
TestAssert<size_t>(137ull * 1024ull * 1024ull, FPL_MEGABYTES(137), LAI, "137 MB");
TestAssert<size_t>(3ull * 1024ull * 1024ull * 1024ull, FPL_GIGABYTES(3), LAI, "3 GB");
#if defined(FPL_ARCH_X64)
TestAssert<size_t>(813ull * 1024ull * 1024ull * 1024ull, FPL_GIGABYTES(813), LAI, "813 GB");
TestAssert<size_t>(2ull * 1024ull * 1024ull * 1024ull * 1024ull, FPL_TERABYTES(2), LAI, "2 TB");
#endif
}
TestLog(FN, "Test normal allocation and deallocation");
{
size_t memSize = FPL_KILOBYTES(42);
uint8_t *mem = (uint8_t *)MemoryAllocate(memSize);
for (size_t i = 0; i < memSize; ++i) {
uint8_t value = *mem++;
TestAssert<uint8_t>(0, value, LAI, "42 KB must be zero");
}
MemoryFree(mem);
}
{
size_t memSize = FPL_MEGABYTES(512);
void *mem = MemoryAllocate(memSize);
TestNotAssert<void *>(mem, nullptr, LAI, "512 MB of memory must be allocatd");
MemoryFree(mem);
}
TestLog(FN, "Test aligned allocation and deallocation");
{
size_t memSize = FPL_KILOBYTES(42);
uint8_t *mem = (uint8_t *)MemoryAlignedAllocate(memSize, 16);
for (size_t i = 0; i < memSize; ++i) {
uint8_t value = *(mem + i);
TestAssert<uint8_t>(0, value, LAI, "42 KB must be zero");
}
MemoryAlignedFree(mem);
}
{
size_t memSize = FPL_MEGABYTES(512);
void *mem = MemoryAlignedAllocate(memSize, 16);
TestNotAssert<void *>(mem, nullptr, LAI, "512 MB of memory must be allocatd");
MemoryAlignedFree(mem);
}
}
static void PathTests() {
char homePathBuffer[1024] = {};
GetHomePath(homePathBuffer, FPL_ARRAYCOUNT(homePathBuffer));
ConsoleFormatOut("Home Path:\n%s\n", homePathBuffer);
char exeFilePathBuffer[1024] = {};
GetExecutableFilePath(exeFilePathBuffer, FPL_ARRAYCOUNT(exeFilePathBuffer));
ConsoleFormatOut("Executable file Path:\n%s\n", exeFilePathBuffer);
char extractedPathBuffer[1024] = {};
ExtractFilePath(exeFilePathBuffer, extractedPathBuffer, FPL_ARRAYCOUNT(extractedPathBuffer));
ConsoleFormatOut("Extracted path:\n%s\n", extractedPathBuffer);
char *exeFileName = ExtractFileName(exeFilePathBuffer);
ConsoleFormatOut("Extracted filename:\n%s\n", exeFileName);
char *exeFileExt = ExtractFileExtension(exeFilePathBuffer);
ConsoleFormatOut("Extracted extension:\n%s\n", exeFileExt);
char combinedPathBuffer[1024 * 10] = {};
CombinePath(combinedPathBuffer, FPL_ARRAYCOUNT(combinedPathBuffer), 4, "Hallo", "Welt", "der", "Programmierer");
ConsoleFormatOut("Combined path:\n%s\n", combinedPathBuffer);
char changedFileExtBuffer[1024] = {};
ChangeFileExtension(exeFilePathBuffer, ".obj", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 1:\n%s\n", changedFileExtBuffer);
ChangeFileExtension(exeFileName, ".obj", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 2:\n%s\n", changedFileExtBuffer);
ChangeFileExtension(".dll", ".obj", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 3:\n%s\n", changedFileExtBuffer);
ChangeFileExtension("", ".obj", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 4:\n%s\n", changedFileExtBuffer);
ChangeFileExtension(".dll", "", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 5:\n%s\n", changedFileExtBuffer);
ChangeFileExtension("", "", changedFileExtBuffer, FPL_ARRAYCOUNT(changedFileExtBuffer));
ConsoleFormatOut("Changed file ext 5:\n%s\n", changedFileExtBuffer);
}
static void HardwareTest() {
char cpuNameBuffer[1024] = {};
GetProcessorName(cpuNameBuffer, FPL_ARRAYCOUNT(cpuNameBuffer));
ConsoleFormatOut("Processor name:\n%s\n", cpuNameBuffer);
uint32_t coreCount = GetProcessorCoreCount();
ConsoleFormatOut("Processor cores:%d\n", coreCount);
MemoryInfos memInfos = GetSystemMemoryInfos();
ConsoleFormatOut("Physical total memory (bytes):%zu\n", memInfos.totalPhysicalSize);
ConsoleFormatOut("Physical available memory (bytes):%zu\n", memInfos.availablePhysicalSize);
ConsoleFormatOut("Physical used memory (bytes):%zu\n", memInfos.usedPhysicalSize);
ConsoleFormatOut("Virtual total memory (bytes):%zu\n", memInfos.totalVirtualSize);
ConsoleFormatOut("Virtual used memory (bytes):%zu\n", memInfos.usedVirtualSize);
ConsoleFormatOut("Page total memory (bytes):%zu\n", memInfos.totalPageSize);
ConsoleFormatOut("Page used memory (bytes):%zu\n", memInfos.usedPageSize);
}
static void FilesTest() {
bool nonExisting = FileExists("C:\\Windows\\i_am_not_existing.lib");
FPL_ASSERT(!nonExisting);
bool notepadExists = FileExists("C:\\Windows\\notepad.exe");
FPL_ASSERT(notepadExists);
uint32_t emptySize = GetFileSize32("C:\\Windows\\i_am_not_existing.lib");
FPL_ASSERT(emptySize == 0);
uint32_t notepadSize = GetFileSize32("C:\\Windows\\notepad.exe");
FPL_ASSERT(notepadSize > 0);
FileEntry fileEntry;
if (ListFilesBegin("C:\\*", fileEntry)) {
ConsoleFormatOut("%s\n", fileEntry.path);
while (ListFilesNext(fileEntry)) {
ConsoleFormatOut("%s\n", fileEntry.path);
}
ListFilesEnd(fileEntry);
}
}
static void TestThreadProc(const ThreadContext &context, void *data) {
uint32_t ms = (uint32_t)(intptr_t)(data) * 1000;
ConsoleFormatOut("Thread '%llu' started\n", context.id);
ThreadSleep(ms);
ConsoleFormatOut("Thread '%llu' finished\n", context.id);
}
static void ThreadingTest() {
ThreadContext *threads[3];
threads[0] = ThreadCreate(TestThreadProc, (void *)1);
threads[1] = ThreadCreate(TestThreadProc, (void *)2);
threads[2] = ThreadCreate(TestThreadProc, (void *)3);
ThreadWaitForAll(threads, FPL_ARRAYCOUNT(threads));
}
int main(int argc, char **args) {
volatile int64_t rindex_rindexShown = 0;
int64_t r = AtomicLoadS64(&rindex_rindexShown);
int32_t rindex = (int32_t)(r & 0xFFFFFFFF00000000);
int32_t rindexShown = (r >> 32) & 0xFFFFFFFF00000000;
rindex_rindexShown = (int64_t)42 | ((int64_t)612 << 32);
r = AtomicLoadS64(&rindex_rindexShown);
rindex = (int32_t)r;
rindexShown = (r & 0xFFFFFFFF00000000) >> 32;
AtomicAddS64(&rindex_rindexShown, 1);
r = AtomicLoadS64(&rindex_rindexShown);
rindex = (int32_t)r;
rindexShown = (r & 0xFFFFFFFF00000000) >> 32;
InitPlatform(InitFlags::None);
MemoryTests();
ThreadingTest();
HardwareTest();
PathTests();
FilesTest();
ReleasePlatform();
}
<|endoftext|> |
<commit_before>/*
* Author: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* 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 <iostream>
#include <unistd.h>
#include "math.h"
#include "itg3200.h"
#define READ_BUFFER_LENGTH 8
//address and id
#define ITG3200_I2C_ADDR 0x68
#define ITG3200_ID 0x00
//configuration registers
#define ITG3200_SMPLRT_DIV 0x15
#define ITG3200_DLPF_FS 0x16
//interrupt registers
#define ITG3200_INT_CFG 0x17
#define ITG3200_INT_STATUS 0x1A
//data registers (read only)
#define ITG3200_TEMP_H 0x1B
#define ITG3200_TEMP_L 0x1C
#define ITG3200_XOUT_H 0x1D
#define ITG3200_XOUT_L 0x1E
#define ITG3200_YOUT_H 0x1F
#define ITG3200_YOUT_L 0x20
#define ITG3200_ZOUT_H 0x21
#define ITG3200_ZOUT_L 0x22
#define DATA_REG_SIZE 8
//power management
#define ITG3200_PWR_MGM 0x3E
//useful values
#define ITG3200_RESET 0x80
#define ITG3200_SLEEP 0x40
#define ITG3200_WAKEUP 0x00
using namespace upm;
Itg3200::Itg3200(int bus) : m_i2c(bus)
{
//reset chip
m_i2c.address(ITG3200_I2C_ADDR);
m_buffer[0] = ITG3200_PWR_MGM;
m_buffer[1] = ITG3200_RESET;
m_i2c.write(m_buffer, 2);
Itg3200::calibrate();
Itg3200::update();
}
void
Itg3200::calibrate(void)
{
int reads = 600;
int delay = 4000; // 4 milliseconds
int skip = 5; // initial samples to skip
int temp[3] = {0};
for(int i = 0; i < reads; i++){
Itg3200::update();
if (i > skip){
for (int j = 0; j < 3; j++){
temp[j] += m_rotation[j];
}
}
usleep(delay);
}
for(int i = 0; i < 3; i++){
m_offsets[i] = (-1) * temp[i] / (reads - skip);
}
}
float
Itg3200::getTemperature()
{
return 35.0 + (m_temperature + 13200.0) / 280.0;
}
float*
Itg3200::getRotation()
{
for(int i = 0; i < 3; i++){
m_angle[i] = m_rotation[i]/14.375;
}
return &m_angle[0];
}
int16_t*
Itg3200::getRawValues()
{
return &m_rotation[0];
}
int16_t
Itg3200::getRawTemp()
{
return m_temperature;
}
mraa::Result
Itg3200::update(void)
{
m_i2c.address(ITG3200_I2C_ADDR);
m_i2c.writeByte(ITG3200_TEMP_H);
m_i2c.address(ITG3200_I2C_ADDR);
m_i2c.read(m_buffer, DATA_REG_SIZE);
//temp
//
m_temperature = (m_buffer[0] << 8 ) | m_buffer[1];
// x
m_rotation[0] = ((m_buffer[2] << 8 ) | m_buffer[3]) + m_offsets[0];
// y
m_rotation[1] = ((m_buffer[4] << 8 ) | m_buffer[5]) + m_offsets[1];
// z
m_rotation[2] = ((m_buffer[6] << 8 ) | m_buffer[7]) + m_offsets[2];
return mraa::SUCCESS;
}
<commit_msg>itg3200: throw exception(s) on fatal errors<commit_after>/*
* Author: Mihai Tudor Panu <mihai.tudor.panu@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* 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 <iostream>
#include <string>
#include <stdexcept>
#include <unistd.h>
#include "math.h"
#include "itg3200.h"
#define READ_BUFFER_LENGTH 8
//address and id
#define ITG3200_I2C_ADDR 0x68
#define ITG3200_ID 0x00
//configuration registers
#define ITG3200_SMPLRT_DIV 0x15
#define ITG3200_DLPF_FS 0x16
//interrupt registers
#define ITG3200_INT_CFG 0x17
#define ITG3200_INT_STATUS 0x1A
//data registers (read only)
#define ITG3200_TEMP_H 0x1B
#define ITG3200_TEMP_L 0x1C
#define ITG3200_XOUT_H 0x1D
#define ITG3200_XOUT_L 0x1E
#define ITG3200_YOUT_H 0x1F
#define ITG3200_YOUT_L 0x20
#define ITG3200_ZOUT_H 0x21
#define ITG3200_ZOUT_L 0x22
#define DATA_REG_SIZE 8
//power management
#define ITG3200_PWR_MGM 0x3E
//useful values
#define ITG3200_RESET 0x80
#define ITG3200_SLEEP 0x40
#define ITG3200_WAKEUP 0x00
using namespace upm;
Itg3200::Itg3200(int bus) : m_i2c(bus)
{
//init bus and reset chip
if ( !(m_i2c = mraa_i2c_init(bus)) )
{
throw std::invalid_argument(std::string(__FUNCTION__) +
": mraa_i2c_init() failed");
return;
}
m_i2c.address(ITG3200_I2C_ADDR);
m_buffer[0] = ITG3200_PWR_MGM;
m_buffer[1] = ITG3200_RESET;
m_i2c.write(m_buffer, 2);
Itg3200::calibrate();
Itg3200::update();
}
void
Itg3200::calibrate(void)
{
int reads = 600;
int delay = 4000; // 4 milliseconds
int skip = 5; // initial samples to skip
int temp[3] = {0};
for(int i = 0; i < reads; i++){
Itg3200::update();
if (i > skip){
for (int j = 0; j < 3; j++){
temp[j] += m_rotation[j];
}
}
usleep(delay);
}
for(int i = 0; i < 3; i++){
m_offsets[i] = (-1) * temp[i] / (reads - skip);
}
}
float
Itg3200::getTemperature()
{
return 35.0 + (m_temperature + 13200.0) / 280.0;
}
float*
Itg3200::getRotation()
{
for(int i = 0; i < 3; i++){
m_angle[i] = m_rotation[i]/14.375;
}
return &m_angle[0];
}
int16_t*
Itg3200::getRawValues()
{
return &m_rotation[0];
}
int16_t
Itg3200::getRawTemp()
{
return m_temperature;
}
mraa::Result
Itg3200::update(void)
{
m_i2c.address(ITG3200_I2C_ADDR);
m_i2c.writeByte(ITG3200_TEMP_H);
m_i2c.address(ITG3200_I2C_ADDR);
m_i2c.read(m_buffer, DATA_REG_SIZE);
//temp
//
m_temperature = (m_buffer[0] << 8 ) | m_buffer[1];
// x
m_rotation[0] = ((m_buffer[2] << 8 ) | m_buffer[3]) + m_offsets[0];
// y
m_rotation[1] = ((m_buffer[4] << 8 ) | m_buffer[5]) + m_offsets[1];
// z
m_rotation[2] = ((m_buffer[6] << 8 ) | m_buffer[7]) + m_offsets[2];
return mraa::SUCCESS;
}
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Base class for a Pitman Arm steering subsystem.
// Derived from ChSteering, but still an abstract base class.
//
// =============================================================================
#include <vector>
#include "assets/ChCylinderShape.h"
#include "assets/ChColorAsset.h"
#include "subsys/steering/ChPitmanArm.h"
namespace chrono {
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
ChPitmanArm::ChPitmanArm(const std::string& name)
: ChSteering(name)
{
// Create the steering link body
m_link = ChSharedBodyPtr(new ChBody);
m_link->SetNameString(name + "_link");
// Create the Pitman arm body
m_arm = ChSharedBodyPtr(new ChBody);
m_arm->SetNameString(name + "_arm");
// Revolute joint between Pitman arm and chassis
m_revolute = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute);
m_revolute->SetNameString(name + "_revolute");
// Universal joint between Pitman arm and steering link
m_universal = ChSharedPtr<ChLinkLockUniversal>(new ChLinkLockUniversal);
m_universal->SetNameString(name + "_universal");
// Revolute-spherical joint to model the idler arm
m_revsph = ChSharedPtr<ChLinkRevoluteSpherical>(new ChLinkRevoluteSpherical);
m_revsph->SetNameString(name + "_revsph");
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChPitmanArm::Initialize(ChSharedPtr<ChBody> chassis,
const ChCoordsys<>& position)
{
// Transform all points and directions to absolute frame.
std::vector<ChVector<> > points(NUM_POINTS);
std::vector<ChVector<> > dirs(NUM_DIRS);
ChCoordsys<> to_global = chassis->GetCoord().TransformLocalToParent(position);
for (int i = 0; i < NUM_POINTS; i++) {
ChVector<> rel_pos = getLocation(static_cast<PointId>(i));
points[i] = to_global.TransformPointLocalToParent(rel_pos);
}
for (int i = 0; i < NUM_DIRS; i++) {
ChVector<> rel_dir = getDirection(static_cast<DirectionId>(i));
dirs[i] = to_global.TransformDirectionLocalToParent(rel_dir);
}
// Unit vectors for orientation matrices.
ChVector<> u;
ChVector<> v;
ChVector<> w;
ChMatrix33<> rot;
// Initialize the steering link body
m_link->SetPos(points[STEERINGLINK]);
m_link->SetRot(to_global.rot);
m_link->SetMass(getSteeringLinkMass());
m_link->SetInertiaXX(getSteeringLinkInertia());
AddVisualizationSteeringLink(m_link, points[UNIV], points[REVSPH_S], points[TIEROD_PA], points[TIEROD_IA], getSteeringLinkRadius());
chassis->GetSystem()->AddBody(m_link);
// Initialize the Pitman arm body
m_arm->SetPos(points[PITMANARM]);
m_arm->SetRot(to_global.rot);
m_arm->SetMass(getPitmanArmMass());
m_arm->SetInertiaXX(getPitmanArmInertia());
AddVisualizationPitmanArm(m_arm, points[REV], points[UNIV], getPitmanArmRadius());
chassis->GetSystem()->AddBody(m_arm);
// Initialize the revolute joint between chassis and Pitman arm.
// The z direction of the joint orientation matrix is dirs[REV_AXIS], assumed
// to be a unit vector.
u = points[PITMANARM] - points[REV];
v = Vcross(dirs[REV_AXIS], u);
v.Normalize();
u = Vcross(v, dirs[REV_AXIS]);
rot.Set_A_axis(u, v, dirs[REV_AXIS]);
m_revolute->Initialize(chassis, m_arm, ChCoordsys<>(points[REV], rot.Get_A_quaternion()));
chassis->GetSystem()->AddLink(m_revolute);
// Initialize the universal joint between the Pitman arm and steering link.
// The x and y directions of the joint orientation matrix are given by
// dirs[UNIV_AXIS_ARM] and dirs[UNIV_AXIS_LINK], assumed to be unit vectors
// and orthogonal.
w = Vcross(dirs[UNIV_AXIS_ARM], dirs[UNIV_AXIS_LINK]);
rot.Set_A_axis(dirs[UNIV_AXIS_ARM], dirs[UNIV_AXIS_LINK], w);
m_universal->Initialize(m_arm, m_link, ChCoordsys<>(points[UNIV], rot.Get_A_quaternion()));
chassis->GetSystem()->AddLink(m_universal);
// Initialize the revolute-spherical joint (massless idler arm).
// The length of the idler arm is the distance between the two hardpoints.
// The z direction of the revolute joint orientation matrix is
// dirs[REVSPH_AXIS], assumed to be a unit vector.
double distance = (points[REVSPH_S] - points[REVSPH_R]).Length();
u = points[REVSPH_S] - points[REVSPH_R];
v = Vcross(dirs[REVSPH_AXIS], u);
v.Normalize();
u = Vcross(v, dirs[REVSPH_AXIS]);
rot.Set_A_axis(u, v, dirs[REVSPH_AXIS]);
m_revsph->Initialize(m_arm, m_link, ChCoordsys<>(points[UNIV], rot.Get_A_quaternion()), distance);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChPitmanArm::AddVisualizationPitmanArm(ChSharedPtr<ChBody> arm,
const ChVector<>& pt_C,
const ChVector<>& pt_L,
double radius)
{
// Express hardpoint locations in body frame.
ChVector<> p_C = arm->TransformPointParentToLocal(pt_C);
ChVector<> p_L = arm->TransformPointParentToLocal(pt_L);
ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape);
cyl->GetCylinderGeometry().p1 = p_C;
cyl->GetCylinderGeometry().p2 = p_L;
cyl->GetCylinderGeometry().rad = radius;
arm->AddAsset(cyl);
ChSharedPtr<ChColorAsset> col(new ChColorAsset);
col->SetColor(ChColor(0.7f, 0.7f, 0.2f));
arm->AddAsset(col);
}
void ChPitmanArm::AddVisualizationSteeringLink(ChSharedPtr<ChBody> link,
const ChVector<>& pt_P,
const ChVector<>& pt_I,
const ChVector<>& pt_TP,
const ChVector<>& pt_TI,
double radius)
{
// Express hardpoint locations in body frame.
ChVector<> p_P = link->TransformPointParentToLocal(pt_P);
ChVector<> p_I = link->TransformPointParentToLocal(pt_I);
ChVector<> p_TP = link->TransformPointParentToLocal(pt_TP);
ChVector<> p_TI = link->TransformPointParentToLocal(pt_TI);
ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape);
cyl->GetCylinderGeometry().p1 = p_P;
cyl->GetCylinderGeometry().p2 = p_I;
cyl->GetCylinderGeometry().rad = radius;
link->AddAsset(cyl);
ChSharedPtr<ChCylinderShape> cyl_P(new ChCylinderShape);
cyl_P->GetCylinderGeometry().p1 = p_P;
cyl_P->GetCylinderGeometry().p2 = p_TP;
cyl_P->GetCylinderGeometry().rad = radius;
link->AddAsset(cyl_P);
ChSharedPtr<ChCylinderShape> cyl_I(new ChCylinderShape);
cyl_I->GetCylinderGeometry().p1 = p_I;
cyl_I->GetCylinderGeometry().p2 = p_TI;
cyl_I->GetCylinderGeometry().rad = radius;
link->AddAsset(cyl_I);
ChSharedPtr<ChColorAsset> col(new ChColorAsset);
col->SetColor(ChColor(0.2f, 0.7f, 0.7f));
link->AddAsset(col);
}
} // end namespace chrono
<commit_msg>Fix bug in the initialization of the rev-sph joint of a PitmanArm steering subsystem.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Base class for a Pitman Arm steering subsystem.
// Derived from ChSteering, but still an abstract base class.
//
// =============================================================================
#include <vector>
#include "assets/ChCylinderShape.h"
#include "assets/ChColorAsset.h"
#include "subsys/steering/ChPitmanArm.h"
namespace chrono {
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
ChPitmanArm::ChPitmanArm(const std::string& name)
: ChSteering(name)
{
// Create the steering link body
m_link = ChSharedBodyPtr(new ChBody);
m_link->SetNameString(name + "_link");
// Create the Pitman arm body
m_arm = ChSharedBodyPtr(new ChBody);
m_arm->SetNameString(name + "_arm");
// Revolute joint between Pitman arm and chassis
m_revolute = ChSharedPtr<ChLinkLockRevolute>(new ChLinkLockRevolute);
m_revolute->SetNameString(name + "_revolute");
// Universal joint between Pitman arm and steering link
m_universal = ChSharedPtr<ChLinkLockUniversal>(new ChLinkLockUniversal);
m_universal->SetNameString(name + "_universal");
// Revolute-spherical joint to model the idler arm
m_revsph = ChSharedPtr<ChLinkRevoluteSpherical>(new ChLinkRevoluteSpherical);
m_revsph->SetNameString(name + "_revsph");
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChPitmanArm::Initialize(ChSharedPtr<ChBody> chassis,
const ChCoordsys<>& position)
{
// Transform all points and directions to absolute frame.
std::vector<ChVector<> > points(NUM_POINTS);
std::vector<ChVector<> > dirs(NUM_DIRS);
ChCoordsys<> to_global = chassis->GetCoord().TransformLocalToParent(position);
for (int i = 0; i < NUM_POINTS; i++) {
ChVector<> rel_pos = getLocation(static_cast<PointId>(i));
points[i] = to_global.TransformPointLocalToParent(rel_pos);
}
for (int i = 0; i < NUM_DIRS; i++) {
ChVector<> rel_dir = getDirection(static_cast<DirectionId>(i));
dirs[i] = to_global.TransformDirectionLocalToParent(rel_dir);
}
// Unit vectors for orientation matrices.
ChVector<> u;
ChVector<> v;
ChVector<> w;
ChMatrix33<> rot;
// Initialize the steering link body
m_link->SetPos(points[STEERINGLINK]);
m_link->SetRot(to_global.rot);
m_link->SetMass(getSteeringLinkMass());
m_link->SetInertiaXX(getSteeringLinkInertia());
AddVisualizationSteeringLink(m_link, points[UNIV], points[REVSPH_S], points[TIEROD_PA], points[TIEROD_IA], getSteeringLinkRadius());
chassis->GetSystem()->AddBody(m_link);
// Initialize the Pitman arm body
m_arm->SetPos(points[PITMANARM]);
m_arm->SetRot(to_global.rot);
m_arm->SetMass(getPitmanArmMass());
m_arm->SetInertiaXX(getPitmanArmInertia());
AddVisualizationPitmanArm(m_arm, points[REV], points[UNIV], getPitmanArmRadius());
chassis->GetSystem()->AddBody(m_arm);
// Initialize the revolute joint between chassis and Pitman arm.
// The z direction of the joint orientation matrix is dirs[REV_AXIS], assumed
// to be a unit vector.
u = points[PITMANARM] - points[REV];
v = Vcross(dirs[REV_AXIS], u);
v.Normalize();
u = Vcross(v, dirs[REV_AXIS]);
rot.Set_A_axis(u, v, dirs[REV_AXIS]);
m_revolute->Initialize(chassis, m_arm, ChCoordsys<>(points[REV], rot.Get_A_quaternion()));
chassis->GetSystem()->AddLink(m_revolute);
// Initialize the universal joint between the Pitman arm and steering link.
// The x and y directions of the joint orientation matrix are given by
// dirs[UNIV_AXIS_ARM] and dirs[UNIV_AXIS_LINK], assumed to be unit vectors
// and orthogonal.
w = Vcross(dirs[UNIV_AXIS_ARM], dirs[UNIV_AXIS_LINK]);
rot.Set_A_axis(dirs[UNIV_AXIS_ARM], dirs[UNIV_AXIS_LINK], w);
m_universal->Initialize(m_arm, m_link, ChCoordsys<>(points[UNIV], rot.Get_A_quaternion()));
chassis->GetSystem()->AddLink(m_universal);
// Initialize the revolute-spherical joint (massless idler arm).
// The length of the idler arm is the distance between the two hardpoints.
// The z direction of the revolute joint orientation matrix is
// dirs[REVSPH_AXIS], assumed to be a unit vector.
double distance = (points[REVSPH_S] - points[REVSPH_R]).Length();
u = points[REVSPH_S] - points[REVSPH_R];
v = Vcross(dirs[REVSPH_AXIS], u);
v.Normalize();
u = Vcross(v, dirs[REVSPH_AXIS]);
rot.Set_A_axis(u, v, dirs[REVSPH_AXIS]);
m_revsph->Initialize(chassis, m_link, ChCoordsys<>(points[REVSPH_R], rot.Get_A_quaternion()), distance);
chassis->GetSystem()->AddLink(m_revsph);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChPitmanArm::AddVisualizationPitmanArm(ChSharedPtr<ChBody> arm,
const ChVector<>& pt_C,
const ChVector<>& pt_L,
double radius)
{
// Express hardpoint locations in body frame.
ChVector<> p_C = arm->TransformPointParentToLocal(pt_C);
ChVector<> p_L = arm->TransformPointParentToLocal(pt_L);
ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape);
cyl->GetCylinderGeometry().p1 = p_C;
cyl->GetCylinderGeometry().p2 = p_L;
cyl->GetCylinderGeometry().rad = radius;
arm->AddAsset(cyl);
ChSharedPtr<ChColorAsset> col(new ChColorAsset);
col->SetColor(ChColor(0.7f, 0.7f, 0.2f));
arm->AddAsset(col);
}
void ChPitmanArm::AddVisualizationSteeringLink(ChSharedPtr<ChBody> link,
const ChVector<>& pt_P,
const ChVector<>& pt_I,
const ChVector<>& pt_TP,
const ChVector<>& pt_TI,
double radius)
{
// Express hardpoint locations in body frame.
ChVector<> p_P = link->TransformPointParentToLocal(pt_P);
ChVector<> p_I = link->TransformPointParentToLocal(pt_I);
ChVector<> p_TP = link->TransformPointParentToLocal(pt_TP);
ChVector<> p_TI = link->TransformPointParentToLocal(pt_TI);
ChSharedPtr<ChCylinderShape> cyl(new ChCylinderShape);
cyl->GetCylinderGeometry().p1 = p_P;
cyl->GetCylinderGeometry().p2 = p_I;
cyl->GetCylinderGeometry().rad = radius;
link->AddAsset(cyl);
ChSharedPtr<ChCylinderShape> cyl_P(new ChCylinderShape);
cyl_P->GetCylinderGeometry().p1 = p_P;
cyl_P->GetCylinderGeometry().p2 = p_TP;
cyl_P->GetCylinderGeometry().rad = radius;
link->AddAsset(cyl_P);
ChSharedPtr<ChCylinderShape> cyl_I(new ChCylinderShape);
cyl_I->GetCylinderGeometry().p1 = p_I;
cyl_I->GetCylinderGeometry().p2 = p_TI;
cyl_I->GetCylinderGeometry().rad = radius;
link->AddAsset(cyl_I);
ChSharedPtr<ChColorAsset> col(new ChColorAsset);
col->SetColor(ChColor(0.2f, 0.7f, 0.7f));
link->AddAsset(col);
}
} // end namespace chrono
<|endoftext|> |
<commit_before>// $Id$
//
// Copyright (C) 2014 Novartis Institutes for BioMedical Research
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <boost/python.hpp>
#include <GraphMol/ROMol.h>
#include <RDBoost/Wrap.h>
#include <GraphMol/FMCS/FMCS.h>
namespace python = boost::python;
namespace RDKit {
MCSResult *FindMCSWrapper(python::object mols){
std::vector<ROMOL_SPTR> ms;
unsigned int nElems=python::extract<unsigned int>(mols.attr("__len__")());
ms.resize(nElems);
for(unsigned int i=0;i<nElems;++i){
ms[i] = python::extract<ROMOL_SPTR>(mols[i]);
}
MCSResult *res=new MCSResult(findMCS(ms));
return res;
}
}
namespace {
struct mcsresult_wrapper {
static void wrap(){
python::class_<RDKit::MCSResult>("MCSResult","stores MCS results",python::no_init)
.def_readonly("numAtoms",&RDKit::MCSResult::NumAtoms)
.def_readonly("numBonds",&RDKit::MCSResult::NumBonds)
.def_readonly("smartsString",&RDKit::MCSResult::SmartsString)
.def_readonly("canceled",&RDKit::MCSResult::Canceled)
;
}
};
}
BOOST_PYTHON_MODULE(rdFMCS) {
python::scope().attr("__doc__") =
"Module containing a C++ implementation of the FMCS algorithm";
mcsresult_wrapper::wrap();
std::string docString = "Find the MCS for a set of molecules";
python::def("FindMCS", RDKit::FindMCSWrapper,
(python::arg("mols")),// python::arg("ignoreHs")=true),
python::return_value_policy<python::manage_new_object>(),
docString.c_str());
}
<commit_msg>start supporting arguments to FindMCS<commit_after>// $Id$
//
// Copyright (C) 2014 Novartis Institutes for BioMedical Research
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <boost/python.hpp>
#include <GraphMol/ROMol.h>
#include <RDBoost/Wrap.h>
#include <GraphMol/FMCS/FMCS.h>
namespace python = boost::python;
namespace RDKit {
MCSResult *FindMCSWrapper(python::object mols,bool maximizeBonds,double threshold,
unsigned timeout,bool verbose){
std::vector<ROMOL_SPTR> ms;
unsigned int nElems=python::extract<unsigned int>(mols.attr("__len__")());
ms.resize(nElems);
for(unsigned int i=0;i<nElems;++i){
ms[i] = python::extract<ROMOL_SPTR>(mols[i]);
}
MCSParameters *ps=new MCSParameters();
ps->MaximizeBonds=maximizeBonds;
ps->Threshold=threshold;
ps->Timeout=timeout;
ps->Verbose=verbose;
MCSResult *res=new MCSResult(findMCS(ms,ps));
delete ps;
return res;
}
}
namespace {
struct mcsresult_wrapper {
static void wrap(){
python::class_<RDKit::MCSResult>("MCSResult","stores MCS results",python::no_init)
.def_readonly("numAtoms",&RDKit::MCSResult::NumAtoms)
.def_readonly("numBonds",&RDKit::MCSResult::NumBonds)
.def_readonly("smartsString",&RDKit::MCSResult::SmartsString)
.def_readonly("canceled",&RDKit::MCSResult::Canceled)
;
}
};
}
BOOST_PYTHON_MODULE(rdFMCS) {
python::scope().attr("__doc__") =
"Module containing a C++ implementation of the FMCS algorithm";
mcsresult_wrapper::wrap();
std::string docString = "Find the MCS for a set of molecules";
python::def("FindMCS", RDKit::FindMCSWrapper,
(python::arg("mols"),
python::arg("maximizeBonds")=true,
python::arg("threshold")=1.0,
python::arg("timeout")=3600,
python::arg("verbose")=false
),
python::return_value_policy<python::manage_new_object>(),
docString.c_str());
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015,2018 Immo Software
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "asr_envelope.h"
#include "arm_math.h"
using namespace slab;
//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------
ASREnvelope::ASREnvelope()
: AudioFilter(),
m_attack(),
m_release(),
m_peak(1.0f),
m_mode(kOneShotAR),
m_enableSustain(false),
m_releaseOffset(0),
m_elapsedSamples(0)
{
}
void ASREnvelope::set_sample_rate(float rate)
{
AudioFilter::set_sample_rate(rate);
m_attack.set_sample_rate(rate);
m_release.set_sample_rate(rate);
}
void ASREnvelope::set_mode(EnvelopeMode mode)
{
m_mode = mode;
m_enableSustain = (mode == kOneShotASR);
}
void ASREnvelope::set_peak(float peak)
{
m_peak = peak;
m_attack.set_begin_value(0.0f);
m_attack.set_end_value(peak);
m_release.set_begin_value(peak);
m_release.set_end_value(0.0f);
}
void ASREnvelope::set_length_in_seconds(EnvelopeStage stage, float seconds)
{
switch (stage)
{
case kAttack:
m_attack.set_length_in_seconds(seconds);
break;
case kRelease:
m_release.set_length_in_seconds(seconds);
break;
default:
break;
}
}
void ASREnvelope::set_length_in_samples(EnvelopeStage stage, uint32_t samples)
{
switch (stage)
{
case kAttack:
m_attack.set_length_in_samples(samples);
break;
case kRelease:
m_release.set_length_in_samples(samples);
break;
default:
break;
}
}
float ASREnvelope::get_length_in_seconds(EnvelopeStage stage)
{
switch (stage)
{
case kAttack:
return m_attack.get_length_in_seconds();
case kRelease:
return m_release.get_length_in_seconds();
default:
break;
}
return 0.0f;
}
uint32_t ASREnvelope::get_length_in_samples(EnvelopeStage stage)
{
switch (stage)
{
case kAttack:
return m_attack.get_length_in_samples();
case kRelease:
return m_release.get_length_in_samples();
default:
break;
}
return 0;
}
void ASREnvelope::set_curve_type(EnvelopeStage stage, AudioRamp::CurveType theType)
{
switch (stage)
{
case kAttack:
m_attack.set_curve_type(theType);
break;
case kRelease:
m_release.set_curve_type(theType);
break;
default:
break;
}
}
void ASREnvelope::recompute()
{
// Recompute the slope of both ramps.
m_attack.recompute();
m_release.recompute();
}
void ASREnvelope::set_release_offset(uint32_t offset)
{
m_releaseOffset = m_elapsedSamples + offset;
}
void ASREnvelope::reset()
{
m_attack.reset();
m_release.reset();
m_elapsedSamples = 0;
m_releaseOffset = 0;
}
float ASREnvelope::next()
{
float sample;
process(&sample, 1);
return sample;
}
bool ASREnvelope::is_finished()
{
return (m_mode != kLoopingAR) && (m_attack.is_finished()
&& (!m_enableSustain || (m_releaseOffset != 0 && m_elapsedSamples >= m_releaseOffset))
&& m_release.is_finished());
}
void ASREnvelope::process(float * samples, uint32_t count)
{
uint32_t totalRemaining = count;
while (totalRemaining)
{
// Special case to prevent infinite loop if the stages are both 0 length and
// we're in the looping envelope mode.
if (m_mode == kLoopingAR
&& m_attack.get_length_in_samples() == 0
&& m_release.get_length_in_samples() == 0)
{
arm_fill_f32(0.0f, samples, totalRemaining);
return;
}
// Attack.
uint32_t attackCount = m_attack.get_remaining_samples();
if (attackCount > count)
{
attackCount = count;
}
if (attackCount)
{
m_attack.process(samples, attackCount);
}
// Sustain.
if (attackCount < count)
{
int32_t sustainCount = 0;
if (m_enableSustain)
{
sustainCount = count - attackCount;
if (m_releaseOffset > 0)
{
if (attackCount + sustainCount + m_elapsedSamples > m_releaseOffset)
{
sustainCount = m_releaseOffset - m_elapsedSamples - attackCount;
if (sustainCount < 0)
{
sustainCount = 0;
}
}
}
if (sustainCount > 0)
{
arm_fill_f32(m_peak, samples + attackCount, sustainCount);
}
}
// Release.
uint32_t attackSustainCount = attackCount + sustainCount;
if (attackSustainCount < count)
{
uint32_t releaseCount = count - attackSustainCount;
if (m_mode == kLoopingAR)
{
uint32_t releaseRemaining = m_release.get_remaining_samples();
if (releaseRemaining > releaseCount)
{
m_release.process(samples + attackSustainCount, releaseCount);
}
else
{
// Fill last part of release stage, then retrigger and loop.
m_release.process(samples + attackSustainCount, releaseRemaining);
reset();
uint32_t thisLoopCount = attackSustainCount + releaseRemaining;
totalRemaining -= thisLoopCount;
samples += thisLoopCount;
m_elapsedSamples += thisLoopCount;
count = releaseCount - releaseRemaining;
continue;
}
}
else
{
// For non-looping modes, we can just let the release stage fill to the end.
if (releaseCount)
{
m_release.process(samples + attackSustainCount, releaseCount);
}
}
}
}
totalRemaining -= count;
m_elapsedSamples += count;
}
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<commit_msg>Fixed ASREnvelope to fill peak value if attack and release are both 0 in looping mode.<commit_after>/*
* Copyright (c) 2015,2018 Immo Software
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "asr_envelope.h"
#include "arm_math.h"
using namespace slab;
//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------
ASREnvelope::ASREnvelope()
: AudioFilter(),
m_attack(),
m_release(),
m_peak(1.0f),
m_mode(kOneShotAR),
m_enableSustain(false),
m_releaseOffset(0),
m_elapsedSamples(0)
{
}
void ASREnvelope::set_sample_rate(float rate)
{
AudioFilter::set_sample_rate(rate);
m_attack.set_sample_rate(rate);
m_release.set_sample_rate(rate);
}
void ASREnvelope::set_mode(EnvelopeMode mode)
{
m_mode = mode;
m_enableSustain = (mode == kOneShotASR);
}
void ASREnvelope::set_peak(float peak)
{
m_peak = peak;
m_attack.set_begin_value(0.0f);
m_attack.set_end_value(peak);
m_release.set_begin_value(peak);
m_release.set_end_value(0.0f);
}
void ASREnvelope::set_length_in_seconds(EnvelopeStage stage, float seconds)
{
switch (stage)
{
case kAttack:
m_attack.set_length_in_seconds(seconds);
break;
case kRelease:
m_release.set_length_in_seconds(seconds);
break;
default:
break;
}
}
void ASREnvelope::set_length_in_samples(EnvelopeStage stage, uint32_t samples)
{
switch (stage)
{
case kAttack:
m_attack.set_length_in_samples(samples);
break;
case kRelease:
m_release.set_length_in_samples(samples);
break;
default:
break;
}
}
float ASREnvelope::get_length_in_seconds(EnvelopeStage stage)
{
switch (stage)
{
case kAttack:
return m_attack.get_length_in_seconds();
case kRelease:
return m_release.get_length_in_seconds();
default:
break;
}
return 0.0f;
}
uint32_t ASREnvelope::get_length_in_samples(EnvelopeStage stage)
{
switch (stage)
{
case kAttack:
return m_attack.get_length_in_samples();
case kRelease:
return m_release.get_length_in_samples();
default:
break;
}
return 0;
}
void ASREnvelope::set_curve_type(EnvelopeStage stage, AudioRamp::CurveType theType)
{
switch (stage)
{
case kAttack:
m_attack.set_curve_type(theType);
break;
case kRelease:
m_release.set_curve_type(theType);
break;
default:
break;
}
}
void ASREnvelope::recompute()
{
// Recompute the slope of both ramps.
m_attack.recompute();
m_release.recompute();
}
void ASREnvelope::set_release_offset(uint32_t offset)
{
m_releaseOffset = m_elapsedSamples + offset;
}
void ASREnvelope::reset()
{
m_attack.reset();
m_release.reset();
m_elapsedSamples = 0;
m_releaseOffset = 0;
}
float ASREnvelope::next()
{
float sample;
process(&sample, 1);
return sample;
}
bool ASREnvelope::is_finished()
{
return (m_mode != kLoopingAR) && (m_attack.is_finished()
&& (!m_enableSustain || (m_releaseOffset != 0 && m_elapsedSamples >= m_releaseOffset))
&& m_release.is_finished());
}
void ASREnvelope::process(float * samples, uint32_t count)
{
uint32_t totalRemaining = count;
while (totalRemaining)
{
// Special case to prevent infinite loop if the stages are both 0 length and
// we're in the looping envelope mode.
if (m_mode == kLoopingAR
&& m_attack.get_length_in_samples() == 0
&& m_release.get_length_in_samples() == 0)
{
arm_fill_f32(m_peak, samples, totalRemaining);
return;
}
// Attack.
uint32_t attackCount = m_attack.get_remaining_samples();
if (attackCount > count)
{
attackCount = count;
}
if (attackCount)
{
m_attack.process(samples, attackCount);
}
// Sustain.
if (attackCount < count)
{
int32_t sustainCount = 0;
if (m_enableSustain)
{
sustainCount = count - attackCount;
if (m_releaseOffset > 0)
{
if (attackCount + sustainCount + m_elapsedSamples > m_releaseOffset)
{
sustainCount = m_releaseOffset - m_elapsedSamples - attackCount;
if (sustainCount < 0)
{
sustainCount = 0;
}
}
}
if (sustainCount > 0)
{
arm_fill_f32(m_peak, samples + attackCount, sustainCount);
}
}
// Release.
uint32_t attackSustainCount = attackCount + sustainCount;
if (attackSustainCount < count)
{
uint32_t releaseCount = count - attackSustainCount;
if (m_mode == kLoopingAR)
{
uint32_t releaseRemaining = m_release.get_remaining_samples();
if (releaseRemaining > releaseCount)
{
m_release.process(samples + attackSustainCount, releaseCount);
}
else
{
// Fill last part of release stage, then retrigger and loop.
m_release.process(samples + attackSustainCount, releaseRemaining);
reset();
uint32_t thisLoopCount = attackSustainCount + releaseRemaining;
totalRemaining -= thisLoopCount;
samples += thisLoopCount;
m_elapsedSamples += thisLoopCount;
count = releaseCount - releaseRemaining;
continue;
}
}
else
{
// For non-looping modes, we can just let the release stage fill to the end.
if (releaseCount)
{
m_release.process(samples + attackSustainCount, releaseCount);
}
}
}
}
totalRemaining -= count;
m_elapsedSamples += count;
}
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#pragma once
// std
#include <cstdint>
#include <map>
// project
#include "Type.hpp"
#include "Section.hpp"
#include "Memory.hpp"
namespace dai
{
namespace bootloader
{
namespace request {
enum Command : uint32_t {
USB_ROM_BOOT = 0,
BOOT_APPLICATION,
UPDATE_FLASH,
GET_BOOTLOADER_VERSION,
BOOT_MEMORY,
UPDATE_FLASH_EX,
UPDATE_FLASH_EX_2,
NO_OP,
GET_BOOTLOADER_TYPE,
SET_BOOTLOADER_CONFIG,
GET_BOOTLOADER_CONFIG,
BOOTLOADER_MEMORY,
};
struct BaseRequest {
BaseRequest(Command command) : cmd(command){}
Command cmd;
};
// Specific request PODs
struct UsbRomBoot : BaseRequest {
// Common
UsbRomBoot() : BaseRequest(USB_ROM_BOOT) {}
};
struct BootApplication : BaseRequest {
// Common
BootApplication() : BaseRequest(BOOT_APPLICATION) {}
// Data
};
struct UpdateFlash : BaseRequest {
// Common
UpdateFlash() : BaseRequest(UPDATE_FLASH) {}
// Data
enum Storage : uint32_t { SBR, BOOTLOADER };
Storage storage;
uint32_t totalSize;
uint32_t numPackets;
};
struct GetBootloaderVersion : BaseRequest {
// Common
GetBootloaderVersion() : BaseRequest(GET_BOOTLOADER_VERSION) {}
// Data
};
// 0.0.12 or higher
struct BootMemory : BaseRequest {
// Common
BootMemory() : BaseRequest(BOOT_MEMORY) {}
// Data
uint32_t totalSize;
uint32_t numPackets;
};
// UpdateFlashEx - Additional options
struct UpdateFlashEx : BaseRequest {
// Common
UpdateFlashEx() : BaseRequest(UPDATE_FLASH_EX) {}
// Data
Memory memory;
Section section;
uint32_t totalSize;
uint32_t numPackets;
};
// UpdateFlashEx2 - Additional options
struct UpdateFlashEx2 : BaseRequest {
// Common
UpdateFlashEx2() : BaseRequest(UPDATE_FLASH_EX_2) {}
// Data
Memory memory;
uint32_t offset;
uint32_t totalSize;
uint32_t numPackets;
};
struct GetBootloaderType : BaseRequest {
// Common
GetBootloaderType() : BaseRequest(GET_BOOTLOADER_TYPE) {}
// Data
};
// 0.0.14 or higher
struct SetBootloaderConfig : BaseRequest {
// Common
SetBootloaderConfig() : BaseRequest(SET_BOOTLOADER_CONFIG) {}
// Data
Memory memory;
uint32_t totalSize;
uint32_t numPackets;
};
struct GetBootloaderConfig : BaseRequest {
// Common
GetBootloaderConfig() : BaseRequest(GET_BOOTLOADER_CONFIG) {}
// Data
Memory memory;
};
struct BootloaderMemory : BaseRequest {
// Common
BootloaderMemory() : BaseRequest(BOOTLOADER_MEMORY) {}
// Data
};
}
namespace response {
enum Command : uint32_t {
FLASH_COMPLETE = 0,
FLASH_STATUS_UPDATE,
BOOTLOADER_VERSION,
BOOTLOADER_TYPE,
GET_BOOTLOADER_CONFIG,
BOOTLOADER_MEMORY,
};
struct BaseResponse {
BaseResponse(Command command) : cmd(command){}
Command cmd;
};
// Specific request PODs
struct FlashComplete : BaseResponse {
// Common
FlashComplete() : BaseResponse(FLASH_COMPLETE) {}
// Data
uint32_t success;
char errorMsg[64];
};
struct FlashStatusUpdate : BaseResponse {
// Common
FlashStatusUpdate() : BaseResponse(FLASH_STATUS_UPDATE) {}
// Data
float progress;
};
struct BootloaderVersion : BaseResponse {
// Common
BootloaderVersion() : BaseResponse(BOOTLOADER_VERSION) {}
// Data
uint32_t major, minor, patch;
};
struct BootloaderType : BaseResponse {
// Common
BootloaderType() : BaseResponse(BOOTLOADER_TYPE) {}
// Data
Type type;
};
// 0.0.14
struct GetBootloaderConfig : BaseResponse {
// Common
GetBootloaderConfig() : BaseResponse(GET_BOOTLOADER_CONFIG) {}
// Data
uint32_t success;
char errorMsg[64];
uint32_t totalSize;
uint32_t numPackets;
};
struct BootloaderMemory : BaseResponse {
// Common
GetBootloaderMemory() : BaseResponse(BOOTLOADER_MEMORY) {}
// Data
Memory memory;
};
}
} // namespace bootloader
} // namespace dai
<commit_msg>Fixed a bootloader memory response error<commit_after>#pragma once
// std
#include <cstdint>
#include <map>
// project
#include "Type.hpp"
#include "Section.hpp"
#include "Memory.hpp"
namespace dai
{
namespace bootloader
{
namespace request {
enum Command : uint32_t {
USB_ROM_BOOT = 0,
BOOT_APPLICATION,
UPDATE_FLASH,
GET_BOOTLOADER_VERSION,
BOOT_MEMORY,
UPDATE_FLASH_EX,
UPDATE_FLASH_EX_2,
NO_OP,
GET_BOOTLOADER_TYPE,
SET_BOOTLOADER_CONFIG,
GET_BOOTLOADER_CONFIG,
BOOTLOADER_MEMORY,
};
struct BaseRequest {
BaseRequest(Command command) : cmd(command){}
Command cmd;
};
// Specific request PODs
struct UsbRomBoot : BaseRequest {
// Common
UsbRomBoot() : BaseRequest(USB_ROM_BOOT) {}
};
struct BootApplication : BaseRequest {
// Common
BootApplication() : BaseRequest(BOOT_APPLICATION) {}
// Data
};
struct UpdateFlash : BaseRequest {
// Common
UpdateFlash() : BaseRequest(UPDATE_FLASH) {}
// Data
enum Storage : uint32_t { SBR, BOOTLOADER };
Storage storage;
uint32_t totalSize;
uint32_t numPackets;
};
struct GetBootloaderVersion : BaseRequest {
// Common
GetBootloaderVersion() : BaseRequest(GET_BOOTLOADER_VERSION) {}
// Data
};
// 0.0.12 or higher
struct BootMemory : BaseRequest {
// Common
BootMemory() : BaseRequest(BOOT_MEMORY) {}
// Data
uint32_t totalSize;
uint32_t numPackets;
};
// UpdateFlashEx - Additional options
struct UpdateFlashEx : BaseRequest {
// Common
UpdateFlashEx() : BaseRequest(UPDATE_FLASH_EX) {}
// Data
Memory memory;
Section section;
uint32_t totalSize;
uint32_t numPackets;
};
// UpdateFlashEx2 - Additional options
struct UpdateFlashEx2 : BaseRequest {
// Common
UpdateFlashEx2() : BaseRequest(UPDATE_FLASH_EX_2) {}
// Data
Memory memory;
uint32_t offset;
uint32_t totalSize;
uint32_t numPackets;
};
struct GetBootloaderType : BaseRequest {
// Common
GetBootloaderType() : BaseRequest(GET_BOOTLOADER_TYPE) {}
// Data
};
// 0.0.14 or higher
struct SetBootloaderConfig : BaseRequest {
// Common
SetBootloaderConfig() : BaseRequest(SET_BOOTLOADER_CONFIG) {}
// Data
Memory memory;
uint32_t totalSize;
uint32_t numPackets;
};
struct GetBootloaderConfig : BaseRequest {
// Common
GetBootloaderConfig() : BaseRequest(GET_BOOTLOADER_CONFIG) {}
// Data
Memory memory;
};
struct BootloaderMemory : BaseRequest {
// Common
BootloaderMemory() : BaseRequest(BOOTLOADER_MEMORY) {}
// Data
};
}
namespace response {
enum Command : uint32_t {
FLASH_COMPLETE = 0,
FLASH_STATUS_UPDATE,
BOOTLOADER_VERSION,
BOOTLOADER_TYPE,
GET_BOOTLOADER_CONFIG,
BOOTLOADER_MEMORY,
};
struct BaseResponse {
BaseResponse(Command command) : cmd(command){}
Command cmd;
};
// Specific request PODs
struct FlashComplete : BaseResponse {
// Common
FlashComplete() : BaseResponse(FLASH_COMPLETE) {}
// Data
uint32_t success;
char errorMsg[64];
};
struct FlashStatusUpdate : BaseResponse {
// Common
FlashStatusUpdate() : BaseResponse(FLASH_STATUS_UPDATE) {}
// Data
float progress;
};
struct BootloaderVersion : BaseResponse {
// Common
BootloaderVersion() : BaseResponse(BOOTLOADER_VERSION) {}
// Data
uint32_t major, minor, patch;
};
struct BootloaderType : BaseResponse {
// Common
BootloaderType() : BaseResponse(BOOTLOADER_TYPE) {}
// Data
Type type;
};
// 0.0.14
struct GetBootloaderConfig : BaseResponse {
// Common
GetBootloaderConfig() : BaseResponse(GET_BOOTLOADER_CONFIG) {}
// Data
uint32_t success;
char errorMsg[64];
uint32_t totalSize;
uint32_t numPackets;
};
struct BootloaderMemory : BaseResponse {
// Common
BootloaderMemory() : BaseResponse(BOOTLOADER_MEMORY) {}
// Data
Memory memory;
};
}
} // namespace bootloader
} // namespace dai
<|endoftext|> |
<commit_before>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : app/common/model.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// include i/f header
#include "model.hpp"
// includes, system
#include <boost/filesystem.hpp> // boost::filesystem::path
#include <glm/gtx/transform.hpp>
#include <oglplus/opt/resources.hpp>
// includes, project
//#include <>
#define UKACHULLDCS_USE_TRACE
#undef UKACHULLDCS_USE_TRACE
#include <support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
class file {
public:
file(std::string const& a)
: stream_()
{
TRACE("model::mesh::<unnamed>::file::file");
namespace bfs = boost::filesystem;
bfs::path const p(a);
std::string const d(p.parent_path().string());
std::string const f(p.stem().string());
std::string const e(p.extension().string());
#if defined(UKACHULLDCS_USE_TRACE)
std::cout << support::trace::prefix() << "model::mesh::<unnamed>::file::file: "
<< "'" << d + "/" + f + e << "'"
<< std::endl;
#endif
oglplus::OpenResourceFile(stream_, d, f, e.c_str());
}
std::ifstream& stream()
{
TRACE("model::mesh::<unnamed>::file::stream");
return stream_;
}
private:
std::ifstream stream_;
};
// variables, internal
// functions, internal
} // namespace {
namespace model {
// variables, exported
// functions, exported
/* explicit */
mesh::mesh(std::string const& a, oglplus::Program& b)
: prg_ (b),
mesh_ (file(a).stream()),
vao_ (),
positions_ (),
normals_ (),
tcoords_ (),
xform_ (),
mtl_id_ (-1)
{
TRACE("model::mesh::mesh");
using namespace oglplus;
{
oglplus::Spheref bsphere;
mesh_.BoundingSphere(bsphere);
if (!bsphere.Degenerate()) {
xform_ = (glm::scale (glm::vec3(1.0 / bsphere.Diameter())) *
glm::translate(-glm::vec3(bsphere.Center().x(),
bsphere.Center().y(),
bsphere.Center().z())));
}
}
vao_.Bind();
positions_.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex(mesh_.Positions(data));
Buffer::Data(Buffer::Target::Array, data);
(prg_|"position").Setup<GLfloat>(n_per_vertex).Enable();
}
normals_.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex(mesh_.Normals(data));
Buffer::Data(Buffer::Target::Array, data);
(prg_|"normal").Setup<GLfloat>(n_per_vertex).Enable();
}
tcoords_.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex(mesh_.TexCoordinates(data));
Buffer::Data(Buffer::Target::Array, data);
(prg_|"tcoords").Setup<GLfloat>(n_per_vertex).Enable();
}
}
glm::mat4 const&
mesh::xform() const
{
TRACE("model::mesh::xform(get)");
return xform_;
}
glm::mat4
mesh::xform(glm::mat4 const& a)
{
TRACE("model::mesh::xform(set)");
glm::mat4 const result(xform_);
xform_ = a;
return result;
}
void
mesh::draw()
{
TRACE("model::mesh::draw");
using namespace oglplus;
prg_.Use();
if (Uniform<glm::mat4>(prg_, "xform_model").IsActive()) {
Uniform<glm::mat4>(prg_, "xform_model").Set(xform_);
}
if (Lazy<Uniform<signed>>(prg_, "mtl_id").IsActive()) {
Lazy<Uniform<signed>>(prg_, "mtl_id").Set(mtl_id_);
}
vao_.Bind();
mesh_.Instructions().Draw(mesh_.Indices());
}
} // namespace model {
<commit_msg>cleanup<commit_after>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : app/common/model.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// include i/f header
#include "model.hpp"
// includes, system
#include <boost/filesystem.hpp> // boost::filesystem::path
#include <glm/gtx/transform.hpp>
#include <oglplus/opt/resources.hpp>
// includes, project
//#include <>
#define UKACHULLDCS_USE_TRACE
#undef UKACHULLDCS_USE_TRACE
#include <support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
class file {
public:
file(std::string const& a)
: stream_()
{
TRACE("model::mesh::<unnamed>::file::file");
namespace bfs = boost::filesystem;
bfs::path const p(a);
std::string const d(p.parent_path().string());
std::string const f(p.stem().string());
std::string const e(p.extension().string());
#if defined(UKACHULLDCS_USE_TRACE)
std::cout << support::trace::prefix() << "model::mesh::<unnamed>::file::file: "
<< "'" << d + "/" + f + e << "'"
<< std::endl;
#endif
oglplus::OpenResourceFile(stream_, d, f, e.c_str());
}
std::ifstream& stream()
{
TRACE("model::mesh::<unnamed>::file::stream");
return stream_;
}
private:
std::ifstream stream_;
};
// variables, internal
// functions, internal
} // namespace {
namespace model {
// variables, exported
// functions, exported
/* explicit */
mesh::mesh(std::string const& a, oglplus::Program& b)
: prg_ (b),
mesh_ (file(a).stream()),
vao_ (),
positions_ (),
normals_ (),
tcoords_ (),
xform_ (),
mtl_id_ (-1)
{
TRACE("model::mesh::mesh");
using namespace oglplus;
{
oglplus::Spheref bsphere;
mesh_.BoundingSphere(bsphere);
if (!bsphere.Degenerate()) {
xform_ = (glm::scale ( glm::vec3(1.0 / bsphere.Diameter())) *
glm::translate(-glm::vec3(bsphere.Center().x(),
bsphere.Center().y(),
bsphere.Center().z())));
}
}
vao_.Bind();
positions_.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex(mesh_.Positions(data));
Buffer::Data(Buffer::Target::Array, data);
(prg_|"position").Setup<GLfloat>(n_per_vertex).Enable();
}
normals_.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex(mesh_.Normals(data));
Buffer::Data(Buffer::Target::Array, data);
(prg_|"normal").Setup<GLfloat>(n_per_vertex).Enable();
}
tcoords_.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex(mesh_.TexCoordinates(data));
Buffer::Data(Buffer::Target::Array, data);
(prg_|"tcoords").Setup<GLfloat>(n_per_vertex).Enable();
}
}
glm::mat4 const&
mesh::xform() const
{
TRACE("model::mesh::xform(get)");
return xform_;
}
glm::mat4
mesh::xform(glm::mat4 const& a)
{
TRACE("model::mesh::xform(set)");
glm::mat4 const result(xform_);
xform_ = a;
return result;
}
void
mesh::draw()
{
TRACE("model::mesh::draw");
using namespace oglplus;
prg_.Use();
if (Uniform<glm::mat4>(prg_, "xform_model").IsActive()) {
Uniform<glm::mat4>(prg_, "xform_model").Set(xform_);
}
if (Lazy<Uniform<signed>>(prg_, "mtl_id").IsActive()) {
Lazy<Uniform<signed>>(prg_, "mtl_id").Set(mtl_id_);
}
vao_.Bind();
mesh_.Instructions().Draw(mesh_.Indices());
}
} // namespace model {
<|endoftext|> |
<commit_before>/* mockturtle: C++ logic network library
* Copyright (C) 2018 EPFL
*
* 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.
*/
/*!
\file resubstitution.hpp
\brief Resubstitution
\author Heinz Riener
*/
#pragma once
#include "../networks/mig.hpp"
#include "../traits.hpp"
#include "../algorithms/simulation.hpp"
#include "../algorithms/reconv_cut.hpp"
#include "../algorithms/mffc_utils.hpp"
#include "../utils/progress_bar.hpp"
#include "../utils/stopwatch.hpp"
#include "../views/fanout_view.hpp"
#include "../views/window_view.hpp"
#include "../views/depth_view.hpp"
#include <fmt/format.h>
#include <kitty/dynamic_truth_table.hpp>
#include <kitty/kitty.hpp>
#include <iostream>
// #include "../algorithms/akers_synthesis.hpp"
// #include "../algorithms/cut_rewriting.hpp"
// #include "../views/cut_view.hpp"
// #include "../views/mffc_view.hpp"
// #include "../views/topo_view.hpp"
namespace mockturtle
{
/*! \brief Parameters for resubstitution.
*
* The data structure `resubstitution_params` holds configurable parameters with
* default arguments for `resubstitution`.
*/
struct resubstitution_params
{
/*! \brief Maximum number of PIs of reconvergence-driven cuts. */
uint32_t max_pis{6};
/*! \brief Maximum number of nodes per reconvergence-driven window. */
uint32_t max_nodes{200};
/*! \brief Maximum number of nodes added by resubstitution. */
uint32_t max_inserts{0};
/*! \brief Show progress. */
bool progress{false};
/*! \brief Be verbose. */
bool verbose{false};
};
struct resubstitution_stats
{
stopwatch<>::duration time_total{0};
stopwatch<>::duration time_simulation{0};
stopwatch<>::duration time_resubstitution{0};
void report() const
{
std::cout << fmt::format( "[i] total time = {:>5.2f} secs\n", to_seconds( time_total ) );
std::cout << fmt::format( "[i] simulation time = {:>5.2f} secs\n", to_seconds( time_simulation ) );
std::cout << fmt::format( "[i] resubstituion time = {:>5.2f} secs\n", to_seconds( time_resubstitution ) );
}
};
namespace detail
{
template<class Ntk>
class resubstitution_impl
{
public:
using node = node<Ntk>;
using signal = signal<Ntk>;
using window = depth_view<window_view<fanout_view<Ntk>>>;
explicit resubstitution_impl( Ntk& ntk, resubstitution_params const& ps, resubstitution_stats& st )
: ntk( ntk ), fanout_ntk( ntk ), ps( ps ), st( st )
{
}
bool resubstitute_node( window& win, node const& n, signal const& s )
{
const auto& r = ntk.get_node( s );
int32_t gain = detail::recursive_deref( win, /* original node */n );
gain -= detail::recursive_ref( win, /* replace with */r );
if ( gain > 0 )
{
++_candidates;
_estimated_gain += gain;
ntk.substitute_node_of_parents( fanout_ntk.fanout( n ), n, s );
ntk.set_value( n, 0 );
ntk.set_value( r, ntk.fanout_size( r ) );
return true;
}
else
{
detail::recursive_deref( win, /* replaced with */r );
detail::recursive_ref( win, /* original node */n );
return false;
}
}
void zero_resubstitution( window& win, node const& n, node_map<kitty::dynamic_truth_table,window> const& tts )
{
std::vector<node> gates;
win.foreach_gate( [&]( auto const& n ){
gates.push_back( n );
});
ntk.foreach_gate( [&]( auto const& x ){
if ( x == n || win.level( x ) >= win.level( n ) )
{
return true; /* next */
}
if ( tts[ n ] == tts[ x ] )
{
const auto result = resubstitute_node( win, n, ntk.make_signal( x ) );
if ( result ) return false; /* accept */
}
else if ( tts[ n ] == ~tts[ x ] )
{
const auto result = resubstitute_node( win, n, !ntk.make_signal( x ) );
if ( result ) return false; /* accept */
}
return true; /* next */
});
}
void run()
{
const auto size = ntk.size();
progress_bar pbar{ntk.size(), "|{0}| node = {1:>4} cand = {2:>4} est. reduction = {3:>5}", ps.progress};
stopwatch t( st.time_total );
ntk.clear_visited();
ntk.clear_values();
ntk.foreach_node( [&]( auto const& n ) {
ntk.set_value( n, ntk.fanout_size( n ) );
} );
ntk.foreach_gate( [&]( auto const& n, auto i ){
if ( i >= size )
{
return false;
}
pbar( i, i, _candidates, _estimated_gain );
auto const mffc_size = detail::mffc_size( ntk, n );
if ( mffc_size > 1 )
{
reconv_cut_params params{ ps.max_pis };
auto const& leaves = reconv_cut( params )( ntk, { n } );
window_view<fanout_view<Ntk>> extended_cut( fanout_ntk, leaves, { n } );
if ( extended_cut.size() > ps.max_nodes ) return true;
depth_view win( extended_cut );
default_simulator<kitty::dynamic_truth_table> sim( win.num_pis() );
const auto tts = call_with_stopwatch( st.time_simulation,
[&]() { return simulate_nodes<kitty::dynamic_truth_table>( win, sim ); } );
call_with_stopwatch( st.time_resubstitution,
[&]() { zero_resubstitution( win, n, tts ); } );
}
return true;
});
}
private:
Ntk& ntk;
fanout_view<Ntk> fanout_ntk;
resubstitution_params const& ps;
resubstitution_stats& st;
uint32_t _candidates{0};
uint32_t _estimated_gain{0};
};
} /* namespace detail */
/*! \brief Boolean resubstitution.
*
* **Required network functions:**
* - `get_node`
* - `size`
* - `make_signal`
* - `foreach_gate`
* - `substitute_node_of_parents`
* - `clear_visited`
* - `clear_values`
* - `fanout_size`
* - `set_value`
* - `foreach_node`
*
* \param ntk Input network (will be changed in-place)
* \param ps Resubstitution params
*/
template<class Ntk>
void resubstitution( Ntk& ntk, resubstitution_params const& ps = {} )
{
static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" );
static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" );
static_assert( has_size_v<Ntk>, "Ntk does not implement the size method" );
static_assert( has_make_signal_v<Ntk>, "Ntk does not implement the make_signal method" );
static_assert( has_foreach_gate_v<Ntk>, "Ntk does not implement the foreach_gate method" );
static_assert( has_substitute_node_of_parents_v<Ntk>, "Ntk does not implement the substitute_node_of_parents method" );
static_assert( has_clear_visited_v<Ntk>, "Ntk does not implement the clear_visited method" );
static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the clear_values method" );
static_assert( has_fanout_size_v<Ntk>, "Ntk does not implement the fanout_size method" );
static_assert( has_set_value_v<Ntk>, "Ntk does not implement the set_value method" );
static_assert( has_foreach_node_v<Ntk>, "Ntk does not implement the foreach_node method" );
resubstitution_stats st;
detail::resubstitution_impl<Ntk> p( ntk, ps, st );
p.run();
if ( ps.verbose )
{
st.report();
}
}
} /* namespace mockturtle */
<commit_msg>resubstitution.<commit_after>/* mockturtle: C++ logic network library
* Copyright (C) 2018 EPFL
*
* 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.
*/
/*!
\file resubstitution.hpp
\brief Resubstitution
\author Heinz Riener
*/
#pragma once
#include "../networks/mig.hpp"
#include "../traits.hpp"
#include "../algorithms/simulation.hpp"
#include "../algorithms/reconv_cut.hpp"
#include "../algorithms/mffc_utils.hpp"
#include "../utils/progress_bar.hpp"
#include "../utils/stopwatch.hpp"
#include "../views/fanout_view.hpp"
#include "../views/window_view.hpp"
#include "../views/depth_view.hpp"
#include <fmt/format.h>
#include <kitty/dynamic_truth_table.hpp>
#include <kitty/kitty.hpp>
#include <iostream>
// #include "../algorithms/akers_synthesis.hpp"
// #include "../algorithms/cut_rewriting.hpp"
// #include "../views/cut_view.hpp"
// #include "../views/mffc_view.hpp"
// #include "../views/topo_view.hpp"
namespace mockturtle
{
/*! \brief Parameters for resubstitution.
*
* The data structure `resubstitution_params` holds configurable parameters with
* default arguments for `resubstitution`.
*/
struct resubstitution_params
{
/*! \brief Maximum number of PIs of reconvergence-driven cuts. */
uint32_t max_pis{6};
/*! \brief Maximum number of nodes per reconvergence-driven window. */
uint32_t max_nodes{200};
/*! \brief Maximum number of nodes added by resubstitution. */
uint32_t max_inserts{0};
/*! \brief Show progress. */
bool progress{false};
/*! \brief Be verbose. */
bool verbose{false};
};
struct resubstitution_stats
{
stopwatch<>::duration time_total{0};
stopwatch<>::duration time_simulation{0};
stopwatch<>::duration time_resubstitution{0};
void report() const
{
std::cout << fmt::format( "[i] total time = {:>5.2f} secs\n", to_seconds( time_total ) );
std::cout << fmt::format( "[i] simulation time = {:>5.2f} secs\n", to_seconds( time_simulation ) );
std::cout << fmt::format( "[i] resubstituion time = {:>5.2f} secs\n", to_seconds( time_resubstitution ) );
}
};
namespace detail
{
template<class Ntk>
class resubstitution_impl
{
public:
using node = typename Ntk::node;
using signal = typename Ntk::signal;
using window = depth_view<window_view<fanout_view<Ntk>>>;
explicit resubstitution_impl( Ntk& ntk, resubstitution_params const& ps, resubstitution_stats& st )
: ntk( ntk ), fanout_ntk( ntk ), ps( ps ), st( st )
{
}
bool resubstitute_node( window& win, node const& n, signal const& s )
{
const auto& r = ntk.get_node( s );
int32_t gain = detail::recursive_deref( win, /* original node */n );
gain -= detail::recursive_ref( win, /* replace with */r );
if ( gain > 0 )
{
++_candidates;
_estimated_gain += gain;
ntk.substitute_node_of_parents( fanout_ntk.fanout( n ), n, s );
ntk.set_value( n, 0 );
ntk.set_value( r, ntk.fanout_size( r ) );
return true;
}
else
{
detail::recursive_deref( win, /* replaced with */r );
detail::recursive_ref( win, /* original node */n );
return false;
}
}
void zero_resubstitution( window& win, node const& n, node_map<kitty::dynamic_truth_table,window> const& tts )
{
std::vector<node> gates;
win.foreach_gate( [&]( auto const& n ){
gates.push_back( n );
});
ntk.foreach_gate( [&]( auto const& x ){
if ( x == n || win.level( x ) >= win.level( n ) )
{
return true; /* next */
}
if ( tts[ n ] == tts[ x ] )
{
const auto result = resubstitute_node( win, n, ntk.make_signal( x ) );
if ( result ) return false; /* accept */
}
else if ( tts[ n ] == ~tts[ x ] )
{
const auto result = resubstitute_node( win, n, !ntk.make_signal( x ) );
if ( result ) return false; /* accept */
}
return true; /* next */
});
}
void run()
{
const auto size = ntk.size();
progress_bar pbar{ntk.size(), "|{0}| node = {1:>4} cand = {2:>4} est. reduction = {3:>5}", ps.progress};
stopwatch t( st.time_total );
ntk.clear_visited();
ntk.clear_values();
ntk.foreach_node( [&]( auto const& n ) {
ntk.set_value( n, ntk.fanout_size( n ) );
} );
ntk.foreach_gate( [&]( auto const& n, auto i ){
if ( i >= size )
{
return false;
}
pbar( i, i, _candidates, _estimated_gain );
auto const mffc_size = detail::mffc_size( ntk, n );
if ( mffc_size > 1 )
{
reconv_cut_params params{ ps.max_pis };
auto const& leaves = reconv_cut( params )( ntk, { n } );
window_view<fanout_view<Ntk>> extended_cut( fanout_ntk, leaves, { n } );
if ( extended_cut.size() > ps.max_nodes ) return true;
depth_view win( extended_cut );
default_simulator<kitty::dynamic_truth_table> sim( win.num_pis() );
const auto tts = call_with_stopwatch( st.time_simulation,
[&]() { return simulate_nodes<kitty::dynamic_truth_table>( win, sim ); } );
call_with_stopwatch( st.time_resubstitution,
[&]() { zero_resubstitution( win, n, tts ); } );
}
return true;
});
}
private:
Ntk& ntk;
fanout_view<Ntk> fanout_ntk;
resubstitution_params const& ps;
resubstitution_stats& st;
uint32_t _candidates{0};
uint32_t _estimated_gain{0};
};
} /* namespace detail */
/*! \brief Boolean resubstitution.
*
* **Required network functions:**
* - `get_node`
* - `size`
* - `make_signal`
* - `foreach_gate`
* - `substitute_node_of_parents`
* - `clear_visited`
* - `clear_values`
* - `fanout_size`
* - `set_value`
* - `foreach_node`
*
* \param ntk Input network (will be changed in-place)
* \param ps Resubstitution params
*/
template<class Ntk>
void resubstitution( Ntk& ntk, resubstitution_params const& ps = {} )
{
static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" );
static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" );
static_assert( has_size_v<Ntk>, "Ntk does not implement the size method" );
static_assert( has_make_signal_v<Ntk>, "Ntk does not implement the make_signal method" );
static_assert( has_foreach_gate_v<Ntk>, "Ntk does not implement the foreach_gate method" );
static_assert( has_substitute_node_of_parents_v<Ntk>, "Ntk does not implement the substitute_node_of_parents method" );
static_assert( has_clear_visited_v<Ntk>, "Ntk does not implement the clear_visited method" );
static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the clear_values method" );
static_assert( has_fanout_size_v<Ntk>, "Ntk does not implement the fanout_size method" );
static_assert( has_set_value_v<Ntk>, "Ntk does not implement the set_value method" );
static_assert( has_foreach_node_v<Ntk>, "Ntk does not implement the foreach_node method" );
resubstitution_stats st;
detail::resubstitution_impl<Ntk> p( ntk, ps, st );
p.run();
if ( ps.verbose )
{
st.report();
}
}
} /* namespace mockturtle */
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/*
* $Id$
*/
#if !defined(XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP)
#define XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP
//
// There are two primary xerces configuration header files:
//
// Xerces_autoconf_config.hpp
//
// For configuration of items that must be accessable
// through public headers. This file has limited information
// and carefully works to avoid collision of macro names, etc.
//
// This file is included by XercesDefs.h.
// This version of the file is specific for Microsoft Visual C++
// family of compilers
//
// config.h
//
// This file is not used with Microsoft Visual C++; the macros
// it would specify are instead hardcoded in the makefiles
//
#include <basetsd.h>
// silence the warning "while compiling class-template member function xxxx : identifier was truncated to '255'
// characters in the browser information"
#pragma warning( disable: 4786 )
// ---------------------------------------------------------------------------
// These defines have been hardcoded for the Microsoft Visual C++ compilers
// ---------------------------------------------------------------------------
#undef XERCES_AUTOCONF
#undef XERCES_HAVE_SYS_TYPES_H
#undef XERCES_HAVE_INTTYPES_H
#define XERCES_S16BIT_INT signed short
#define XERCES_U16BIT_INT unsigned short
#define XERCES_S32BIT_INT INT32
#define XERCES_U32BIT_INT UINT32
#define XERCES_S64BIT_INT INT64
#define XERCES_U64BIT_INT UINT64
#define XERCES_SIZEOF_INT 4
#define XERCES_SIZEOF_LONG 4
#define XERCES_SIZEOF_INT64 8
#ifdef _NATIVE_WCHAR_T_DEFINED
#define XERCES_XMLCH_T wchar_t
#else
#define XERCES_XMLCH_T unsigned short
#endif
#define XERCES_SIZE_T SIZE_T
#define XERCES_SSIZE_T SSIZE_T
#define XERCES_HAS_CPP_NAMESPACE 1
#define XERCES_STD_NAMESPACE 1
#define XERCES_NEW_IOSTREAMS 1
#undef XERCES_NO_NATIVE_BOOL
#define XERCES_LSTRSUPPORT 1
#ifdef XERCES_STATIC_LIBRARY
#define XERCES_PLATFORM_EXPORT
#define XERCES_PLATFORM_IMPORT
#else
#define XERCES_PLATFORM_EXPORT __declspec(dllexport)
#define XERCES_PLATFORM_IMPORT __declspec(dllimport)
#define DLL_EXPORT
#endif
#define XERCES_MFC_SUPPORT
// ---------------------------------------------------------------------------
// XMLSize_t is the unsigned integral type.
// ---------------------------------------------------------------------------
typedef XERCES_SIZE_T XMLSize_t;
typedef XERCES_SSIZE_T XMLSSize_t;
// ---------------------------------------------------------------------------
// Define our version of the XML character
// ---------------------------------------------------------------------------
typedef XERCES_XMLCH_T XMLCh;
// ---------------------------------------------------------------------------
// Define unsigned 16, 32, and 64 bit integers
// ---------------------------------------------------------------------------
typedef XERCES_U16BIT_INT XMLUInt16;
typedef XERCES_U32BIT_INT XMLUInt32;
typedef XERCES_U64BIT_INT XMLUInt64;
// ---------------------------------------------------------------------------
// Define signed 16, 32, and 64 bit integers
// ---------------------------------------------------------------------------
typedef XERCES_S16BIT_INT XMLInt16;
typedef XERCES_S32BIT_INT XMLInt32;
typedef XERCES_S64BIT_INT XMLInt64;
// ---------------------------------------------------------------------------
// XMLFilePos is the type used to represent a file position.
// ---------------------------------------------------------------------------
typedef XMLUInt64 XMLFilePos;
// ---------------------------------------------------------------------------
// XMLFileLoc is the type used to represent a file location (line/column).
// ---------------------------------------------------------------------------
typedef XMLUInt64 XMLFileLoc;
// ---------------------------------------------------------------------------
// Force on the Xerces debug token if it is on in the build environment
// ---------------------------------------------------------------------------
#if defined(_DEBUG)
#define XERCES_DEBUG
#endif
#endif
<commit_msg>Stick to 32-bit int on VC6.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/*
* $Id$
*/
#if !defined(XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP)
#define XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP
//
// There are two primary xerces configuration header files:
//
// Xerces_autoconf_config.hpp
//
// For configuration of items that must be accessable
// through public headers. This file has limited information
// and carefully works to avoid collision of macro names, etc.
//
// This file is included by XercesDefs.h.
// This version of the file is specific for Microsoft Visual C++
// family of compilers
//
// config.h
//
// This file is not used with Microsoft Visual C++; the macros
// it would specify are instead hardcoded in the makefiles
//
#include <basetsd.h>
// silence the warning "while compiling class-template member function xxxx : identifier was truncated to '255'
// characters in the browser information"
#pragma warning( disable: 4786 )
// ---------------------------------------------------------------------------
// These defines have been hardcoded for the Microsoft Visual C++ compilers
// ---------------------------------------------------------------------------
#undef XERCES_AUTOCONF
#undef XERCES_HAVE_SYS_TYPES_H
#undef XERCES_HAVE_INTTYPES_H
#define XERCES_S16BIT_INT signed short
#define XERCES_U16BIT_INT unsigned short
#define XERCES_S32BIT_INT INT32
#define XERCES_U32BIT_INT UINT32
// While VC6 has 64-bit int, there is no support in the libraries
// (e.g., iostream). So we are going to stick to 32-bit ints.
//
#if (_MSC_VER >= 1300)
# define XERCES_S64BIT_INT INT64
# define XERCES_U64BIT_INT UINT64
#else
# define XERCES_S64BIT_INT INT32
# define XERCES_U64BIT_INT UINT32
#endif
#define XERCES_SIZEOF_INT 4
#define XERCES_SIZEOF_LONG 4
#if (_MSC_VER >= 1300)
# define XERCES_SIZEOF_INT64 8
#else
# define XERCES_SIZEOF_INT64 4
#endif
#ifdef _NATIVE_WCHAR_T_DEFINED
#define XERCES_XMLCH_T wchar_t
#else
#define XERCES_XMLCH_T unsigned short
#endif
#define XERCES_SIZE_T SIZE_T
#define XERCES_SSIZE_T SSIZE_T
#define XERCES_HAS_CPP_NAMESPACE 1
#define XERCES_STD_NAMESPACE 1
#define XERCES_NEW_IOSTREAMS 1
#undef XERCES_NO_NATIVE_BOOL
#define XERCES_LSTRSUPPORT 1
#ifdef XERCES_STATIC_LIBRARY
#define XERCES_PLATFORM_EXPORT
#define XERCES_PLATFORM_IMPORT
#else
#define XERCES_PLATFORM_EXPORT __declspec(dllexport)
#define XERCES_PLATFORM_IMPORT __declspec(dllimport)
#define DLL_EXPORT
#endif
#define XERCES_MFC_SUPPORT
// ---------------------------------------------------------------------------
// XMLSize_t is the unsigned integral type.
// ---------------------------------------------------------------------------
typedef XERCES_SIZE_T XMLSize_t;
typedef XERCES_SSIZE_T XMLSSize_t;
// ---------------------------------------------------------------------------
// Define our version of the XML character
// ---------------------------------------------------------------------------
typedef XERCES_XMLCH_T XMLCh;
// ---------------------------------------------------------------------------
// Define unsigned 16, 32, and 64 bit integers
// ---------------------------------------------------------------------------
typedef XERCES_U16BIT_INT XMLUInt16;
typedef XERCES_U32BIT_INT XMLUInt32;
typedef XERCES_U64BIT_INT XMLUInt64;
// ---------------------------------------------------------------------------
// Define signed 16, 32, and 64 bit integers
// ---------------------------------------------------------------------------
typedef XERCES_S16BIT_INT XMLInt16;
typedef XERCES_S32BIT_INT XMLInt32;
typedef XERCES_S64BIT_INT XMLInt64;
// ---------------------------------------------------------------------------
// XMLFilePos is the type used to represent a file position.
// ---------------------------------------------------------------------------
typedef XMLUInt64 XMLFilePos;
// ---------------------------------------------------------------------------
// XMLFileLoc is the type used to represent a file location (line/column).
// ---------------------------------------------------------------------------
typedef XMLUInt64 XMLFileLoc;
// ---------------------------------------------------------------------------
// Force on the Xerces debug token if it is on in the build environment
// ---------------------------------------------------------------------------
#if defined(_DEBUG)
#define XERCES_DEBUG
#endif
#endif
<|endoftext|> |
<commit_before>#include <node.h>
#include <windows.h>
#include <algorithm>
#define min(left,right) std::min(left,right)
#define max(left,right) std::max(left,right)
#include <gdiplus.h>
#include "appjs.h"
#include "includes/cef.h"
#include "includes/util.h"
#include "includes/cef_handler.h"
#include "base/native_window.h"
#define MAX_LOADSTRING 100
extern CefRefPtr<ClientHandler> g_handler;
namespace appjs {
using namespace v8;
TCHAR szWindowClass[MAX_LOADSTRING];
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
ATOM MyRegisterClass(HINSTANCE hInstance);
HICON smallIcon;
HICON bigIcon;
Settings* browserSettings;
char* url_;
void NativeWindow::Init(char* url, Settings* settings) {
url_ = url;
if( !g_handler->GetBrowserHwnd() ) {
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
WCHAR* wSmallIconPath = icons->getString("small",L"");
WCHAR* wBigIconPath = icons->getString("big",L"");
Gdiplus::Bitmap* smallIconBitmap = Gdiplus::Bitmap::FromFile(wSmallIconPath);
Gdiplus::Bitmap* bigIconBitmap = Gdiplus::Bitmap::FromFile(wBigIconPath);
if( smallIconBitmap->GetWidth() ) {
smallIconBitmap->GetHICON(&smallIcon);
delete[] wSmallIconPath;
delete smallIconBitmap;
}
if( bigIconBitmap->GetWidth() ) {
bigIconBitmap->GetHICON(&bigIcon);
delete[] wBigIconPath;
delete bigIconBitmap;
}
}
HINSTANCE hInstance = GetModuleHandle(NULL);
strcpy(szWindowClass,"AppjsWindow");
browserSettings = settings;
if(!MyRegisterClass(hInstance)){
//TODO send error to node
if( GetLastError() != 1410 ) { //1410: Class Already Registered
fprintf(stderr,"Error occurred: ");
fprintf(stderr,"%d\n",GetLastError());
return;
}
};
DWORD commonStyle = WS_CLIPCHILDREN;
DWORD style;
// set resizable
if( !resizable ) {
style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
} else {
style = WS_OVERLAPPEDWINDOW;
}
// set chrome
if( show_chrome ) {
commonStyle |= style;
} else {
commonStyle |= WS_POPUP;
}
if( x < 0 || y < 0 ) {
x = (GetSystemMetrics(SM_CXSCREEN) - width) / 2;
y = (GetSystemMetrics(SM_CYSCREEN) - height) / 2;
}
// Perform application initialization
browser_ = NULL;
handle_ = CreateWindowEx(NULL, szWindowClass,"", commonStyle, x, y, width, height, NULL, NULL, hInstance, NULL);
if (!handle_) {
//TODO send error to node
fprintf(stderr,"Error occurred: ");
fprintf(stderr,"%d\n",GetLastError());
return;
}
//set window opacity
SetWindowLong(handle_, GWL_EXSTYLE, GetWindowLong(handle_, GWL_EXSTYLE) | WS_EX_LAYERED);
SetWindowLongPtr(handle_,GWLP_USERDATA, (LONG)this);
SetLayeredWindowAttributes(handle_, 0, 255 * opacity, LWA_ALPHA);
UpdateWindow(handle_);
Cef::Run();
};
int NativeWindow::ScreenWidth() {
return GetSystemMetrics(SM_CXSCREEN);
}
int NativeWindow::ScreenHeight() {
return GetSystemMetrics(SM_CYSCREEN);
}
void NativeWindow::Show() {
if (browser_) {
ShowWindow(handle_, SW_SHOW);
}
}
void NativeWindow::Hide() {
if (browser_) {
ShowWindow(handle_, SW_HIDE);
}
}
void NativeWindow::Destroy() {
if (browser_) {
CloseWindow(handle_);
}
}
// Register Class
ATOM MyRegisterClass(HINSTANCE hInstance) {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = bigIcon;
wcex.hIconSm = smallIcon;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
return RegisterClassEx(&wcex);
}
// Processes messages for the main window.
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
// Callback for the main window
switch (message) {
case WM_CREATE: {
NativeWindow* window = ClientHandler::GetWindow(hwnd);
RECT rect;
GetClientRect(hwnd, &rect);
// Initialize window info to the defaults for a child window
Cef::AddWebView(hwnd, rect, url_, browserSettings);
return 0;
}
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc;
hdc = BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
return 0;
}
/*case WM_SETFOCUS:
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
// Pass focus to the browser window
PostMessage(g_handler->GetBrowserHwnd(), WM_SETFOCUS, wParam, NULL);
}
return 0;*/
case WM_SIZE: {
NativeWindow* window = ClientHandler::GetWindow(hwnd);
if (window->GetBrowser()) {
// Resize the browser window to match the new frame
// window size
//TODO this code only resizes main browser. What if we have multiple browsers?
/*RECT rect;
GetClientRect(handle_, &rect);
HDWP hdwp = BeginDeferWindowPos(1);
hdwp = DeferWindowPos(hdwp, g_handler->GetBrowserHwnd(), NULL,
rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
SWP_NOZORDER);
EndDeferWindowPos(hdwp);*/
}
break;
}
case WM_ERASEBKGND: {
NativeWindow* window = ClientHandler::GetWindow(hwnd);
if (window->GetBrowser()) {
// Dont erase the background if the browser window has been loaded
// (this avoids flashing)
return 0;
}
break;
}
case WM_CLOSE: {
NativeWindow* window = ClientHandler::GetWindow(hwnd);
if (window->GetBrowser()) {
window->GetBrowser()->ParentWindowWillClose();
}
break;
}
/*case WM_DESTROY:
//PostQuitMessage(0);
return 0;*/
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
} /* appjs */
<commit_msg>windows bindings to new stuff<commit_after>#include <node.h>
#include <windows.h>
#include <algorithm>
#define min(left,right) std::min(left,right)
#define max(left,right) std::max(left,right)
#include <gdiplus.h>
#include <dwmapi.h>
#include "appjs.h"
#include "includes/cef.h"
#include "includes/util.h"
#include "includes/cef_handler.h"
#include "base/native_window.h"
#define MAX_LOADSTRING 100
extern CefRefPtr<ClientHandler> g_handler;
namespace appjs {
using namespace v8;
TCHAR szWindowClass[MAX_LOADSTRING];
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
ATOM MyRegisterClass(HINSTANCE hInstance);
HICON smallIcon;
HICON bigIcon;
Settings* browserSettings;
char* url_;
void UpdateStyle(HWND hwnd, int index, LONG value){
SetWindowLong(hwnd, index, value);
SetWindowPos(hwnd, NULL, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
}
void BlurBehind(HWND hwnd, bool enable){
DWM_BLURBEHIND bb = {0};
bb.fEnable = enable;
bb.hRgnBlur = NULL;
bb.dwFlags = DWM_BB_ENABLE;
DwmEnableBlurBehindWindow(hwnd, &bb);
}
void NativeWindow::Init(char* url, Settings* settings) {
url_ = url;
blur_ = settings->getBoolean("blur", false);
if( !g_handler->GetBrowserHwnd() ) {
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
WCHAR* wSmallIconPath = icons->getString("small",L"");
WCHAR* wBigIconPath = icons->getString("big",L"");
Gdiplus::Bitmap* smallIconBitmap = Gdiplus::Bitmap::FromFile(wSmallIconPath);
Gdiplus::Bitmap* bigIconBitmap = Gdiplus::Bitmap::FromFile(wBigIconPath);
if( smallIconBitmap->GetWidth() ) {
smallIconBitmap->GetHICON(&smallIcon);
delete[] wSmallIconPath;
delete smallIconBitmap;
}
if( bigIconBitmap->GetWidth() ) {
bigIconBitmap->GetHICON(&bigIcon);
delete[] wBigIconPath;
delete bigIconBitmap;
}
}
HINSTANCE hInstance = GetModuleHandle(NULL);
strcpy(szWindowClass,"AppjsWindow");
browserSettings = settings;
if(!MyRegisterClass(hInstance)){
//TODO send error to node
if( GetLastError() != 1410 ) { //1410: Class Already Registered
fprintf(stderr,"Error occurred: ");
fprintf(stderr,"%d\n",GetLastError());
return;
}
};
DWORD commonStyle = WS_OVERLAPPEDWINDOW;
DWORD style;
if( !resizable ) {
style &= ~(WS_THICKFRAME);
}
// set chrome
if( show_chrome ) {
commonStyle |= style;
} else {
commonStyle |= WS_POPUP;
}
if( left_ < 0 || top_ < 0 ) {
left_ = (GetSystemMetrics(SM_CXSCREEN) - width_) / 2;
top_ = (GetSystemMetrics(SM_CYSCREEN) - height_) / 2;
}
// Perform application initialization
browser_ = NULL;
handle_ = CreateWindowEx(WS_EX_APPWINDOW, szWindowClass,"", WS_THICKFRAME, top_, left_, width_, height_, NULL, NULL, hInstance, NULL);
if (!handle_) {
//TODO send error to node
fprintf(stderr,"Error occurred: ");
fprintf(stderr,"%d\n",GetLastError());
return;
}
SetWindowLongPtr(handle_,GWLP_USERDATA, (LONG)this);
if (alpha) {
SetBlur(true);
}
UpdateWindow(handle_);
Cef::Run();
};
int NativeWindow::ScreenWidth() {
return GetSystemMetrics(SM_CXSCREEN);
}
int NativeWindow::ScreenHeight() {
return GetSystemMetrics(SM_CYSCREEN);
}
void NativeWindow::Show() {
if (browser_) {
ShowWindow(handle_, SW_SHOW);
}
}
void NativeWindow::Hide() {
if (browser_) {
ShowWindow(handle_, SW_HIDE);
}
}
void NativeWindow::Destroy() {
if (browser_) {
CloseWindow(handle_);
}
}
void NativeWindow::Drag() {
if (handle_) {
ReleaseCapture();
SendMessage(handle_, WM_NCLBUTTONDOWN, HTCAPTION, 0);
}
}
void NativeWindow::SetPosition(int top, int left, int width, int height) {
if (handle_) {
UpdatePosition(top, left, width, height);
SetWindowPos(handle_, NULL, top, left, width, height, NULL);
}
}
void NativeWindow::SetPosition(int top, int left) {
if (handle_) {
top_ = top;
left_ = left;
SetWindowPos(handle_, NULL, top, left, NULL, NULL, SWP_NOSIZE);
}
}
void NativeWindow::SetSize(int width, int height) {
if (handle_) {
width_ = width;
height_ = height;
SetWindowPos(handle_, NULL, NULL, NULL, width, height, SWP_NOMOVE);
}
}
long NativeWindow::GetStyle() {
return GetWindowLong(handle_, GWL_STYLE);
}
long NativeWindow::GetExStyle() {
return GetWindowLong(handle_, GWL_EXSTYLE);
}
void NativeWindow::SetStyle(long style) {
UpdateStyle(handle_, GWL_STYLE, style);
}
void NativeWindow::SetExStyle(long style) {
UpdateStyle(handle_, GWL_EXSTYLE, style);
}
bool NativeWindow::GetBlur() {
return blur_;
}
void NativeWindow::SetBlur(bool blur){
blur_ = blur;
BlurBehind(handle_, blur);
}
void NativeWindow::UpdatePosition(){
RECT rect;
GetClientRect(handle_, &rect);
width_ = rect.right - rect.left;
height_ = rect.bottom - rect.top;
left_ = rect.left;
top_ = rect.top;
}
void NativeWindow::SetBorderWidth(int left, int right, int top, int bottom){
if (handle_) {
MARGINS margins = {left, right, top, bottom};
DwmExtendFrameIntoClientArea(handle_, &margins);
}
}
void NativeWindow::SetBorderWidth(int size){
if (handle_) {
MARGINS margins = {size, size, size, size};
DwmExtendFrameIntoClientArea(handle_, &margins);
}
}
ATOM MyRegisterClass(HINSTANCE hInst) {
WNDCLASSEX wcex = {0};
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInst;
wcex.hIcon = bigIcon;
wcex.hIconSm = smallIcon;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.lpszMenuName = NULL;
wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wcex.lpszClassName = szWindowClass;
return RegisterClassEx(&wcex);
}
// Processes messages for the main window.
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
// Callback for the main window
switch (message) {
case WM_CREATE: {
NativeWindow* window = ClientHandler::GetWindow(hwnd);
RECT rect;
GetClientRect(hwnd, &rect);
// Initialize window info to the defaults for a child window
Cef::AddWebView(hwnd, rect, url_, browserSettings);
return 0;
}
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc;
hdc = BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
return 0;
}
/*case WM_SETFOCUS:
if (g_handler.get() && g_handler->GetBrowserHwnd()) {
// Pass focus to the browser window
PostMessage(g_handler->GetBrowserHwnd(), WM_SETFOCUS, wParam, NULL);
}
return 0;*/
case WM_SIZE: {
NativeWindow* window = ClientHandler::GetWindow(hwnd);
if (window->GetBrowser()) {
RECT r;
GetClientRect(hwnd, &r);
HDWP hdwp = BeginDeferWindowPos(1);
hdwp = DeferWindowPos(hdwp, window->GetBrowser()->GetWindowHandle(), NULL, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER);
EndDeferWindowPos(hdwp);
}
break;
}
case WM_ERASEBKGND:
return 1;
// case WM_ERASEBKGND: {
// NativeWindow* window = ClientHandler::GetWindow(hwnd);
// if (window->GetBrowser()) {
// // Dont erase the background if the browser window has been loaded
// // (this avoids flashing)
// return 0;
// }
case WM_CLOSE: {
NativeWindow* window = ClientHandler::GetWindow(hwnd);
if (window->GetBrowser()) {
window->GetBrowser()->ParentWindowWillClose();
}
}
break;
//case WM_DESTROY:
// PostQuitMessage(0);
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
} /* appjs */
<|endoftext|> |
<commit_before>#ifndef INCLUDE_UNITTESTS_NORMAL_CALCULATIONS_HH
#define INCLUDE_UNITTESTS_NORMAL_CALCULATIONS_HH
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <iostream>
class OpenMeshNormals : public OpenMeshBase {
protected:
// This function is called before each test is run
virtual void SetUp() {
}
// This function is called after all tests are through
virtual void TearDown() {
// Do some final stuff with the member data here...
}
// Member already defined in OpenMeshBase
//Mesh mesh_;
};
/*
* ====================================================================
* Define tests below
* ====================================================================
*/
/*
* Collapsing a tetrahedron
*/
TEST_F(OpenMeshNormals, NormalCalculations) {
mesh_.clear();
// Add some vertices
Mesh::VertexHandle vhandle[4];
vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));
vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));
vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));
vhandle[3] = mesh_.add_vertex(Mesh::Point(0, 0, 1));
// Add four faces
std::vector<Mesh::VertexHandle> face_vhandles;
face_vhandles.push_back(vhandle[0]);
face_vhandles.push_back(vhandle[1]);
face_vhandles.push_back(vhandle[2]);
mesh_.add_face(face_vhandles);
face_vhandles.clear();
face_vhandles.push_back(vhandle[0]);
face_vhandles.push_back(vhandle[2]);
face_vhandles.push_back(vhandle[3]);
mesh_.add_face(face_vhandles);
face_vhandles.clear();
face_vhandles.push_back(vhandle[2]);
face_vhandles.push_back(vhandle[1]);
face_vhandles.push_back(vhandle[3]);
mesh_.add_face(face_vhandles);
face_vhandles.clear();
face_vhandles.push_back(vhandle[3]);
face_vhandles.push_back(vhandle[1]);
face_vhandles.push_back(vhandle[0]);
mesh_.add_face(face_vhandles);
// ===============================================
// Setup complete
// ===============================================
// Check one Request only vertex normals
// Face normals are required for vertex and halfedge normals, so
// This will compute no normals and is only a runtime check if the blocks
// that prevent access to non existing properties are in place
mesh_.request_vertex_normals();
mesh_.request_face_normals();
mesh_.request_halfedge_normals();
// Automatically compute all normals
// As only vertex normals are requested and no face normals, this will compute nothing.
mesh_.update_normals();
// Face normals alone
mesh_.update_face_normals();
// Vertex normals alone (require valid face normals)
mesh_.update_vertex_normals();
// Halfedge normals alone (require valid face normals)
mesh_.update_halfedge_normals();
}
#endif // INCLUDE GUARD
<commit_msg>Improved block checks<commit_after>#ifndef INCLUDE_UNITTESTS_NORMAL_CALCULATIONS_HH
#define INCLUDE_UNITTESTS_NORMAL_CALCULATIONS_HH
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <iostream>
class OpenMeshNormals : public OpenMeshBase {
protected:
// This function is called before each test is run
virtual void SetUp() {
}
// This function is called after all tests are through
virtual void TearDown() {
// Do some final stuff with the member data here...
}
// Member already defined in OpenMeshBase
//Mesh mesh_;
};
/*
* ====================================================================
* Define tests below
* ====================================================================
*/
/*
* Collapsing a tetrahedron
*/
TEST_F(OpenMeshNormals, NormalCalculations) {
mesh_.clear();
// Add some vertices
Mesh::VertexHandle vhandle[4];
vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0));
vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0));
vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0));
vhandle[3] = mesh_.add_vertex(Mesh::Point(0, 0, 1));
// Add four faces
std::vector<Mesh::VertexHandle> face_vhandles;
face_vhandles.push_back(vhandle[0]);
face_vhandles.push_back(vhandle[1]);
face_vhandles.push_back(vhandle[2]);
mesh_.add_face(face_vhandles);
face_vhandles.clear();
face_vhandles.push_back(vhandle[0]);
face_vhandles.push_back(vhandle[2]);
face_vhandles.push_back(vhandle[3]);
mesh_.add_face(face_vhandles);
face_vhandles.clear();
face_vhandles.push_back(vhandle[2]);
face_vhandles.push_back(vhandle[1]);
face_vhandles.push_back(vhandle[3]);
mesh_.add_face(face_vhandles);
face_vhandles.clear();
face_vhandles.push_back(vhandle[3]);
face_vhandles.push_back(vhandle[1]);
face_vhandles.push_back(vhandle[0]);
mesh_.add_face(face_vhandles);
// ===============================================
// Setup complete
// ===============================================
// Check one Request only vertex normals
// Face normals are required for vertex and halfedge normals, so
// that prevent access to non existing properties are in place
mesh_.request_vertex_normals();
mesh_.request_halfedge_normals();
// Check blocks
mesh_.update_normals();
// Request required face normals
mesh_.request_face_normals();
// Automatically compute all normals
// As only vertex normals are requested and no face normals, this will compute nothing.
mesh_.update_normals();
// Face normals alone
mesh_.update_face_normals();
// Vertex normals alone (require valid face normals)
mesh_.update_vertex_normals();
// Halfedge normals alone (require valid face normals)
mesh_.update_halfedge_normals();
}
#endif // INCLUDE GUARD
<|endoftext|> |
<commit_before>
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <sstream>
#include <stdexcept>
#include <torrentsync/dht/AddressData.h>
#include <test/torrentsync/dht/CommonAddressTest.h>
namespace
{
class AddressData_fix : public torrentsync::dht::AddressData
{
};
};
BOOST_FIXTURE_TEST_SUITE(torrentsync_dht_AddressData,AddressData_fix);
using namespace torrentsync::dht;
BOOST_AUTO_TEST_CASE(static_data_uppercase)
{
const std::string data = "FFFFFFFFFFFFFFFF0000000000000001AAAAAAAA";
BOOST_REQUIRE_NO_THROW(parse(data));
BOOST_REQUIRE_EQUAL(0xFFFFFFFFFFFFFFFF, p1);
BOOST_REQUIRE_EQUAL(0x0000000000000001, p2);
BOOST_REQUIRE_EQUAL(0xAAAAAAAA, p3);
BOOST_REQUIRE(boost::iequals(data,string()));
}
BOOST_AUTO_TEST_CASE(static_data_lowercase)
{
const std::string data = "ffffffffffffffff0000000000000001aaaaaaaa";
BOOST_REQUIRE_NO_THROW(parse(data));
BOOST_REQUIRE_EQUAL(0xFFFFFFFFFFFFFFFF, p1);
BOOST_REQUIRE_EQUAL(0x0000000000000001, p2);
BOOST_REQUIRE_EQUAL(0xAAAAAAAA, p3);
BOOST_REQUIRE(boost::iequals(data,string()));
}
BOOST_AUTO_TEST_CASE(static_data_mixedcase)
{
const std::string data = "fFFFffffffffFFFF0000000000000001aaAAAAAa";
BOOST_REQUIRE_NO_THROW(parse(data));
BOOST_REQUIRE_EQUAL(0xFFFFFFFFFFFFFFFF, p1);
BOOST_REQUIRE_EQUAL(0x0000000000000001, p2);
BOOST_REQUIRE_EQUAL(0xAAAAAAAA, p3);
BOOST_REQUIRE(boost::iequals(data,string()));
}
BOOST_AUTO_TEST_CASE(rand_data)
{
for (int i = 0; i < TEST_LOOP_COUNT; ++i )
{
const std::string data = generateRandomAddress();
BOOST_REQUIRE_NO_THROW(parse(data));
BOOST_REQUIRE(boost::iequals(data,string()));
}
}
BOOST_AUTO_TEST_CASE(too_short)
{
for ( int i = 0; i < TEST_LOOP_COUNT; ++i )
{
std::string s;
s.assign(rand()%40,'1');
BOOST_REQUIRE_THROW(parse(s), std::invalid_argument);
}
}
BOOST_AUTO_TEST_CASE(too_long)
{
for ( int i = 0; i < TEST_LOOP_COUNT; ++i )
{
std::string s;
s.assign(rand()%TEST_LOOP_COUNT+40+1,'1');
BOOST_REQUIRE_THROW(parse(s), std::invalid_argument);
}
}
BOOST_AUTO_TEST_CASE(comparing_fixed1)
{
AddressData a1("0F00000000000000000000000000000000000000");
AddressData a2("FF00000000000000000000000000000000000000");
AddressData a3("FFFF000000000000000000000000000000000000");
BOOST_REQUIRE_EQUAL(a2 > a1, true);
BOOST_REQUIRE_EQUAL(a2 >= a1, true);
BOOST_REQUIRE_EQUAL(a2 < a1, false);
BOOST_REQUIRE_EQUAL(a2 <= a1, false);
BOOST_REQUIRE_EQUAL(a2 == a1, false);
BOOST_REQUIRE_EQUAL(a3 > a2, true);
BOOST_REQUIRE_EQUAL(a3 >= a2, true);
BOOST_REQUIRE_EQUAL(a3 > a1, true);
BOOST_REQUIRE_EQUAL(a3 >= a1, true);
BOOST_REQUIRE_EQUAL(a3 < a2, false);
BOOST_REQUIRE_EQUAL(a3 <= a2, false);
BOOST_REQUIRE_EQUAL(a3 == a2, false);
BOOST_REQUIRE_EQUAL(a3 < a1, false);
BOOST_REQUIRE_EQUAL(a3 <= a1, false);
BOOST_REQUIRE_EQUAL(a3 == a1, false);
}
BOOST_AUTO_TEST_CASE(comparing_fixed2)
{
AddressData a1("0000000000000000000000000000000000000000");
AddressData a2("0000000000000000000F00000000000000000000");
AddressData a3("FFFF000000000000000000000000000000000000");
BOOST_REQUIRE_EQUAL(a2 > a1, true);
BOOST_REQUIRE_EQUAL(a2 >= a1, true);
BOOST_REQUIRE_EQUAL(a2 < a1, false);
BOOST_REQUIRE_EQUAL(a2 <= a1, false);
BOOST_REQUIRE_EQUAL(a2 == a1, false);
BOOST_REQUIRE_EQUAL(a3 > a2, true);
BOOST_REQUIRE_EQUAL(a3 >= a2, true);
BOOST_REQUIRE_EQUAL(a3 > a1, true);
BOOST_REQUIRE_EQUAL(a3 >= a1, true);
BOOST_REQUIRE_EQUAL(a3 < a2, false);
BOOST_REQUIRE_EQUAL(a3 <= a2, false);
BOOST_REQUIRE_EQUAL(a3 == a2, false);
BOOST_REQUIRE_EQUAL(a3 < a1, false);
BOOST_REQUIRE_EQUAL(a3 <= a1, false);
BOOST_REQUIRE_EQUAL(a3 == a1, false);
}
BOOST_AUTO_TEST_CASE(comparing_fixed3)
{
AddressData a1("000F000000000000000000000000000000000000");
AddressData a2("000F000000000000000F00000000000000000000");
AddressData a3("FFFF000000000000000000000000000000000000");
BOOST_REQUIRE_EQUAL(a2 > a1, true);
BOOST_REQUIRE_EQUAL(a2 >= a1, true);
BOOST_REQUIRE_EQUAL(a2 < a1, false);
BOOST_REQUIRE_EQUAL(a2 <= a1, false);
BOOST_REQUIRE_EQUAL(a2 == a1, false);
BOOST_REQUIRE_EQUAL(a3 > a2, true);
BOOST_REQUIRE_EQUAL(a3 >= a2, true);
BOOST_REQUIRE_EQUAL(a3 > a1, true);
BOOST_REQUIRE_EQUAL(a3 >= a1, true);
BOOST_REQUIRE_EQUAL(a3 < a2, false);
BOOST_REQUIRE_EQUAL(a3 <= a2, false);
BOOST_REQUIRE_EQUAL(a3 == a2, false);
BOOST_REQUIRE_EQUAL(a3 < a1, false);
BOOST_REQUIRE_EQUAL(a3 <= a1, false);
BOOST_REQUIRE_EQUAL(a3 == a1, false);
}
BOOST_AUTO_TEST_CASE(comparing_fixed4)
{
AddressData a1("000F000000000000000F00000000000000000000");
AddressData a2("000F000000000000000F00000000000000F00000");
AddressData a3("FFFF000000000000000000000000000000000000");
BOOST_REQUIRE_EQUAL(a2 > a1, true);
BOOST_REQUIRE_EQUAL(a2 >= a1, true);
BOOST_REQUIRE_EQUAL(a2 < a1, false);
BOOST_REQUIRE_EQUAL(a2 <= a1, false);
BOOST_REQUIRE_EQUAL(a2 == a1, false);
BOOST_REQUIRE_EQUAL(a3 > a2, true);
BOOST_REQUIRE_EQUAL(a3 >= a2, true);
BOOST_REQUIRE_EQUAL(a3 > a1, true);
BOOST_REQUIRE_EQUAL(a3 >= a1, true);
BOOST_REQUIRE_EQUAL(a3 < a2, false);
BOOST_REQUIRE_EQUAL(a3 <= a2, false);
BOOST_REQUIRE_EQUAL(a3 == a2, false);
BOOST_REQUIRE_EQUAL(a3 < a1, false);
BOOST_REQUIRE_EQUAL(a3 <= a1, false);
BOOST_REQUIRE_EQUAL(a3 == a1, false);
}
BOOST_AUTO_TEST_CASE(splitInHalf_ok)
{
AddressData low = AddressData::minValue;
AddressData high = AddressData::maxValue;
MaybeBounds bounds = AddressData::splitInHalf(low,high);
BOOST_REQUIRE(!!bounds);
BOOST_REQUIRE_LT(low,bounds->first);
BOOST_REQUIRE_LT(bounds->first,bounds->second);
BOOST_REQUIRE_LT(bounds->second,high);
BOOST_REQUIRE_EQUAL(bounds->first.string(),"7fffffffffffffffffffffffffffffffffffffff");
BOOST_REQUIRE_EQUAL(bounds->second.string(),"8000000000000000000000000000000000000000");
// sub bounds low-bounds.
MaybeBounds bounds_low = AddressData::splitInHalf(low,bounds->first);
BOOST_REQUIRE(!!bounds_low);
BOOST_REQUIRE_LT(low,bounds_low->first);
BOOST_REQUIRE_LT(bounds_low->first,bounds_low->second);
BOOST_REQUIRE_LT(bounds_low->second,bounds->first);
BOOST_REQUIRE_EQUAL(bounds_low->first.string(),"3fffffffffffffffffffffffffffffffffffffff");
BOOST_REQUIRE_EQUAL(bounds_low->second.string(),"4000000000000000000000000000000000000000");
// sub bounds high-bounds.
MaybeBounds bounds_high = AddressData::splitInHalf(bounds->second,high);
BOOST_REQUIRE(!!bounds_high);
BOOST_REQUIRE_LT(bounds->second,bounds_high->first);
BOOST_REQUIRE_LT(bounds_high->first,bounds_high->second);
BOOST_REQUIRE_LT(bounds_high->second,high);
BOOST_REQUIRE_EQUAL(bounds_high->first.string(),"bfffffffffffffffffffffffffffffffffffffff");
BOOST_REQUIRE_EQUAL(bounds_high->second.string(),"c000000000000000000000000000000000000000");
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Added bytestring test cases<commit_after>
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <sstream>
#include <stdexcept>
#include <torrentsync/dht/AddressData.h>
#include <test/torrentsync/dht/CommonAddressTest.h>
namespace
{
class AddressData_fix : public torrentsync::dht::AddressData
{
};
};
BOOST_FIXTURE_TEST_SUITE(torrentsync_dht_AddressData,AddressData_fix);
using namespace torrentsync::dht;
BOOST_AUTO_TEST_CASE(static_data_uppercase)
{
const std::string data = "FFFFFFFFFFFFFFFF0000000000000001AAAAAAAA";
BOOST_REQUIRE_NO_THROW(parse(data));
BOOST_REQUIRE_EQUAL(0xFFFFFFFFFFFFFFFF, p1);
BOOST_REQUIRE_EQUAL(0x0000000000000001, p2);
BOOST_REQUIRE_EQUAL(0xAAAAAAAA, p3);
BOOST_REQUIRE(boost::iequals(data,string()));
}
BOOST_AUTO_TEST_CASE(static_data_lowercase)
{
const std::string data = "ffffffffffffffff0000000000000001aaaaaaaa";
BOOST_REQUIRE_NO_THROW(parse(data));
BOOST_REQUIRE_EQUAL(0xFFFFFFFFFFFFFFFF, p1);
BOOST_REQUIRE_EQUAL(0x0000000000000001, p2);
BOOST_REQUIRE_EQUAL(0xAAAAAAAA, p3);
BOOST_REQUIRE(boost::iequals(data,string()));
}
BOOST_AUTO_TEST_CASE(static_data_mixedcase)
{
const std::string data = "fFFFffffffffFFFF0000000000000001aaAAAAAa";
BOOST_REQUIRE_NO_THROW(parse(data));
BOOST_REQUIRE_EQUAL(0xFFFFFFFFFFFFFFFF, p1);
BOOST_REQUIRE_EQUAL(0x0000000000000001, p2);
BOOST_REQUIRE_EQUAL(0xAAAAAAAA, p3);
BOOST_REQUIRE(boost::iequals(data,string()));
}
BOOST_AUTO_TEST_CASE(rand_data)
{
for (int i = 0; i < TEST_LOOP_COUNT; ++i )
{
const std::string data = generateRandomAddress();
BOOST_REQUIRE_NO_THROW(parse(data));
BOOST_REQUIRE(boost::iequals(data,string()));
}
}
BOOST_AUTO_TEST_CASE(too_short)
{
for ( int i = 0; i < TEST_LOOP_COUNT; ++i )
{
std::string s;
s.assign(rand()%40,'1');
BOOST_REQUIRE_THROW(parse(s), std::invalid_argument);
}
}
BOOST_AUTO_TEST_CASE(too_long)
{
for ( int i = 0; i < TEST_LOOP_COUNT; ++i )
{
std::string s;
s.assign(rand()%TEST_LOOP_COUNT+40+1,'1');
BOOST_REQUIRE_THROW(parse(s), std::invalid_argument);
}
}
BOOST_AUTO_TEST_CASE(comparing_fixed1)
{
AddressData a1("0F00000000000000000000000000000000000000");
AddressData a2("FF00000000000000000000000000000000000000");
AddressData a3("FFFF000000000000000000000000000000000000");
BOOST_REQUIRE_EQUAL(a2 > a1, true);
BOOST_REQUIRE_EQUAL(a2 >= a1, true);
BOOST_REQUIRE_EQUAL(a2 < a1, false);
BOOST_REQUIRE_EQUAL(a2 <= a1, false);
BOOST_REQUIRE_EQUAL(a2 == a1, false);
BOOST_REQUIRE_EQUAL(a3 > a2, true);
BOOST_REQUIRE_EQUAL(a3 >= a2, true);
BOOST_REQUIRE_EQUAL(a3 > a1, true);
BOOST_REQUIRE_EQUAL(a3 >= a1, true);
BOOST_REQUIRE_EQUAL(a3 < a2, false);
BOOST_REQUIRE_EQUAL(a3 <= a2, false);
BOOST_REQUIRE_EQUAL(a3 == a2, false);
BOOST_REQUIRE_EQUAL(a3 < a1, false);
BOOST_REQUIRE_EQUAL(a3 <= a1, false);
BOOST_REQUIRE_EQUAL(a3 == a1, false);
}
BOOST_AUTO_TEST_CASE(comparing_fixed2)
{
AddressData a1("0000000000000000000000000000000000000000");
AddressData a2("0000000000000000000F00000000000000000000");
AddressData a3("FFFF000000000000000000000000000000000000");
BOOST_REQUIRE_EQUAL(a2 > a1, true);
BOOST_REQUIRE_EQUAL(a2 >= a1, true);
BOOST_REQUIRE_EQUAL(a2 < a1, false);
BOOST_REQUIRE_EQUAL(a2 <= a1, false);
BOOST_REQUIRE_EQUAL(a2 == a1, false);
BOOST_REQUIRE_EQUAL(a3 > a2, true);
BOOST_REQUIRE_EQUAL(a3 >= a2, true);
BOOST_REQUIRE_EQUAL(a3 > a1, true);
BOOST_REQUIRE_EQUAL(a3 >= a1, true);
BOOST_REQUIRE_EQUAL(a3 < a2, false);
BOOST_REQUIRE_EQUAL(a3 <= a2, false);
BOOST_REQUIRE_EQUAL(a3 == a2, false);
BOOST_REQUIRE_EQUAL(a3 < a1, false);
BOOST_REQUIRE_EQUAL(a3 <= a1, false);
BOOST_REQUIRE_EQUAL(a3 == a1, false);
}
BOOST_AUTO_TEST_CASE(comparing_fixed3)
{
AddressData a1("000F000000000000000000000000000000000000");
AddressData a2("000F000000000000000F00000000000000000000");
AddressData a3("FFFF000000000000000000000000000000000000");
BOOST_REQUIRE_EQUAL(a2 > a1, true);
BOOST_REQUIRE_EQUAL(a2 >= a1, true);
BOOST_REQUIRE_EQUAL(a2 < a1, false);
BOOST_REQUIRE_EQUAL(a2 <= a1, false);
BOOST_REQUIRE_EQUAL(a2 == a1, false);
BOOST_REQUIRE_EQUAL(a3 > a2, true);
BOOST_REQUIRE_EQUAL(a3 >= a2, true);
BOOST_REQUIRE_EQUAL(a3 > a1, true);
BOOST_REQUIRE_EQUAL(a3 >= a1, true);
BOOST_REQUIRE_EQUAL(a3 < a2, false);
BOOST_REQUIRE_EQUAL(a3 <= a2, false);
BOOST_REQUIRE_EQUAL(a3 == a2, false);
BOOST_REQUIRE_EQUAL(a3 < a1, false);
BOOST_REQUIRE_EQUAL(a3 <= a1, false);
BOOST_REQUIRE_EQUAL(a3 == a1, false);
}
BOOST_AUTO_TEST_CASE(comparing_fixed4)
{
AddressData a1("000F000000000000000F00000000000000000000");
AddressData a2("000F000000000000000F00000000000000F00000");
AddressData a3("FFFF000000000000000000000000000000000000");
BOOST_REQUIRE_EQUAL(a2 > a1, true);
BOOST_REQUIRE_EQUAL(a2 >= a1, true);
BOOST_REQUIRE_EQUAL(a2 < a1, false);
BOOST_REQUIRE_EQUAL(a2 <= a1, false);
BOOST_REQUIRE_EQUAL(a2 == a1, false);
BOOST_REQUIRE_EQUAL(a3 > a2, true);
BOOST_REQUIRE_EQUAL(a3 >= a2, true);
BOOST_REQUIRE_EQUAL(a3 > a1, true);
BOOST_REQUIRE_EQUAL(a3 >= a1, true);
BOOST_REQUIRE_EQUAL(a3 < a2, false);
BOOST_REQUIRE_EQUAL(a3 <= a2, false);
BOOST_REQUIRE_EQUAL(a3 == a2, false);
BOOST_REQUIRE_EQUAL(a3 < a1, false);
BOOST_REQUIRE_EQUAL(a3 <= a1, false);
BOOST_REQUIRE_EQUAL(a3 == a1, false);
}
BOOST_AUTO_TEST_CASE(splitInHalf_ok)
{
AddressData low = AddressData::minValue;
AddressData high = AddressData::maxValue;
MaybeBounds bounds = AddressData::splitInHalf(low,high);
BOOST_REQUIRE(!!bounds);
BOOST_REQUIRE_LT(low,bounds->first);
BOOST_REQUIRE_LT(bounds->first,bounds->second);
BOOST_REQUIRE_LT(bounds->second,high);
BOOST_REQUIRE_EQUAL(bounds->first.string(),"7fffffffffffffffffffffffffffffffffffffff");
BOOST_REQUIRE_EQUAL(bounds->second.string(),"8000000000000000000000000000000000000000");
// sub bounds low-bounds.
MaybeBounds bounds_low = AddressData::splitInHalf(low,bounds->first);
BOOST_REQUIRE(!!bounds_low);
BOOST_REQUIRE_LT(low,bounds_low->first);
BOOST_REQUIRE_LT(bounds_low->first,bounds_low->second);
BOOST_REQUIRE_LT(bounds_low->second,bounds->first);
BOOST_REQUIRE_EQUAL(bounds_low->first.string(),"3fffffffffffffffffffffffffffffffffffffff");
BOOST_REQUIRE_EQUAL(bounds_low->second.string(),"4000000000000000000000000000000000000000");
// sub bounds high-bounds.
MaybeBounds bounds_high = AddressData::splitInHalf(bounds->second,high);
BOOST_REQUIRE(!!bounds_high);
BOOST_REQUIRE_LT(bounds->second,bounds_high->first);
BOOST_REQUIRE_LT(bounds_high->first,bounds_high->second);
BOOST_REQUIRE_LT(bounds_high->second,high);
BOOST_REQUIRE_EQUAL(bounds_high->first.string(),"bfffffffffffffffffffffffffffffffffffffff");
BOOST_REQUIRE_EQUAL(bounds_high->second.string(),"c000000000000000000000000000000000000000");
}
BOOST_AUTO_TEST_CASE(bytestring_parsing)
{
const std::string data = "1122334455667788aabbccddeeffgghhAABBCCDD";
BOOST_REQUIRE_NO_THROW(parseByteString(data));
BOOST_REQUIRE(boost::iequals(byteString(),data));
}
BOOST_AUTO_TEST_CASE(bytestring_parsing_special)
{
const std::string data = "1122334455667788\tabb\ncdde\0ffgghhAABBCCDD";
BOOST_REQUIRE_NO_THROW(parseByteString(data));
BOOST_REQUIRE(boost::iequals(byteString(),data));
}
BOOST_AUTO_TEST_CASE(bytestring_errors)
{
const std::string data = "112334455667788\tabb\ncdde\0ffgghhAABBCCDD";
BOOST_REQUIRE_THROW(parseByteString(data), std::illegal_argument);
const std::string data2 = "1122334455667788\tabb\ncdde\0ffgghhAABBCCDD1234567890";
BOOST_REQUIRE_THROW(parseByteString(data2), std::illegal_argument);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgrePage.h"
#include "OgreRoot.h"
#include "OgrePagedWorldSection.h"
#include "OgrePagedWorld.h"
#include "OgrePageStrategy.h"
#include "OgrePageManager.h"
#include "OgreSceneNode.h"
#include "OgreSceneManager.h"
#include "OgreStreamSerialiser.h"
#include "OgrePageContentCollectionFactory.h"
#include "OgrePageContentCollection.h"
namespace Ogre
{
//---------------------------------------------------------------------
const uint32 Page::CHUNK_ID = StreamSerialiser::makeIdentifier("PAGE");
const uint16 Page::CHUNK_VERSION = 1;
const uint32 Page::CHUNK_CONTENTCOLLECTION_DECLARATION_ID = StreamSerialiser::makeIdentifier("PCNT");
const uint16 Page::WORKQUEUE_PREPARE_REQUEST = 1;
const uint16 Page::WORKQUEUE_CHANGECOLLECTION_REQUEST = 3;
//---------------------------------------------------------------------
Page::Page(PageID pageID, PagedWorldSection* parent)
: mID(pageID)
, mParent(parent)
, mDeferredProcessInProgress(false)
, mModified(false)
, mDebugNode(0)
{
WorkQueue* wq = Root::getSingleton().getWorkQueue();
mWorkQueueChannel = wq->getChannel("Ogre/Page");
wq->addRequestHandler(mWorkQueueChannel, this);
wq->addResponseHandler(mWorkQueueChannel, this);
touch();
}
//---------------------------------------------------------------------
Page::~Page()
{
WorkQueue* wq = Root::getSingleton().getWorkQueue();
wq->removeRequestHandler(mWorkQueueChannel, this);
wq->removeResponseHandler(mWorkQueueChannel, this);
destroyAllContentCollections();
if (mDebugNode)
{
// destroy while we have the chance
SceneNode::ObjectIterator it = mDebugNode->getAttachedObjectIterator();
while(it.hasMoreElements())
mParent->getSceneManager()->destroyMovableObject(it.getNext());
mDebugNode->removeAndDestroyAllChildren();
mParent->getSceneManager()->destroySceneNode(mDebugNode);
mDebugNode = 0;
}
}
//---------------------------------------------------------------------
void Page::destroyAllContentCollections()
{
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
delete *i;
}
mContentCollections.clear();
}
//---------------------------------------------------------------------
PageManager* Page::getManager() const
{
return mParent->getManager();
}
//---------------------------------------------------------------------
void Page::touch()
{
mFrameLastHeld = Root::getSingleton().getNextFrameNumber() + 1;
}
//---------------------------------------------------------------------
bool Page::isHeld() const
{
unsigned long nextFrame = Root::getSingleton().getNextFrameNumber();
// 1-frame tolerance, since the next frame number varies depending which
// side of frameRenderingQueued you are
return (mFrameLastHeld == nextFrame ||
mFrameLastHeld + 1 == nextFrame);
}
//---------------------------------------------------------------------
bool Page::prepareImpl(StreamSerialiser& stream, PageData* dataToPopulate)
{
// Now do the real loading
if (!stream.readChunkBegin(CHUNK_ID, CHUNK_VERSION, "Page"))
return false;
// pageID check (we should know the ID we're expecting)
uint32 storedID;
stream.read(&storedID);
if (mID != storedID)
{
LogManager::getSingleton().stream() << "Error: Tried to populate Page ID " << mID
<< " with data corresponding to page ID " << storedID;
stream.undoReadChunk(CHUNK_ID);
return false;
}
PageManager* mgr = getManager();
while(stream.peekNextChunkID() == CHUNK_CONTENTCOLLECTION_DECLARATION_ID)
{
const StreamSerialiser::Chunk* collChunk = stream.readChunkBegin();
String factoryName;
stream.read(&factoryName);
stream.readChunkEnd(CHUNK_CONTENTCOLLECTION_DECLARATION_ID);
// Supported type?
PageContentCollectionFactory* collFact = mgr->getContentCollectionFactory(factoryName);
if (collFact)
{
PageContentCollection* collInst = collFact->createInstance();
if (collInst->prepare(stream)) // read type-specific data
{
dataToPopulate->collectionsToAdd.push_back(collInst);
}
else
{
LogManager::getSingleton().stream() << "Error preparing PageContentCollection type: "
<< factoryName << " in " << *this;
collFact->destroyInstance(collInst);
}
}
else
{
LogManager::getSingleton().stream() << "Unsupported PageContentCollection type: "
<< factoryName << " in " << *this;
// skip
stream.readChunkEnd(collChunk->id);
}
}
mModified = false;
return true;
}
//---------------------------------------------------------------------
void Page::load(bool synchronous)
{
if (!mDeferredProcessInProgress)
{
destroyAllContentCollections();
PageRequest req(this);
mDeferredProcessInProgress = true;
Root::getSingleton().getWorkQueue()->addRequest(mWorkQueueChannel, WORKQUEUE_PREPARE_REQUEST,
Any(req), 0, synchronous);
}
}
//---------------------------------------------------------------------
void Page::unload()
{
destroyAllContentCollections();
}
//---------------------------------------------------------------------
bool Page::canHandleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ)
{
PageRequest preq = any_cast<PageRequest>(req->getData());
// only deal with own requests
// we do this because if we delete a page we want any pending tasks to be discarded
if (preq.srcPage != this)
return false;
else
return true;
}
//---------------------------------------------------------------------
bool Page::canHandleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
{
PageRequest preq = any_cast<PageRequest>(res->getRequest()->getData());
// only deal with own requests
// we do this because if we delete a page we want any pending tasks to be discarded
if (preq.srcPage != this)
return false;
else
return true;
}
//---------------------------------------------------------------------
WorkQueue::Response* Page::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ)
{
// Background thread (maybe)
PageRequest preq = any_cast<PageRequest>(req->getData());
// only deal with own requests; we shouldn't ever get here though
if (preq.srcPage != this)
return 0;
PageResponse res;
res.pageData = OGRE_NEW PageData();
WorkQueue::Response* response = 0;
try
{
prepareImpl(res.pageData);
response = OGRE_NEW WorkQueue::Response(req, true, Any(res));
}
catch (Exception& e)
{
// oops
response = OGRE_NEW WorkQueue::Response(req, false, Any(res),
e.getFullDescription());
}
return response;
}
//---------------------------------------------------------------------
void Page::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
{
// Main thread
PageResponse pres = any_cast<PageResponse>(res->getData());
PageRequest preq = any_cast<PageRequest>(res->getRequest()->getData());
// only deal with own requests
if (preq.srcPage!= this)
return;
// final loading behaviour
if (res->succeeded())
{
std::swap(mContentCollections, pres.pageData->collectionsToAdd);
loadImpl();
}
OGRE_DELETE pres.pageData;
mDeferredProcessInProgress = false;
}
//---------------------------------------------------------------------
bool Page::prepareImpl(PageData* dataToPopulate)
{
// Background loading
String filename = generateFilename();
DataStreamPtr stream = Root::getSingleton().openFileStream(filename,
getManager()->getPageResourceGroup());
StreamSerialiser ser(stream);
return prepareImpl(ser, dataToPopulate);
}
//---------------------------------------------------------------------
void Page::loadImpl()
{
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
(*i)->load();
}
}
//---------------------------------------------------------------------
void Page::save()
{
String filename = generateFilename();
save(filename);
}
//---------------------------------------------------------------------
void Page::save(const String& filename)
{
DataStreamPtr stream = Root::getSingleton().createFileStream(filename,
getManager()->getPageResourceGroup(), true);
StreamSerialiser ser(stream);
save(ser);
}
//---------------------------------------------------------------------
void Page::save(StreamSerialiser& stream)
{
stream.writeChunkBegin(CHUNK_ID, CHUNK_VERSION);
// page id
stream.write(&mID);
// content collections
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
// declaration
stream.writeChunkBegin(CHUNK_CONTENTCOLLECTION_DECLARATION_ID);
stream.write(&(*i)->getType());
stream.writeChunkEnd(CHUNK_CONTENTCOLLECTION_DECLARATION_ID);
// data
(*i)->save(stream);
}
stream.writeChunkEnd(CHUNK_ID);
mModified = false;
}
//---------------------------------------------------------------------
void Page::frameStart(Real timeSinceLastFrame)
{
updateDebugDisplay();
// content collections
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
(*i)->frameStart(timeSinceLastFrame);
}
}
//---------------------------------------------------------------------
void Page::frameEnd(Real timeElapsed)
{
// content collections
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
(*i)->frameEnd(timeElapsed);
}
}
//---------------------------------------------------------------------
void Page::notifyCamera(Camera* cam)
{
// content collections
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
(*i)->notifyCamera(cam);
}
}
//---------------------------------------------------------------------
void Page::updateDebugDisplay()
{
uint8 dbglvl = getManager()->getDebugDisplayLevel();
if (dbglvl > 0)
{
// update debug display
if (!mDebugNode)
{
mDebugNode = mParent->getSceneManager()->getRootSceneNode()->createChildSceneNode();
}
mParent->getStrategy()->updateDebugDisplay(this, mDebugNode);
mDebugNode->setVisible(true);
}
else if (mDebugNode)
{
mDebugNode->setVisible(false);
}
}
//---------------------------------------------------------------------
PageContentCollection* Page::createContentCollection(const String& typeName)
{
PageContentCollection* coll = getManager()->createContentCollection(typeName);
coll->_notifyAttached(this);
mContentCollections.push_back(coll);
return coll;
}
//---------------------------------------------------------------------
void Page::destroyContentCollection(PageContentCollection* coll)
{
ContentCollectionList::iterator i = std::find(
mContentCollections.begin(), mContentCollections.end(), coll);
if (i != mContentCollections.end())
{
mContentCollections.erase(i);
}
getManager()->destroyContentCollection(coll);
}
//---------------------------------------------------------------------
size_t Page::getContentCollectionCount() const
{
return mContentCollections.size();
}
//---------------------------------------------------------------------
PageContentCollection* Page::getContentCollection(size_t index)
{
assert(index < mContentCollections.size());
return mContentCollections[index];
}
//---------------------------------------------------------------------
const Page::ContentCollectionList& Page::getContentCollectionList() const
{
return mContentCollections;
}
//---------------------------------------------------------------------
SceneManager* Page::getSceneManager() const
{
return mParent->getSceneManager();
}
//---------------------------------------------------------------------
std::ostream& operator <<( std::ostream& o, const Page& p )
{
o << "Page(ID:" << p.getID() << ", section:" << p.getParentSection()->getName()
<< ", world:" << p.getParentSection()->getWorld()->getName() << ")";
return o;
}
//---------------------------------------------------------------------
String Page::generateFilename() const
{
StringUtil::StrStreamType str;
if (mParent)
str << mParent->getWorld()->getName() << "_" << mParent->getName();
str << std::setw(8) << std::setfill('0') << std::hex << mID << ".page";
return str.str();
}
}
<commit_msg>Paging: make sure we give procedural generation a chance Also make hold tolerance more robust<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgrePage.h"
#include "OgreRoot.h"
#include "OgrePagedWorldSection.h"
#include "OgrePagedWorld.h"
#include "OgrePageStrategy.h"
#include "OgrePageManager.h"
#include "OgreSceneNode.h"
#include "OgreSceneManager.h"
#include "OgreStreamSerialiser.h"
#include "OgrePageContentCollectionFactory.h"
#include "OgrePageContentCollection.h"
namespace Ogre
{
//---------------------------------------------------------------------
const uint32 Page::CHUNK_ID = StreamSerialiser::makeIdentifier("PAGE");
const uint16 Page::CHUNK_VERSION = 1;
const uint32 Page::CHUNK_CONTENTCOLLECTION_DECLARATION_ID = StreamSerialiser::makeIdentifier("PCNT");
const uint16 Page::WORKQUEUE_PREPARE_REQUEST = 1;
const uint16 Page::WORKQUEUE_CHANGECOLLECTION_REQUEST = 3;
//---------------------------------------------------------------------
Page::Page(PageID pageID, PagedWorldSection* parent)
: mID(pageID)
, mParent(parent)
, mDeferredProcessInProgress(false)
, mModified(false)
, mDebugNode(0)
{
WorkQueue* wq = Root::getSingleton().getWorkQueue();
mWorkQueueChannel = wq->getChannel("Ogre/Page");
wq->addRequestHandler(mWorkQueueChannel, this);
wq->addResponseHandler(mWorkQueueChannel, this);
touch();
}
//---------------------------------------------------------------------
Page::~Page()
{
WorkQueue* wq = Root::getSingleton().getWorkQueue();
wq->removeRequestHandler(mWorkQueueChannel, this);
wq->removeResponseHandler(mWorkQueueChannel, this);
destroyAllContentCollections();
if (mDebugNode)
{
// destroy while we have the chance
SceneNode::ObjectIterator it = mDebugNode->getAttachedObjectIterator();
while(it.hasMoreElements())
mParent->getSceneManager()->destroyMovableObject(it.getNext());
mDebugNode->removeAndDestroyAllChildren();
mParent->getSceneManager()->destroySceneNode(mDebugNode);
mDebugNode = 0;
}
}
//---------------------------------------------------------------------
void Page::destroyAllContentCollections()
{
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
delete *i;
}
mContentCollections.clear();
}
//---------------------------------------------------------------------
PageManager* Page::getManager() const
{
return mParent->getManager();
}
//---------------------------------------------------------------------
void Page::touch()
{
mFrameLastHeld = Root::getSingleton().getNextFrameNumber();
}
//---------------------------------------------------------------------
bool Page::isHeld() const
{
unsigned long nextFrame = Root::getSingleton().getNextFrameNumber();
unsigned long dist;
if (nextFrame < mFrameLastHeld)
{
// we must have wrapped around
dist = mFrameLastHeld + (std::numeric_limits<unsigned long>::max() - mFrameLastHeld);
}
else
dist = nextFrame - mFrameLastHeld;
// 5-frame tolerance
return dist <= 5;
}
//---------------------------------------------------------------------
bool Page::prepareImpl(StreamSerialiser& stream, PageData* dataToPopulate)
{
// Now do the real loading
if (!stream.readChunkBegin(CHUNK_ID, CHUNK_VERSION, "Page"))
return false;
// pageID check (we should know the ID we're expecting)
uint32 storedID;
stream.read(&storedID);
if (mID != storedID)
{
LogManager::getSingleton().stream() << "Error: Tried to populate Page ID " << mID
<< " with data corresponding to page ID " << storedID;
stream.undoReadChunk(CHUNK_ID);
return false;
}
PageManager* mgr = getManager();
while(stream.peekNextChunkID() == CHUNK_CONTENTCOLLECTION_DECLARATION_ID)
{
const StreamSerialiser::Chunk* collChunk = stream.readChunkBegin();
String factoryName;
stream.read(&factoryName);
stream.readChunkEnd(CHUNK_CONTENTCOLLECTION_DECLARATION_ID);
// Supported type?
PageContentCollectionFactory* collFact = mgr->getContentCollectionFactory(factoryName);
if (collFact)
{
PageContentCollection* collInst = collFact->createInstance();
if (collInst->prepare(stream)) // read type-specific data
{
dataToPopulate->collectionsToAdd.push_back(collInst);
}
else
{
LogManager::getSingleton().stream() << "Error preparing PageContentCollection type: "
<< factoryName << " in " << *this;
collFact->destroyInstance(collInst);
}
}
else
{
LogManager::getSingleton().stream() << "Unsupported PageContentCollection type: "
<< factoryName << " in " << *this;
// skip
stream.readChunkEnd(collChunk->id);
}
}
mModified = false;
return true;
}
//---------------------------------------------------------------------
void Page::load(bool synchronous)
{
if (!mDeferredProcessInProgress)
{
destroyAllContentCollections();
PageRequest req(this);
mDeferredProcessInProgress = true;
Root::getSingleton().getWorkQueue()->addRequest(mWorkQueueChannel, WORKQUEUE_PREPARE_REQUEST,
Any(req), 0, synchronous);
}
}
//---------------------------------------------------------------------
void Page::unload()
{
destroyAllContentCollections();
}
//---------------------------------------------------------------------
bool Page::canHandleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ)
{
PageRequest preq = any_cast<PageRequest>(req->getData());
// only deal with own requests
// we do this because if we delete a page we want any pending tasks to be discarded
if (preq.srcPage != this)
return false;
else
return true;
}
//---------------------------------------------------------------------
bool Page::canHandleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
{
PageRequest preq = any_cast<PageRequest>(res->getRequest()->getData());
// only deal with own requests
// we do this because if we delete a page we want any pending tasks to be discarded
if (preq.srcPage != this)
return false;
else
return true;
}
//---------------------------------------------------------------------
WorkQueue::Response* Page::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ)
{
// Background thread (maybe)
PageRequest preq = any_cast<PageRequest>(req->getData());
// only deal with own requests; we shouldn't ever get here though
if (preq.srcPage != this)
return 0;
PageResponse res;
res.pageData = OGRE_NEW PageData();
WorkQueue::Response* response = 0;
try
{
prepareImpl(res.pageData);
response = OGRE_NEW WorkQueue::Response(req, true, Any(res));
}
catch (Exception& e)
{
// oops
response = OGRE_NEW WorkQueue::Response(req, false, Any(res),
e.getFullDescription());
}
return response;
}
//---------------------------------------------------------------------
void Page::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
{
// Main thread
PageResponse pres = any_cast<PageResponse>(res->getData());
PageRequest preq = any_cast<PageRequest>(res->getRequest()->getData());
// only deal with own requests
if (preq.srcPage!= this)
return;
// final loading behaviour
if (res->succeeded())
{
std::swap(mContentCollections, pres.pageData->collectionsToAdd);
loadImpl();
}
OGRE_DELETE pres.pageData;
mDeferredProcessInProgress = false;
}
//---------------------------------------------------------------------
bool Page::prepareImpl(PageData* dataToPopulate)
{
// Procedural preparation
if (mParent->_prepareProceduralPage(this))
return true;
else
{
// Background loading
String filename = generateFilename();
DataStreamPtr stream = Root::getSingleton().openFileStream(filename,
getManager()->getPageResourceGroup());
StreamSerialiser ser(stream);
return prepareImpl(ser, dataToPopulate);
}
}
//---------------------------------------------------------------------
void Page::loadImpl()
{
mParent->_loadProceduralPage(this);
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
(*i)->load();
}
}
//---------------------------------------------------------------------
void Page::save()
{
String filename = generateFilename();
save(filename);
}
//---------------------------------------------------------------------
void Page::save(const String& filename)
{
DataStreamPtr stream = Root::getSingleton().createFileStream(filename,
getManager()->getPageResourceGroup(), true);
StreamSerialiser ser(stream);
save(ser);
}
//---------------------------------------------------------------------
void Page::save(StreamSerialiser& stream)
{
stream.writeChunkBegin(CHUNK_ID, CHUNK_VERSION);
// page id
stream.write(&mID);
// content collections
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
// declaration
stream.writeChunkBegin(CHUNK_CONTENTCOLLECTION_DECLARATION_ID);
stream.write(&(*i)->getType());
stream.writeChunkEnd(CHUNK_CONTENTCOLLECTION_DECLARATION_ID);
// data
(*i)->save(stream);
}
stream.writeChunkEnd(CHUNK_ID);
mModified = false;
}
//---------------------------------------------------------------------
void Page::frameStart(Real timeSinceLastFrame)
{
updateDebugDisplay();
// content collections
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
(*i)->frameStart(timeSinceLastFrame);
}
}
//---------------------------------------------------------------------
void Page::frameEnd(Real timeElapsed)
{
// content collections
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
(*i)->frameEnd(timeElapsed);
}
}
//---------------------------------------------------------------------
void Page::notifyCamera(Camera* cam)
{
// content collections
for (ContentCollectionList::iterator i = mContentCollections.begin();
i != mContentCollections.end(); ++i)
{
(*i)->notifyCamera(cam);
}
}
//---------------------------------------------------------------------
void Page::updateDebugDisplay()
{
uint8 dbglvl = getManager()->getDebugDisplayLevel();
if (dbglvl > 0)
{
// update debug display
if (!mDebugNode)
{
mDebugNode = mParent->getSceneManager()->getRootSceneNode()->createChildSceneNode();
}
mParent->getStrategy()->updateDebugDisplay(this, mDebugNode);
mDebugNode->setVisible(true);
}
else if (mDebugNode)
{
mDebugNode->setVisible(false);
}
}
//---------------------------------------------------------------------
PageContentCollection* Page::createContentCollection(const String& typeName)
{
PageContentCollection* coll = getManager()->createContentCollection(typeName);
coll->_notifyAttached(this);
mContentCollections.push_back(coll);
return coll;
}
//---------------------------------------------------------------------
void Page::destroyContentCollection(PageContentCollection* coll)
{
ContentCollectionList::iterator i = std::find(
mContentCollections.begin(), mContentCollections.end(), coll);
if (i != mContentCollections.end())
{
mContentCollections.erase(i);
}
getManager()->destroyContentCollection(coll);
}
//---------------------------------------------------------------------
size_t Page::getContentCollectionCount() const
{
return mContentCollections.size();
}
//---------------------------------------------------------------------
PageContentCollection* Page::getContentCollection(size_t index)
{
assert(index < mContentCollections.size());
return mContentCollections[index];
}
//---------------------------------------------------------------------
const Page::ContentCollectionList& Page::getContentCollectionList() const
{
return mContentCollections;
}
//---------------------------------------------------------------------
SceneManager* Page::getSceneManager() const
{
return mParent->getSceneManager();
}
//---------------------------------------------------------------------
std::ostream& operator <<( std::ostream& o, const Page& p )
{
o << "Page(ID:" << p.getID() << ", section:" << p.getParentSection()->getName()
<< ", world:" << p.getParentSection()->getWorld()->getName() << ")";
return o;
}
//---------------------------------------------------------------------
String Page::generateFilename() const
{
StringUtil::StrStreamType str;
if (mParent)
str << mParent->getWorld()->getName() << "_" << mParent->getName();
str << std::setw(8) << std::setfill('0') << std::hex << mID << ".page";
return str.str();
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylandwindow.h"
#include "qwaylandbuffer.h"
#include "qwaylanddisplay.h"
#include "qwaylandinputdevice.h"
#include "qwaylandscreen.h"
#include "qwaylandshell.h"
#include "qwaylandshellsurface.h"
#include <QtGui/QWindow>
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif
#include "qwaylandextendedsurface.h"
#include "qwaylandsubsurface.h"
#include <QCoreApplication>
#include <QtGui/QWindowSystemInterface>
QWaylandWindow::QWaylandWindow(QWindow *window)
: QPlatformWindow(window)
, mDisplay(QWaylandScreen::waylandScreenFromWindow(window)->display())
, mSurface(mDisplay->createSurface(this))
, mShellSurface(mDisplay->shell()->createShellSurface(this))
, mExtendedWindow(0)
, mSubSurfaceWindow(0)
, mBuffer(0)
, mWaitingForFrameSync(false)
, mFrameCallback(0)
{
static WId id = 1;
mWindowId = id++;
if (mDisplay->windowExtension())
mExtendedWindow = mDisplay->windowExtension()->getExtendedWindow(this);
if (mDisplay->subSurfaceExtension())
mSubSurfaceWindow = mDisplay->subSurfaceExtension()->getSubSurfaceAwareWindow(this);
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
mDisplay->windowManagerIntegration()->mapClientToProcess(qApp->applicationPid());
mDisplay->windowManagerIntegration()->authenticateWithToken();
#endif
if (parent() && mSubSurfaceWindow) {
mSubSurfaceWindow->setParent(static_cast<const QWaylandWindow *>(parent()));
} else {
wl_shell_surface_set_toplevel(mShellSurface->handle());
}
}
QWaylandWindow::~QWaylandWindow()
{
if (mSurface) {
delete mShellSurface;
delete mExtendedWindow;
wl_surface_destroy(mSurface);
}
QList<QWaylandInputDevice *> inputDevices = mDisplay->inputDevices();
for (int i = 0; i < inputDevices.size(); ++i)
inputDevices.at(i)->handleWindowDestroyed(this);
}
WId QWaylandWindow::winId() const
{
return mWindowId;
}
void QWaylandWindow::setParent(const QPlatformWindow *parent)
{
const QWaylandWindow *parentWaylandWindow = static_cast<const QWaylandWindow *>(parent);
if (subSurfaceWindow()) {
subSurfaceWindow()->setParent(parentWaylandWindow);
}
}
void QWaylandWindow::setVisible(bool visible)
{
if (visible) {
if (mBuffer) {
wl_surface_attach(mSurface, mBuffer->buffer(),0,0);
QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
}
}
}
void QWaylandWindow::configure(uint32_t time, uint32_t edges,
int32_t x, int32_t y,
int32_t width, int32_t height)
{
Q_UNUSED(time);
Q_UNUSED(edges);
QRect geometry = QRect(x, y, width, height);
setGeometry(geometry);
QWindowSystemInterface::handleGeometryChange(window(), geometry);
}
void QWaylandWindow::attach(QWaylandBuffer *buffer)
{
mBuffer = buffer;
if (window()->visible()) {
wl_surface_attach(mSurface, mBuffer->buffer(),0,0);
if (buffer)
QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
}
}
void QWaylandWindow::damage(const QRect &rect)
{
//We have to do sync stuff before calling damage, or we might
//get a frame callback before we get the timestamp
if (!mWaitingForFrameSync) {
mFrameCallback = wl_surface_frame(mSurface);
wl_callback_add_listener(mFrameCallback,&QWaylandWindow::callbackListener,this);
mWaitingForFrameSync = true;
}
wl_surface_damage(mSurface,
rect.x(), rect.y(), rect.width(), rect.height());
}
const wl_callback_listener QWaylandWindow::callbackListener = {
QWaylandWindow::frameCallback
};
void QWaylandWindow::frameCallback(void *data, struct wl_callback *wl_callback, uint32_t time)
{
Q_UNUSED(time);
Q_UNUSED(wl_callback);
QWaylandWindow *self = static_cast<QWaylandWindow*>(data);
self->mWaitingForFrameSync = false;
if (self->mFrameCallback) {
wl_callback_destroy(self->mFrameCallback);
self->mFrameCallback = 0;
}
}
void QWaylandWindow::waitForFrameSync()
{
mDisplay->flushRequests();
while (mWaitingForFrameSync)
mDisplay->blockingReadEvents();
}
QWaylandShellSurface *QWaylandWindow::shellSurface() const
{
return mShellSurface;
}
QWaylandExtendedSurface *QWaylandWindow::extendedWindow() const
{
return mExtendedWindow;
}
QWaylandSubSurface *QWaylandWindow::subSurfaceWindow() const
{
return mSubSurfaceWindow;
}
<commit_msg>Revert "Do not attach null buffer."<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylandwindow.h"
#include "qwaylandbuffer.h"
#include "qwaylanddisplay.h"
#include "qwaylandinputdevice.h"
#include "qwaylandscreen.h"
#include "qwaylandshell.h"
#include "qwaylandshellsurface.h"
#include <QtGui/QWindow>
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "windowmanager_integration/qwaylandwindowmanagerintegration.h"
#endif
#include "qwaylandextendedsurface.h"
#include "qwaylandsubsurface.h"
#include <QCoreApplication>
#include <QtGui/QWindowSystemInterface>
QWaylandWindow::QWaylandWindow(QWindow *window)
: QPlatformWindow(window)
, mDisplay(QWaylandScreen::waylandScreenFromWindow(window)->display())
, mSurface(mDisplay->createSurface(this))
, mShellSurface(mDisplay->shell()->createShellSurface(this))
, mExtendedWindow(0)
, mSubSurfaceWindow(0)
, mBuffer(0)
, mWaitingForFrameSync(false)
, mFrameCallback(0)
{
static WId id = 1;
mWindowId = id++;
if (mDisplay->windowExtension())
mExtendedWindow = mDisplay->windowExtension()->getExtendedWindow(this);
if (mDisplay->subSurfaceExtension())
mSubSurfaceWindow = mDisplay->subSurfaceExtension()->getSubSurfaceAwareWindow(this);
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
mDisplay->windowManagerIntegration()->mapClientToProcess(qApp->applicationPid());
mDisplay->windowManagerIntegration()->authenticateWithToken();
#endif
if (parent() && mSubSurfaceWindow) {
mSubSurfaceWindow->setParent(static_cast<const QWaylandWindow *>(parent()));
} else {
wl_shell_surface_set_toplevel(mShellSurface->handle());
}
}
QWaylandWindow::~QWaylandWindow()
{
if (mSurface) {
delete mShellSurface;
delete mExtendedWindow;
wl_surface_destroy(mSurface);
}
QList<QWaylandInputDevice *> inputDevices = mDisplay->inputDevices();
for (int i = 0; i < inputDevices.size(); ++i)
inputDevices.at(i)->handleWindowDestroyed(this);
}
WId QWaylandWindow::winId() const
{
return mWindowId;
}
void QWaylandWindow::setParent(const QPlatformWindow *parent)
{
const QWaylandWindow *parentWaylandWindow = static_cast<const QWaylandWindow *>(parent);
if (subSurfaceWindow()) {
subSurfaceWindow()->setParent(parentWaylandWindow);
}
}
void QWaylandWindow::setVisible(bool visible)
{
if (visible) {
if (mBuffer) {
wl_surface_attach(mSurface, mBuffer->buffer(),0,0);
QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
}
} else {
wl_surface_attach(mSurface, 0,0,0);
}
}
void QWaylandWindow::configure(uint32_t time, uint32_t edges,
int32_t x, int32_t y,
int32_t width, int32_t height)
{
Q_UNUSED(time);
Q_UNUSED(edges);
QRect geometry = QRect(x, y, width, height);
setGeometry(geometry);
QWindowSystemInterface::handleGeometryChange(window(), geometry);
}
void QWaylandWindow::attach(QWaylandBuffer *buffer)
{
mBuffer = buffer;
if (window()->visible()) {
wl_surface_attach(mSurface, mBuffer->buffer(),0,0);
if (buffer)
QWindowSystemInterface::handleSynchronousExposeEvent(window(), QRect(QPoint(), geometry().size()));
}
}
void QWaylandWindow::damage(const QRect &rect)
{
//We have to do sync stuff before calling damage, or we might
//get a frame callback before we get the timestamp
if (!mWaitingForFrameSync) {
mFrameCallback = wl_surface_frame(mSurface);
wl_callback_add_listener(mFrameCallback,&QWaylandWindow::callbackListener,this);
mWaitingForFrameSync = true;
}
wl_surface_damage(mSurface,
rect.x(), rect.y(), rect.width(), rect.height());
}
const wl_callback_listener QWaylandWindow::callbackListener = {
QWaylandWindow::frameCallback
};
void QWaylandWindow::frameCallback(void *data, struct wl_callback *wl_callback, uint32_t time)
{
Q_UNUSED(time);
Q_UNUSED(wl_callback);
QWaylandWindow *self = static_cast<QWaylandWindow*>(data);
self->mWaitingForFrameSync = false;
if (self->mFrameCallback) {
wl_callback_destroy(self->mFrameCallback);
self->mFrameCallback = 0;
}
}
void QWaylandWindow::waitForFrameSync()
{
mDisplay->flushRequests();
while (mWaitingForFrameSync)
mDisplay->blockingReadEvents();
}
QWaylandShellSurface *QWaylandWindow::shellSurface() const
{
return mShellSurface;
}
QWaylandExtendedSurface *QWaylandWindow::extendedWindow() const
{
return mExtendedWindow;
}
QWaylandSubSurface *QWaylandWindow::subSurfaceWindow() const
{
return mSubSurfaceWindow;
}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2013, Stuart W Baker
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file Serial.cxx
* This file implements a generic serial device driver layer.
*
* @author Stuart W. Baker
* @date 3 January 2013
*/
#include <cstdint>
#include <fcntl.h>
#include "Devtab.hxx"
#include "Serial.hxx"
#include "can_ioctl.h"
void Serial::flush_buffers()
{
int result;
do
{
unsigned char data;
result = os_mq_timedreceive(txQ, &data, 0);
} while (result == OS_MQ_NONE);
do
{
unsigned char data;
result = os_mq_timedreceive(rxQ, &data, 0);
} while (result == OS_MQ_NONE);
}
/** Read from a file or device.
* @param file file reference for this device
* @param buf location to place read data
* @param count number of bytes to read
* @return number of bytes read upon success, -1 upon failure with errno containing the cause
*/
ssize_t Serial::read(File *file, void *buf, size_t count)
{
unsigned char *data = (unsigned char*)buf;
ssize_t result = 0;
while (count)
{
if (os_mq_timedreceive(rxQ, data, 0) == OS_MQ_TIMEDOUT)
{
/* no more data to receive */
if ((file->flags & O_NONBLOCK) ||
result > 0)
{
break;
}
else
{
/* wait for data to come in */
os_mq_receive(rxQ, data);
}
}
count--;
result++;
data++;
}
return result;
}
/** Write to a file or device.
* @param file file reference for this device
* @param buf location to find write data
* @param count number of bytes to write
* @return number of bytes written upon success, -1 upon failure with errno containing the cause
*/
ssize_t Serial::write(File *file, const void *buf, size_t count)
{
const unsigned char *data = (const unsigned char*)buf;
ssize_t result = 0;
while (count)
{
if (file->flags & O_NONBLOCK)
{
if (os_mq_timedsend(txQ, data, 0) == OS_MQ_TIMEDOUT)
{
/* no more room in the buffer */
break;
}
}
else
{
/* wait for room in the queue */
os_mq_send(txQ, data);
}
lock_.lock();
tx_char();
lock_.unlock();
count--;
result++;
data++;
}
return result;
}
/** Request an ioctl transaction
* @param file file reference for this device
* @param node node reference for this device
* @param key ioctl key
* @param data key data
*/
int Serial::ioctl(File *file, unsigned long int key, unsigned long data)
{
return -1;
}
/** Device select method. Default impementation returns true.
* @param file reference to the file
* @param mode FREAD for read active, FWRITE for write active, 0 for
* exceptions
* @return true if active, false if inactive
*/
bool Serial::select(File* file, int mode)
{
switch (mode)
{
case FREAD:
if (os_mq_num_pending(rxQ) > 0)
{
return true;
}
select_insert(&selInfoRd);
break;
case FWRITE:
if (os_mq_num_spaces(txQ) > 0)
{
return true;
}
select_insert(&selInfoWr);
break;
default:
case 0:
/* we don't support any exceptions */
break;
}
return false;
}
ssize_t USBSerialNode::read(File *file, void *buf, size_t count)
{
if (!count) return 0;
auto h = rxBlock_.holder();
ssize_t ret = 0;
uint8_t *dst = static_cast<uint8_t *>(buf);
while (true)
{
bool pass_on_notify = false;
// Checks if we have some RX job to do.
{
auto hh = h.critical();
if ((rxQBegin_ >= rxQEnd_) && (rxPending_))
{
rxQBegin_ = 0;
rxQEnd_ = rx_packet_irqlocked(rxQ_);
rxPending_ = 0;
}
// Tries to copy data from the buffer.
while (rxQBegin_ < rxQEnd_ && ret < (ssize_t)count)
{
*dst++ = rxQ_[rxQBegin_++];
++ret;
}
if (rxQBegin_ < rxQEnd_)
{
pass_on_notify = true;
}
}
if (pass_on_notify)
{
// We have a partial read. Wake up someone else trying to read.
h.notify_next();
// We lost the lock at notify_next, so we return immediately.
return ret;
}
if (ret > 0 || file->flags & O_NONBLOCK)
{
return ret;
}
// No data received now, and no data in the queue. Blocks the current
// thread and tries the whole dance again.
h.wait_for_notification();
}
}
ssize_t USBSerialNode::write(File *file, const void *buf, size_t count)
{
if (!count) return 0;
const uint8_t *data = static_cast<const uint8_t*>(buf);
ssize_t ret = 0;
auto h = txBlock_.holder();
bool pass_on_notify = false;
while (count)
{
{
auto hh = h.critical();
while (has_tx_buffer_free() && count)
{
add_to_tx_buffer(*data++);
--count;
++ret;
}
if (has_tx_buffer_free()) pass_on_notify = true;
if (!txPending_)
{
if (tx_packet_irqlocked(txQ_, txQEnd_))
{
mark_tx_buffer_sent();
txPending_ = 1;
} else {
// packet send failed -- we'll re-try in a next iteration
pass_on_notify = true;
}
}
}
if (file->flags & O_NONBLOCK) {
break;
}
if (count && !pass_on_notify)
{
h.wait_for_notification();
}
}
if (pass_on_notify)
{
h.notify_next();
// must not use locked fields after this
return ret;
}
return ret;
}
int USBSerialNode::ioctl(File *file, unsigned long int key, unsigned long data)
{
/* sanity check to be sure we have a valid key for this device */
HASSERT(IOC_TYPE(key) == CAN_IOC_MAGIC);
// Will be called at the end if non-null.
Notifiable *n = nullptr;
if (IOC_SIZE(key) == NOTIFIABLE_TYPE)
{
n = reinterpret_cast<Notifiable *>(data);
}
switch (key)
{
default:
return -EINVAL;
case CAN_IOC_READ_ACTIVE:
{
auto h = rxBlock_.holder();
auto hh = h.critical();
if (rxQBegin_ >= rxQEnd_) {
n = rxBlock_.register_notifiable(n);
log_.log(0xC8);
} else {
log_.log(0xC8);
}
break;
}
case CAN_IOC_WRITE_ACTIVE:
{
auto h = txBlock_.holder();
auto hh = h.critical();
if (!has_tx_buffer_free()) {
n = txBlock_.register_notifiable(n);
log_.log(0xCA);
} else {
log_.log(0xCB);
}
break;
}
}
if (n)
n->notify();
return 0;
}
/** Device select method. Default impementation returns true.
* @param file reference to the file
* @param mode FREAD for read active, FWRITE for write active, 0 for
* exceptions
* @return true if active, false if inactive
*/
bool USBSerialNode::select(File* file, int mode)
{
#if 0
switch (mode)
{
case FREAD:
if (os_mq_num_pending(rxQ) > 0)
{
return true;
}
select_insert(&selInfoRd);
break;
case FWRITE:
if (has_tx_buffer_free())
{
return true;
}
select_insert(&selInfoWr);
break;
default:
case 0:
/* we don't support any exceptions */
break;
}
#endif
return false;
}
void USBSerialNode::flush_buffers() OVERRIDE {
{
auto h = txBlock_.holder();
// Since this was called after disable() we don't need the critical
// section anymore.
txQEnd_ = 0;
txPending_ = 0; // is this dangerous?
}
{
auto h = rxBlock_.holder();
rxQBegin_ = rxQEnd_ = 0;
if (rxPending_) {
rx_packet_irqlocked(rxQ_);
rxPending_ = 0;
}
}
}
void USBSerialNode::tx_finished_from_isr()
{
if (txQEnd_) {
if (tx_packet_from_isr(txQ_, txQEnd_))
{
txQEnd_ = 0;
txPending_ = 1;
}
else
{
// We failed ot send the next packet. We'll wake up a writer
// (hopefully) that will re-try sending the packet. However, it is
// possible that there is no writer thread around and there will be
// data stuck in the queue here.
txPending_ = 0;
}
}
else
{
txPending_ = 0;
log_.log(0x20);
}
txBlock_.notify_from_isr();
}
void *USBSerialNode::try_read_packet_from_isr()
{
if (rxQBegin_ >= rxQEnd_)
{
rxQBegin_ = rxQEnd_ = 0;
}
if (static_cast<size_t>(rxQEnd_) + USB_SERIAL_PACKET_SIZE <= sizeof(rxQ_))
{
return &rxQ_[rxQEnd_];
}
else
{
return nullptr;
}
}
void USBSerialNode::set_rx_finished_from_isr(uint8_t size)
{
rxQEnd_ += size;
rxBlock_.notify_from_isr();
}
<commit_msg>Fix race condition<commit_after>/** \copyright
* Copyright (c) 2013, Stuart W Baker
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file Serial.cxx
* This file implements a generic serial device driver layer.
*
* @author Stuart W. Baker
* @date 3 January 2013
*/
#include <cstdint>
#include <fcntl.h>
#include "Devtab.hxx"
#include "Serial.hxx"
#include "can_ioctl.h"
void Serial::flush_buffers()
{
int result;
do
{
unsigned char data;
result = os_mq_timedreceive(txQ, &data, 0);
} while (result == OS_MQ_NONE);
do
{
unsigned char data;
result = os_mq_timedreceive(rxQ, &data, 0);
} while (result == OS_MQ_NONE);
}
/** Read from a file or device.
* @param file file reference for this device
* @param buf location to place read data
* @param count number of bytes to read
* @return number of bytes read upon success, -1 upon failure with errno containing the cause
*/
ssize_t Serial::read(File *file, void *buf, size_t count)
{
unsigned char *data = (unsigned char*)buf;
ssize_t result = 0;
while (count)
{
if (os_mq_timedreceive(rxQ, data, 0) == OS_MQ_TIMEDOUT)
{
/* no more data to receive */
if ((file->flags & O_NONBLOCK) ||
result > 0)
{
break;
}
else
{
/* wait for data to come in */
os_mq_receive(rxQ, data);
}
}
count--;
result++;
data++;
}
return result;
}
/** Write to a file or device.
* @param file file reference for this device
* @param buf location to find write data
* @param count number of bytes to write
* @return number of bytes written upon success, -1 upon failure with errno containing the cause
*/
ssize_t Serial::write(File *file, const void *buf, size_t count)
{
const unsigned char *data = (const unsigned char*)buf;
ssize_t result = 0;
while (count)
{
if (file->flags & O_NONBLOCK)
{
if (os_mq_timedsend(txQ, data, 0) == OS_MQ_TIMEDOUT)
{
/* no more room in the buffer */
break;
}
}
else
{
/* wait for room in the queue */
os_mq_send(txQ, data);
}
lock_.lock();
tx_char();
lock_.unlock();
count--;
result++;
data++;
}
return result;
}
/** Request an ioctl transaction
* @param file file reference for this device
* @param node node reference for this device
* @param key ioctl key
* @param data key data
*/
int Serial::ioctl(File *file, unsigned long int key, unsigned long data)
{
return -1;
}
/** Device select method. Default impementation returns true.
* @param file reference to the file
* @param mode FREAD for read active, FWRITE for write active, 0 for
* exceptions
* @return true if active, false if inactive
*/
bool Serial::select(File* file, int mode)
{
bool retval = false;
switch (mode)
{
case FREAD:
portENTER_CRITICAL();
if (os_mq_num_pending(rxQ) > 0)
{
retval = true;
}
else
{
select_insert(&selInfoRd);
}
portEXIT_CRITICAL();
break;
case FWRITE:
portENTER_CRITICAL();
if (os_mq_num_spaces(txQ) > 0)
{
retval = true;
}
else
{
select_insert(&selInfoWr);
}
portEXIT_CRITICAL();
break;
default:
case 0:
/* we don't support any exceptions */
break;
}
return retval;
}
ssize_t USBSerialNode::read(File *file, void *buf, size_t count)
{
if (!count) return 0;
auto h = rxBlock_.holder();
ssize_t ret = 0;
uint8_t *dst = static_cast<uint8_t *>(buf);
while (true)
{
bool pass_on_notify = false;
// Checks if we have some RX job to do.
{
auto hh = h.critical();
if ((rxQBegin_ >= rxQEnd_) && (rxPending_))
{
rxQBegin_ = 0;
rxQEnd_ = rx_packet_irqlocked(rxQ_);
rxPending_ = 0;
}
// Tries to copy data from the buffer.
while (rxQBegin_ < rxQEnd_ && ret < (ssize_t)count)
{
*dst++ = rxQ_[rxQBegin_++];
++ret;
}
if (rxQBegin_ < rxQEnd_)
{
pass_on_notify = true;
}
}
if (pass_on_notify)
{
// We have a partial read. Wake up someone else trying to read.
h.notify_next();
// We lost the lock at notify_next, so we return immediately.
return ret;
}
if (ret > 0 || file->flags & O_NONBLOCK)
{
return ret;
}
// No data received now, and no data in the queue. Blocks the current
// thread and tries the whole dance again.
h.wait_for_notification();
}
}
ssize_t USBSerialNode::write(File *file, const void *buf, size_t count)
{
if (!count) return 0;
const uint8_t *data = static_cast<const uint8_t*>(buf);
ssize_t ret = 0;
auto h = txBlock_.holder();
bool pass_on_notify = false;
while (count)
{
{
auto hh = h.critical();
while (has_tx_buffer_free() && count)
{
add_to_tx_buffer(*data++);
--count;
++ret;
}
if (has_tx_buffer_free()) pass_on_notify = true;
if (!txPending_)
{
if (tx_packet_irqlocked(txQ_, txQEnd_))
{
mark_tx_buffer_sent();
txPending_ = 1;
} else {
// packet send failed -- we'll re-try in a next iteration
pass_on_notify = true;
}
}
}
if (file->flags & O_NONBLOCK) {
break;
}
if (count && !pass_on_notify)
{
h.wait_for_notification();
}
}
if (pass_on_notify)
{
h.notify_next();
// must not use locked fields after this
return ret;
}
return ret;
}
int USBSerialNode::ioctl(File *file, unsigned long int key, unsigned long data)
{
/* sanity check to be sure we have a valid key for this device */
HASSERT(IOC_TYPE(key) == CAN_IOC_MAGIC);
// Will be called at the end if non-null.
Notifiable *n = nullptr;
if (IOC_SIZE(key) == NOTIFIABLE_TYPE)
{
n = reinterpret_cast<Notifiable *>(data);
}
switch (key)
{
default:
return -EINVAL;
case CAN_IOC_READ_ACTIVE:
{
auto h = rxBlock_.holder();
auto hh = h.critical();
if (rxQBegin_ >= rxQEnd_) {
n = rxBlock_.register_notifiable(n);
log_.log(0xC8);
} else {
log_.log(0xC8);
}
break;
}
case CAN_IOC_WRITE_ACTIVE:
{
auto h = txBlock_.holder();
auto hh = h.critical();
if (!has_tx_buffer_free()) {
n = txBlock_.register_notifiable(n);
log_.log(0xCA);
} else {
log_.log(0xCB);
}
break;
}
}
if (n)
n->notify();
return 0;
}
/** Device select method. Default impementation returns true.
* @param file reference to the file
* @param mode FREAD for read active, FWRITE for write active, 0 for
* exceptions
* @return true if active, false if inactive
*/
bool USBSerialNode::select(File* file, int mode)
{
#if 0
switch (mode)
{
case FREAD:
if (os_mq_num_pending(rxQ) > 0)
{
return true;
}
select_insert(&selInfoRd);
break;
case FWRITE:
if (has_tx_buffer_free())
{
return true;
}
select_insert(&selInfoWr);
break;
default:
case 0:
/* we don't support any exceptions */
break;
}
#endif
return false;
}
void USBSerialNode::flush_buffers() OVERRIDE {
{
auto h = txBlock_.holder();
// Since this was called after disable() we don't need the critical
// section anymore.
txQEnd_ = 0;
txPending_ = 0; // is this dangerous?
}
{
auto h = rxBlock_.holder();
rxQBegin_ = rxQEnd_ = 0;
if (rxPending_) {
rx_packet_irqlocked(rxQ_);
rxPending_ = 0;
}
}
}
void USBSerialNode::tx_finished_from_isr()
{
if (txQEnd_) {
if (tx_packet_from_isr(txQ_, txQEnd_))
{
txQEnd_ = 0;
txPending_ = 1;
}
else
{
// We failed ot send the next packet. We'll wake up a writer
// (hopefully) that will re-try sending the packet. However, it is
// possible that there is no writer thread around and there will be
// data stuck in the queue here.
txPending_ = 0;
}
}
else
{
txPending_ = 0;
log_.log(0x20);
}
txBlock_.notify_from_isr();
}
void *USBSerialNode::try_read_packet_from_isr()
{
if (rxQBegin_ >= rxQEnd_)
{
rxQBegin_ = rxQEnd_ = 0;
}
if (static_cast<size_t>(rxQEnd_) + USB_SERIAL_PACKET_SIZE <= sizeof(rxQ_))
{
return &rxQ_[rxQEnd_];
}
else
{
return nullptr;
}
}
void USBSerialNode::set_rx_finished_from_isr(uint8_t size)
{
rxQEnd_ += size;
rxBlock_.notify_from_isr();
}
<|endoftext|> |
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "DeclCollector.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
/// \brief Retrieves the clang CC1 specific flags out of the compilation's
/// jobs. Returns NULL on error.
static const clang::driver::ArgStringList
*GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
clang::driver::Compilation *Compilation) {
// We expect to get back exactly one Command job, if we didn't something
// failed. Extract that job from the Compilation.
const clang::driver::JobList &Jobs = Compilation->getJobs();
if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
// diagnose this...
return NULL;
}
// The one job we find should be to invoke clang again.
const clang::driver::Command *Cmd
= cast<clang::driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
// diagnose this...
return NULL;
}
return &Cmd->getArguments();
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
llvmdir);
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir) {
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::sys::Path resource_path;
if (llvmdir) {
resource_path = llvmdir;
resource_path.appendComponent("lib");
resource_path.appendComponent("clang");
resource_path.appendComponent(CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path
= CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
if (!resource_path.canRead()) {
llvm::errs()
<< "ERROR in cling::CIFactory::createCI():\n resource directory "
<< resource_path.str() << " not found!\n";
resource_path = "";
}
//______________________________________
DiagnosticOptions DefaultDiagnosticOptions;
DefaultDiagnosticOptions.ShowColors = 1;
TextDiagnosticPrinter* DiagnosticPrinter
= new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());
DiagnosticsEngine* Diagnostics
= new DiagnosticsEngine(DiagIDs, DiagnosticPrinter,
/*Owns it*/ true); // LEAKS!
std::vector<const char*> argvCompile(argv, argv + argc);
// We do C++ by default; append right after argv[0] name
// Only insert it if there is no other "-x":
bool haveMinusX = false;
for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;
++iarg) {
haveMinusX = !strcmp(*iarg, "-x");
}
if (!haveMinusX) {
argvCompile.insert(argvCompile.begin() + 1,"-x");
argvCompile.insert(argvCompile.begin() + 2, "c++");
}
argvCompile.push_back("-c");
argvCompile.push_back("-");
bool IsProduction = false;
assert(IsProduction = true && "set IsProduction if asserts are on.");
clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
"cling.out",
IsProduction,
*Diagnostics);
//Driver.setWarnMissingInput(false);
Driver.setCheckInputsExist(false); // think foo.C(12)
llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());
llvm::OwningPtr<clang::driver::Compilation>
Compilation(Driver.BuildCompilation(RF));
const clang::driver::ArgStringList* CC1Args
= GetCC1Arguments(Diagnostics, Compilation.get());
if (CC1Args == NULL) {
return 0;
}
clang::CompilerInvocation*
Invocation = new clang::CompilerInvocation;
clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
CC1Args->data() + CC1Args->size(),
*Diagnostics);
Invocation->getFrontendOpts().DisableFree = true;
if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
!resource_path.empty()) {
// Update ResourceDir
// header search opts' entry for resource_path/include isn't
// updated by providing a new resource path; update it manually.
clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
llvm::sys::Path oldResInc(Opts.ResourceDir);
oldResInc.appendComponent("include");
llvm::sys::Path newResInc(resource_path);
newResInc.appendComponent("include");
bool foundOldResInc = false;
for (unsigned i = 0, e = Opts.UserEntries.size();
!foundOldResInc && i != e; ++i) {
HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
if (!E.IsUserSupplied && !E.IsFramework
&& E.Group == clang::frontend::System && E.IgnoreSysRoot
&& E.IsInternal && !E.ImplicitExternC
&& oldResInc.str() == E.Path) {
E.Path = newResInc.str();
foundOldResInc = true;
}
}
Opts.ResourceDir = resource_path.str();
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
CI->setInvocation(Invocation);
CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
Invocation->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
// Set up source and file managers
CI->createFileManager();
CI->createSourceManager(CI->getFileManager());
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(),
PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(),
/*size_reserve*/0, /*DelayInit*/false);
CI->setASTContext(Ctx);
// Set up the ASTConsumers
CI->setASTConsumer(new DeclCollector());
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Complete, CCC);
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
// When asserts are on, TURN ON not compare the VerifyModule
assert(CI->getCodeGenOpts().VerifyModule = 1);
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 1;
Opts.Exceptions = 1;
Opts.CXXExceptions = 1;
Opts.Deprecated = 1;
Opts.Modules = 1;
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
} else {
Opts.MicrosoftExt = 0;
}
}
} // end namespace
<commit_msg>Turn off the codegen option CXXCtorDtorAliases for the jit. This prevents codegen from implementing a complete constructor by using a linker alias to the base constructor, instead it emits the function itself. This prevents the jit from crashing on simple code.<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "DeclCollector.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
/// \brief Retrieves the clang CC1 specific flags out of the compilation's
/// jobs. Returns NULL on error.
static const clang::driver::ArgStringList
*GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
clang::driver::Compilation *Compilation) {
// We expect to get back exactly one Command job, if we didn't something
// failed. Extract that job from the Compilation.
const clang::driver::JobList &Jobs = Compilation->getJobs();
if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
// diagnose this...
return NULL;
}
// The one job we find should be to invoke clang again.
const clang::driver::Command *Cmd
= cast<clang::driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
// diagnose this...
return NULL;
}
return &Cmd->getArguments();
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
llvmdir);
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir) {
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::sys::Path resource_path;
if (llvmdir) {
resource_path = llvmdir;
resource_path.appendComponent("lib");
resource_path.appendComponent("clang");
resource_path.appendComponent(CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path
= CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
if (!resource_path.canRead()) {
llvm::errs()
<< "ERROR in cling::CIFactory::createCI():\n resource directory "
<< resource_path.str() << " not found!\n";
resource_path = "";
}
//______________________________________
DiagnosticOptions DefaultDiagnosticOptions;
DefaultDiagnosticOptions.ShowColors = 1;
TextDiagnosticPrinter* DiagnosticPrinter
= new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());
DiagnosticsEngine* Diagnostics
= new DiagnosticsEngine(DiagIDs, DiagnosticPrinter,
/*Owns it*/ true); // LEAKS!
std::vector<const char*> argvCompile(argv, argv + argc);
// We do C++ by default; append right after argv[0] name
// Only insert it if there is no other "-x":
bool haveMinusX = false;
for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;
++iarg) {
haveMinusX = !strcmp(*iarg, "-x");
}
if (!haveMinusX) {
argvCompile.insert(argvCompile.begin() + 1,"-x");
argvCompile.insert(argvCompile.begin() + 2, "c++");
}
argvCompile.push_back("-c");
argvCompile.push_back("-");
bool IsProduction = false;
assert(IsProduction = true && "set IsProduction if asserts are on.");
clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
"cling.out",
IsProduction,
*Diagnostics);
//Driver.setWarnMissingInput(false);
Driver.setCheckInputsExist(false); // think foo.C(12)
llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());
llvm::OwningPtr<clang::driver::Compilation>
Compilation(Driver.BuildCompilation(RF));
const clang::driver::ArgStringList* CC1Args
= GetCC1Arguments(Diagnostics, Compilation.get());
if (CC1Args == NULL) {
return 0;
}
clang::CompilerInvocation*
Invocation = new clang::CompilerInvocation;
clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
CC1Args->data() + CC1Args->size(),
*Diagnostics);
Invocation->getFrontendOpts().DisableFree = true;
if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
!resource_path.empty()) {
// Update ResourceDir
// header search opts' entry for resource_path/include isn't
// updated by providing a new resource path; update it manually.
clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
llvm::sys::Path oldResInc(Opts.ResourceDir);
oldResInc.appendComponent("include");
llvm::sys::Path newResInc(resource_path);
newResInc.appendComponent("include");
bool foundOldResInc = false;
for (unsigned i = 0, e = Opts.UserEntries.size();
!foundOldResInc && i != e; ++i) {
HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
if (!E.IsUserSupplied && !E.IsFramework
&& E.Group == clang::frontend::System && E.IgnoreSysRoot
&& E.IsInternal && !E.ImplicitExternC
&& oldResInc.str() == E.Path) {
E.Path = newResInc.str();
foundOldResInc = true;
}
}
Opts.ResourceDir = resource_path.str();
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
CI->setInvocation(Invocation);
CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
Invocation->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
// Set up source and file managers
CI->createFileManager();
CI->createSourceManager(CI->getFileManager());
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(),
PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(),
/*size_reserve*/0, /*DelayInit*/false);
CI->setASTContext(Ctx);
// Set up the ASTConsumers
CI->setASTConsumer(new DeclCollector());
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Complete, CCC);
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
CI->getCodeGenOpts().CXXCtorDtorAliases = 0; // aliasing the complete
// ctor to the base ctor causes
// the JIT to crash
// When asserts are on, TURN ON not compare the VerifyModule
assert(CI->getCodeGenOpts().VerifyModule = 1);
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 1;
Opts.Exceptions = 1;
Opts.CXXExceptions = 1;
Opts.Deprecated = 1;
Opts.Modules = 1;
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
} else {
Opts.MicrosoftExt = 0;
}
}
} // end namespace
<|endoftext|> |
<commit_before>#include "qmljsoutlinetreeview.h"
#include "qmloutlinemodel.h"
#include <QtCore/QDebug>
#include <QtGui/QApplication>
#include <QtGui/QPainter>
namespace QmlJSEditor {
namespace Internal {
QmlJSOutlineItemDelegate::QmlJSOutlineItemDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{
}
QSize QmlJSOutlineItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItemV4 opt = option;
initStyleOption(&opt, index);
const QString annotation = index.data(QmlOutlineModel::AnnotationRole).toString();
if (!annotation.isEmpty())
opt.text += " " + annotation;
QStyle *style = QApplication::style();
return style->sizeFromContents(QStyle::CT_ItemViewItem, &opt, QSize(), 0);
}
void QmlJSOutlineItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItemV4 opt = option;
initStyleOption(&opt, index);
if (opt.state & QStyle::State_Selected)
painter->fillRect(opt.rect, option.palette.highlight());
const QString typeString = index.data(Qt::DisplayRole).toString();
const QString annotationString = index.data(QmlOutlineModel::AnnotationRole).toString();
QStyle *style = QApplication::style();
// paint type name
QRect typeRect = style->itemTextRect(opt.fontMetrics, opt.rect, Qt::AlignLeft, true, typeString);
QPalette::ColorRole textColorRole = QPalette::Text;
if (option.state & QStyle::State_Selected) {
textColorRole = QPalette::HighlightedText;
}
style->drawItemText(painter, typeRect, Qt::AlignLeft, opt.palette, true, typeString, textColorRole);
// paint annotation (e.g. id)
if (!annotationString.isEmpty()) {
QRect annotationRect = style->itemTextRect(opt.fontMetrics, opt.rect, Qt::AlignLeft, true,
annotationString);
static int space = opt.fontMetrics.width(" ");
annotationRect.adjust(typeRect.width() + space, 0, typeRect.width() + space, 0);
QPalette disabledPalette(opt.palette);
disabledPalette.setCurrentColorGroup(QPalette::Disabled);
style->drawItemText(painter, annotationRect, Qt::AlignLeft, disabledPalette, true,
annotationString, textColorRole);
}
}
QmlJSOutlineTreeView::QmlJSOutlineTreeView(QWidget *parent) :
Utils::NavigationTreeView(parent)
{
// see also CppOutlineTreeView
setFocusPolicy(Qt::NoFocus);
setExpandsOnDoubleClick(false);
setDragEnabled(true);
viewport()->setAcceptDrops(true);
setDropIndicatorShown(true);
setDragDropMode(InternalMove);
QmlJSOutlineItemDelegate *itemDelegate = new QmlJSOutlineItemDelegate(this);
setItemDelegateForColumn(0, itemDelegate);
}
} // namespace Internal
} // namespace QmlJSEditor
<commit_msg>QmlJSOutline: Show the type icons again in the outline<commit_after>#include "qmljsoutlinetreeview.h"
#include "qmloutlinemodel.h"
#include <QtCore/QDebug>
#include <QtGui/QApplication>
#include <QtGui/QPainter>
namespace QmlJSEditor {
namespace Internal {
QmlJSOutlineItemDelegate::QmlJSOutlineItemDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{
}
QSize QmlJSOutlineItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItemV4 opt = option;
initStyleOption(&opt, index);
const QString annotation = index.data(QmlOutlineModel::AnnotationRole).toString();
if (!annotation.isEmpty())
opt.text += " " + annotation;
QStyle *style = QApplication::style();
return style->sizeFromContents(QStyle::CT_ItemViewItem, &opt, QSize(), 0);
}
void QmlJSOutlineItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItemV4 opt = option;
initStyleOption(&opt, index);
if (opt.state & QStyle::State_Selected)
painter->fillRect(opt.rect, option.palette.highlight());
const QString typeString = index.data(Qt::DisplayRole).toString();
const QString annotationString = index.data(QmlOutlineModel::AnnotationRole).toString();
QStyle *style = QApplication::style();
style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, 0);
if (!annotationString.isEmpty()) {
QPalette::ColorRole textColorRole = QPalette::Text;
if (option.state & QStyle::State_Selected) {
textColorRole = QPalette::HighlightedText;
}
// calculate sizes of icon, type.
QPixmap iconPixmap = opt.icon.pixmap(opt.rect.size());
QRect iconRect = style->itemPixmapRect(opt.rect, Qt::AlignLeft, iconPixmap);
QRect typeRect = style->itemTextRect(opt.fontMetrics, opt.rect, Qt::AlignLeft, true, typeString);
QRect annotationRect = style->itemTextRect(opt.fontMetrics, opt.rect, Qt::AlignLeft | Qt::AlignBottom, true,
annotationString);
static int space = opt.fontMetrics.width(" ");
annotationRect.adjust(iconRect.width() + typeRect.width() + space, 0,
iconRect.width() + typeRect.width() + space, 0);
QPalette disabledPalette(opt.palette);
disabledPalette.setCurrentColorGroup(QPalette::Disabled);
style->drawItemText(painter, annotationRect, Qt::AlignLeft, disabledPalette, true,
annotationString, textColorRole);
}
}
QmlJSOutlineTreeView::QmlJSOutlineTreeView(QWidget *parent) :
Utils::NavigationTreeView(parent)
{
// see also CppOutlineTreeView
setFocusPolicy(Qt::NoFocus);
setExpandsOnDoubleClick(false);
setDragEnabled(true);
viewport()->setAcceptDrops(true);
setDropIndicatorShown(true);
setDragDropMode(InternalMove);
QmlJSOutlineItemDelegate *itemDelegate = new QmlJSOutlineItemDelegate(this);
setItemDelegateForColumn(0, itemDelegate);
}
} // namespace Internal
} // namespace QmlJSEditor
<|endoftext|> |
<commit_before>/**
*
* Copyright (c) 2021 Project CHIP Authors
*
* 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.
*/
/****************************************************************************
* @file
* @brief Routines for the Low Power plugin, the
*server implementation of the Low Power cluster.
*******************************************************************************
******************************************************************************/
#include <app/clusters/low-power-server/low-power-delegate.h>
#include <app/clusters/low-power-server/low-power-server.h>
#include <app/CommandHandler.h>
#include <app/ConcreteCommandPath.h>
#include <app/util/af.h>
#include <platform/CHIPDeviceConfig.h>
using namespace chip;
using namespace chip::app::Clusters::LowPower;
static constexpr size_t kLowPowerDelegateTableSize =
EMBER_AF_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT;
// -----------------------------------------------------------------------------
// Delegate Implementation
using chip::app::Clusters::LowPower::Delegate;
namespace {
Delegate * gDelegateTable[kLowPowerDelegateTableSize] = { nullptr };
Delegate * GetDelegate(EndpointId endpoint)
{
uint16_t ep = emberAfFindClusterServerEndpointIndex(endpoint, chip::app::Clusters::LowPower::Id);
return (ep == 0xFFFF ? nullptr : gDelegateTable[ep]);
}
bool isDelegateNull(Delegate * delegate, EndpointId endpoint)
{
if (delegate == nullptr)
{
ChipLogProgress(Zcl, "LowPower has no delegate set for endpoint:%u", endpoint);
return true;
}
return false;
}
} // namespace
namespace chip {
namespace app {
namespace Clusters {
namespace LowPower {
void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate)
{
uint16_t ep = emberAfFindClusterServerEndpointIndex(endpoint, chip::app::Clusters::LowPower::Id);
if (ep != 0xFFFF)
{
gDelegateTable[ep] = delegate;
}
else
{
}
}
} // namespace LowPower
} // namespace Clusters
} // namespace app
} // namespace chip
bool emberAfLowPowerClusterSleepCallback(app::CommandHandler * command, const app::ConcreteCommandPath & commandPath,
const Commands::Sleep::DecodableType & commandData)
{
CHIP_ERROR err = CHIP_NO_ERROR;
EndpointId endpoint = commandPath.mEndpointId;
Delegate * delegate = GetDelegate(endpoint);
VerifyOrExit(isDelegateNull(delegate, endpoint) != true, err = CHIP_ERROR_INCORRECT_STATE);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "emberAfLowPowerClusterSleepCallback error: %s", err.AsString());
emberAfSendImmediateDefaultResponse(EMBER_ZCL_STATUS_FAILURE);
}
bool success = delegate->HandleSleep();
EmberAfStatus status = success ? EMBER_ZCL_STATUS_SUCCESS : EMBER_ZCL_STATUS_FAILURE;
emberAfSendImmediateDefaultResponse(status);
return true;
}
void MatterLowPowerPluginServerInitCallback() {}
<commit_msg>Stop crashing in Low Power cluster Sleep command if there's no delegate. (#19494)<commit_after>/**
*
* Copyright (c) 2021 Project CHIP Authors
*
* 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.
*/
/****************************************************************************
* @file
* @brief Routines for the Low Power plugin, the
*server implementation of the Low Power cluster.
*******************************************************************************
******************************************************************************/
#include <app/clusters/low-power-server/low-power-delegate.h>
#include <app/clusters/low-power-server/low-power-server.h>
#include <app/CommandHandler.h>
#include <app/ConcreteCommandPath.h>
#include <app/util/af.h>
#include <platform/CHIPDeviceConfig.h>
#include <protocols/interaction_model/StatusCode.h>
using namespace chip;
using namespace chip::app::Clusters::LowPower;
static constexpr size_t kLowPowerDelegateTableSize =
EMBER_AF_LOW_POWER_CLUSTER_SERVER_ENDPOINT_COUNT + CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT;
// -----------------------------------------------------------------------------
// Delegate Implementation
using chip::app::Clusters::LowPower::Delegate;
namespace {
Delegate * gDelegateTable[kLowPowerDelegateTableSize] = { nullptr };
Delegate * GetDelegate(EndpointId endpoint)
{
uint16_t ep = emberAfFindClusterServerEndpointIndex(endpoint, chip::app::Clusters::LowPower::Id);
return (ep == 0xFFFF ? nullptr : gDelegateTable[ep]);
}
bool isDelegateNull(Delegate * delegate, EndpointId endpoint)
{
if (delegate == nullptr)
{
ChipLogProgress(Zcl, "LowPower has no delegate set for endpoint:%u", endpoint);
return true;
}
return false;
}
} // namespace
namespace chip {
namespace app {
namespace Clusters {
namespace LowPower {
void SetDefaultDelegate(EndpointId endpoint, Delegate * delegate)
{
uint16_t ep = emberAfFindClusterServerEndpointIndex(endpoint, chip::app::Clusters::LowPower::Id);
if (ep != 0xFFFF)
{
gDelegateTable[ep] = delegate;
}
else
{
}
}
} // namespace LowPower
} // namespace Clusters
} // namespace app
} // namespace chip
bool emberAfLowPowerClusterSleepCallback(app::CommandHandler * command, const app::ConcreteCommandPath & commandPath,
const Commands::Sleep::DecodableType & commandData)
{
using Protocols::InteractionModel::Status;
EndpointId endpoint = commandPath.mEndpointId;
Delegate * delegate = GetDelegate(endpoint);
Status status;
if (isDelegateNull(delegate, endpoint))
{
ChipLogError(Zcl, "emberAfLowPowerClusterSleepCallback: no delegate");
status = Status::Failure;
}
else
{
bool success = delegate->HandleSleep();
status = success ? Status::Success : Status::Failure;
}
command->AddStatus(commandPath, status);
return true;
}
void MatterLowPowerPluginServerInitCallback() {}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
** Contact: BlackBerry Limited (blackberry-qt@qnx.com)
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "fileconverter.h"
#include <utils/fileutils.h>
#include <coreplugin/generatedfile.h>
namespace Qnx {
namespace Internal {
//////////////////////////////////////////////////////////////////////////////
//
// ConvertedProjectContext
//
//////////////////////////////////////////////////////////////////////////////
QString ConvertedProjectContext::projectName() const
{
return destProjectPath().section(QLatin1Char('/'), -1);
}
//////////////////////////////////////////////////////////////////////////////
//
// FileConverter
//
//////////////////////////////////////////////////////////////////////////////
bool FileConverter::convertFile(Core::GeneratedFile &file, QString &errorMessage)
{
ImportLog &log = convertedProjectContext().importLog();
log.logInfo(tr("===== Converting file: %1").arg(file.path()));
loadFileContent(file, errorMessage);
if (!errorMessage.isEmpty())
logError(errorMessage);
return errorMessage.isEmpty();
}
QByteArray FileConverter::loadFileContent(const QString &filePath, QString &errorMessage)
{
QByteArray ret;
Utils::FileReader fr;
QString absFilePath = filePath;
if (!filePath.startsWith(QLatin1String(":/"))) {
const QString srcProjectPath = convertedProjectContext().srcProjectPath();
absFilePath = srcProjectPath % QLatin1Char('/') % filePath;
}
fr.fetch(absFilePath);
if (!fr.errorString().isEmpty())
errorMessage = fr.errorString();
else
ret = fr.data();
return ret;
}
bool FileConverter::loadFileContent(Core::GeneratedFile &file, QString &errorMessage)
{
if (file.binaryContents().isEmpty()) {
// virtual files have some content set already
QString filePath = file.path();
QByteArray ba = loadFileContent(filePath, errorMessage);
file.setBinaryContents(ba);
}
return errorMessage.isEmpty();
}
void FileConverter::logError(const QString &errorMessage)
{
if (!errorMessage.isEmpty())
convertedProjectContext().importLog().logError(errorMessage);
}
} // namespace Internal
} // namespace Qnx
<commit_msg>Fix build on OS X<commit_after>/****************************************************************************
**
** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
** Contact: BlackBerry Limited (blackberry-qt@qnx.com)
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "fileconverter.h"
#include <utils/fileutils.h>
#include <coreplugin/generatedfile.h>
namespace Qnx {
namespace Internal {
//////////////////////////////////////////////////////////////////////////////
//
// ConvertedProjectContext
//
//////////////////////////////////////////////////////////////////////////////
QString ConvertedProjectContext::projectName() const
{
return destProjectPath().section(QLatin1Char('/'), -1);
}
//////////////////////////////////////////////////////////////////////////////
//
// FileConverter
//
//////////////////////////////////////////////////////////////////////////////
bool FileConverter::convertFile(Core::GeneratedFile &file, QString &errorMessage)
{
ImportLog &log = convertedProjectContext().importLog();
log.logInfo(tr("===== Converting file: %1").arg(file.path()));
loadFileContent(file, errorMessage);
if (!errorMessage.isEmpty())
logError(errorMessage);
return errorMessage.isEmpty();
}
QByteArray FileConverter::loadFileContent(const QString &filePath, QString &errorMessage)
{
QByteArray ret;
Utils::FileReader fr;
QString absFilePath = filePath;
if (!filePath.startsWith(QLatin1String(":/"))) {
const QString srcProjectPath = convertedProjectContext().srcProjectPath();
absFilePath = srcProjectPath + QLatin1Char('/') + filePath;
}
fr.fetch(absFilePath);
if (!fr.errorString().isEmpty())
errorMessage = fr.errorString();
else
ret = fr.data();
return ret;
}
bool FileConverter::loadFileContent(Core::GeneratedFile &file, QString &errorMessage)
{
if (file.binaryContents().isEmpty()) {
// virtual files have some content set already
QString filePath = file.path();
QByteArray ba = loadFileContent(filePath, errorMessage);
file.setBinaryContents(ba);
}
return errorMessage.isEmpty();
}
void FileConverter::logError(const QString &errorMessage)
{
if (!errorMessage.isEmpty())
convertedProjectContext().importLog().logError(errorMessage);
}
} // namespace Internal
} // namespace Qnx
<|endoftext|> |
<commit_before>#include <nonius/nonius.h++>
#include <utility>
#include <stdexcept>
#include <map>
#include "pcg.hpp"
namespace cmap {
template<typename T>
constexpr inline auto binary_search = [](const T* first, const T* last, T key) {
const auto size = last - first;
auto left = 0;
auto right = size - 1;
while(left <= right) {
const auto m = (left + right) / 2;
const auto current = first[m];
left = (current < key) ? m + 1 : left;
right = (current > key) ? m - 1 : right;
if(current == key) return m;
}
return ptrdiff_t{-1};
};
template<typename T>
constexpr inline auto linear_search = [](const T* first, const T* last, T key) {
const auto size = last - first;
for(auto i = 0 ; i < size ; ++i) {
if(first[i] == key) return ptrdiff_t{i};
}
return ptrdiff_t{-1};
};
template<typename TKey, typename TValue, int TSize = 0>
struct index {
using pair_t = std::pair<TKey,TValue>;
TKey keys[TSize];
TValue values[TSize];
constexpr index()
: keys{}
, values{}
{}
constexpr index(index<TKey,TValue,TSize-1> prev, TKey key, TValue value)
: keys{}
, values{}
{
// This code copies the values from the previous (smaller) index and
// at the same time inserts the key/value combination at the corret
// spot
auto i = 0;
while(i < (TSize - 1) && prev.keys[i] < key) {
keys[i] = prev.keys[i];
values[i] = prev.values[i];
++i;
}
keys[i] = key;
values[i] = value;
while(i < (TSize - 1)) {
keys[i+1] = prev.keys[i];
values[i+1] = prev.values[i];
++i;
}
}
constexpr auto insert(TKey key, TValue value) const
{
using next_t = index<TKey,TValue,TSize+1>;
return next_t(*this, key, value);
}
template<typename TSearch>
constexpr auto find(TKey key, TSearch&& search) const {
const auto first = keys;
const auto last = first + TSize;
const auto idx = search(first, last, key);
return idx >= 0 ? values[idx] : throw std::out_of_range("Key not found!");
}
};
template<typename TKey, typename TValue, int TSize>
constexpr auto operator<<(index<TKey,TValue,TSize> left, std::pair<TKey,TValue> p) {
const auto [key, value] = p;
return left.insert(key, value);
}
constexpr auto map(auto key, auto value) {
return std::pair(key, value);
}
template<typename TKey, typename TValue>
constexpr auto make_map(std::pair<TKey,TValue> first) {
return index<TKey,TValue>() << first;
}
template<typename TKey, typename TValue, typename...Ts>
constexpr auto make_map(std::pair<TKey,TValue> first, Ts...rest) {
return index<TKey,TValue>() << first << (... << rest);
}
} // namespace cmap
template<std::size_t TSize>
constexpr auto random() {
PCG pcg;
pcg(); // initialize
std::array<int, TSize> numbers{};
for(std::size_t i = 0 ; i < TSize ; ++i) {
numbers[i] = pcg();
}
return numbers;
}
template<auto TSize>
constexpr auto reverse(const std::array<int,TSize> in) {
std::array<int,TSize> out{};
for(auto i = 0 ; i < in.size() ; ++i) {
out[i] = in[in.size() - 1 - i];
}
return out;
}
template<std::size_t TSize>
auto make_map(std::array<int, TSize> keys, std::array<int, TSize> values) {
std::map<int,int> map;
for(std::size_t i = 0 ; i < TSize ; ++i) {
map[keys[i]] = values[i];
}
return map;
}
template<std::size_t TSize, std::size_t TDepth = 0>
constexpr auto generate_random_lookup(const std::array<int,TSize>& keys, const std::array<int,TSize>& values) {
if constexpr ((TSize - 1) == TDepth) {
cmap::index<int,int> root;
return cmap::make_map(cmap::map(keys[TDepth], values[TDepth]));
}
else {
return generate_random_lookup<TSize,TDepth + 1>(keys, values) << std::pair(keys[TDepth], values[TDepth]);
}
}
template<auto TSize> constexpr auto keys = random<TSize>();
template<auto TSize> constexpr auto values = random<TSize>();
template<auto TSize> constexpr auto lookup = generate_random_lookup(keys<TSize>,values<TSize>);
template<auto TSize> const auto map = make_map(keys<TSize>, values<TSize>);
template<auto TSize> constexpr auto reversed_keys = reverse(keys<TSize>);
NONIUS_BENCHMARK("[random access 100 (binary_search, constexpr)]", []{
for(const auto key : reversed_keys<100>)) {
volatile auto value = lookup<100>.find(key, cmap::binary_search<int>);
value;
}
})
NONIUS_BENCHMARK("[random access 100 (binary_search, volatile)]", []{
for(const auto key : reversed_keys<100>) {
volatile auto k = key;
volatile auto value = lookup<100>.find(k, cmap::binary_search<int>);
value;
}
})
NONIUS_BENCHMARK("[random access 100 (linear_search, constexpr)]", []{
for(const auto key : reversed_keys<100>) {
volatile auto value = lookup<100>.find(key, cmap::linear_search<int>);
value;
}
})
NONIUS_BENCHMARK("[random access 100 (linear_search, volatile)]", []{
for(const auto key : reversed_keys<100>) {
volatile auto k = key;
volatile auto value = lookup<100>.find(k, cmap::linear_search<int>);
value;
}
})
NONIUS_BENCHMARK("[random access 100 (std::map)]", []{
for(const auto key : reversed_keys<100>) {
volatile auto value = map<100>.at(key);
value;
}
})
<commit_msg>Update cmap.cpp<commit_after>#include <nonius/nonius.h++>
#include <utility>
#include <stdexcept>
#include <map>
#include "pcg.hpp"
namespace cmap {
template<typename T>
constexpr inline auto binary_search = [](const T* first, const T* last, T key) {
const auto size = last - first;
auto left = 0;
auto right = size - 1;
while(left <= right) {
const auto m = (left + right) / 2;
const auto current = first[m];
left = (current < key) ? m + 1 : left;
right = (current > key) ? m - 1 : right;
if(current == key) return m;
}
return ptrdiff_t{-1};
};
template<typename T>
constexpr inline auto linear_search = [](const T* first, const T* last, T key) {
const auto size = last - first;
for(auto i = 0 ; i < size ; ++i) {
if(first[i] == key) return ptrdiff_t{i};
}
return ptrdiff_t{-1};
};
template<typename TKey, typename TValue, int TSize = 0>
struct index {
using pair_t = std::pair<TKey,TValue>;
TKey keys[TSize];
TValue values[TSize];
constexpr index()
: keys{}
, values{}
{}
constexpr index(index<TKey,TValue,TSize-1> prev, TKey key, TValue value)
: keys{}
, values{}
{
// This code copies the values from the previous (smaller) index and
// at the same time inserts the key/value combination at the corret
// spot
auto i = 0;
while(i < (TSize - 1) && prev.keys[i] < key) {
keys[i] = prev.keys[i];
values[i] = prev.values[i];
++i;
}
keys[i] = key;
values[i] = value;
while(i < (TSize - 1)) {
keys[i+1] = prev.keys[i];
values[i+1] = prev.values[i];
++i;
}
}
constexpr auto insert(TKey key, TValue value) const
{
using next_t = index<TKey,TValue,TSize+1>;
return next_t(*this, key, value);
}
template<typename TSearch>
constexpr auto find(TKey key, TSearch&& search) const {
const auto first = keys;
const auto last = first + TSize;
const auto idx = search(first, last, key);
return idx >= 0 ? values[idx] : throw std::out_of_range("Key not found!");
}
};
template<typename TKey, typename TValue, int TSize>
constexpr auto operator<<(index<TKey,TValue,TSize> left, std::pair<TKey,TValue> p) {
const auto [key, value] = p;
return left.insert(key, value);
}
constexpr auto map(auto key, auto value) {
return std::pair(key, value);
}
template<typename TKey, typename TValue>
constexpr auto make_map(std::pair<TKey,TValue> first) {
return index<TKey,TValue>() << first;
}
template<typename TKey, typename TValue, typename...Ts>
constexpr auto make_map(std::pair<TKey,TValue> first, Ts...rest) {
return index<TKey,TValue>() << first << (... << rest);
}
} // namespace cmap
template<std::size_t TSize>
constexpr auto random() {
PCG pcg;
pcg(); // initialize
std::array<int, TSize> numbers{};
for(std::size_t i = 0 ; i < TSize ; ++i) {
numbers[i] = pcg();
}
return numbers;
}
template<auto TSize>
constexpr auto reverse(const std::array<int,TSize> in) {
std::array<int,TSize> out{};
for(auto i = 0 ; i < in.size() ; ++i) {
out[i] = in[in.size() - 1 - i];
}
return out;
}
template<std::size_t TSize>
auto make_map(std::array<int, TSize> keys, std::array<int, TSize> values) {
std::map<int,int> map;
for(std::size_t i = 0 ; i < TSize ; ++i) {
map[keys[i]] = values[i];
}
return map;
}
template<std::size_t TSize, std::size_t TDepth = 0>
constexpr auto generate_random_lookup(const std::array<int,TSize>& keys, const std::array<int,TSize>& values) {
if constexpr ((TSize - 1) == TDepth) {
cmap::index<int,int> root;
return cmap::make_map(cmap::map(keys[TDepth], values[TDepth]));
}
else {
return generate_random_lookup<TSize,TDepth + 1>(keys, values) << std::pair(keys[TDepth], values[TDepth]);
}
}
template<auto TSize> constexpr auto keys = random<TSize>();
template<auto TSize> constexpr auto values = random<TSize>();
template<auto TSize> constexpr auto lookup = generate_random_lookup(keys<TSize>,values<TSize>);
template<auto TSize> const auto map = make_map(keys<TSize>, values<TSize>);
template<auto TSize> constexpr auto reversed_keys = reverse(keys<TSize>);
NONIUS_BENCHMARK("[random access 100 (binary_search, constexpr)]", []{
for(const auto key : reversed_keys<100>) {
volatile auto value = lookup<100>.find(key, cmap::binary_search<int>);
value;
}
})
NONIUS_BENCHMARK("[random access 100 (binary_search, volatile)]", []{
for(const auto key : reversed_keys<100>) {
volatile auto k = key;
volatile auto value = lookup<100>.find(k, cmap::binary_search<int>);
value;
}
})
NONIUS_BENCHMARK("[random access 100 (linear_search, constexpr)]", []{
for(const auto key : reversed_keys<100>) {
volatile auto value = lookup<100>.find(key, cmap::linear_search<int>);
value;
}
})
NONIUS_BENCHMARK("[random access 100 (linear_search, volatile)]", []{
for(const auto key : reversed_keys<100>) {
volatile auto k = key;
volatile auto value = lookup<100>.find(k, cmap::linear_search<int>);
value;
}
})
NONIUS_BENCHMARK("[random access 100 (std::map)]", []{
for(const auto key : reversed_keys<100>) {
volatile auto value = map<100>.at(key);
value;
}
})
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file peer.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
* Peer Network test functions.
*/
#include <boost/test/unit_test.hpp>
#include <chrono>
#include <thread>
#include <libp2p/Host.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
BOOST_AUTO_TEST_SUITE(p2p)
BOOST_AUTO_TEST_CASE(host)
{
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 10;
NetworkPreferences host1prefs("127.0.0.1", 30301, false);
NetworkPreferences host2prefs("127.0.0.1", 30302, false);
Host host1("Test", host1prefs);
host1.start();
Host host2("Test", host2prefs);
auto node2 = host2.id();
host2.start();
host1.addNode(node2, bi::address::from_string("127.0.0.1"), host2prefs.listenPort, host2prefs.listenPort);
this_thread::sleep_for(chrono::seconds(3));
auto host1peerCount = host1.peerCount();
auto host2peerCount = host2.peerCount();
BOOST_REQUIRE_EQUAL(host1peerCount, 1);
BOOST_REQUIRE_EQUAL(host2peerCount, 1);
g_logVerbosity = oldLogVerbosity;
}
BOOST_AUTO_TEST_CASE(networkConfig)
{
Host save("Test", NetworkPreferences(false));
bytes store(save.saveNetwork());
Host restore("Test", NetworkPreferences(false), bytesConstRef(&store));
BOOST_REQUIRE(save.id() == restore.id());
}
BOOST_AUTO_TEST_CASE(save_nodes)
{
std::list<Host*> hosts;
for (auto i:{0,1,2,3,4,5})
{
Host* h = new Host("Test", NetworkPreferences("127.0.0.1", 30300 + i, false));
h->setIdealPeerCount(10);
// starting host is required so listenport is available
h->start();
while (!h->isStarted())
this_thread::sleep_for(chrono::milliseconds(2));
hosts.push_back(h);
}
Host& host = *hosts.front();
for (auto const& h: hosts)
host.addNode(h->id(), bi::address::from_string("127.0.0.1"), h->listenPort(), h->listenPort());
Host& host2 = *hosts.back();
for (auto const& h: hosts)
host2.addNode(h->id(), bi::address::from_string("127.0.0.1"), h->listenPort(), h->listenPort());
this_thread::sleep_for(chrono::milliseconds(2000));
bytes firstHostNetwork(host.saveNetwork());
bytes secondHostNetwork(host.saveNetwork());
BOOST_REQUIRE_EQUAL(sha3(firstHostNetwork), sha3(secondHostNetwork));
BOOST_CHECK_EQUAL(host.peerCount(), 5);
BOOST_CHECK_EQUAL(host2.peerCount(), 5);
RLP r(firstHostNetwork);
BOOST_REQUIRE(r.itemCount() == 3);
BOOST_REQUIRE(r[0].toInt<unsigned>() == dev::p2p::c_protocolVersion);
BOOST_REQUIRE_EQUAL(r[1].toBytes().size(), 32); // secret
BOOST_REQUIRE_EQUAL(r[2].itemCount(), 5);
}
BOOST_AUTO_TEST_SUITE_END()
int peerTest(int argc, char** argv)
{
Public remoteAlias;
short listenPort = 30303;
string remoteHost;
short remotePort = 30303;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-l" && i + 1 < argc)
listenPort = (short)atoi(argv[++i]);
else if (arg == "-r" && i + 1 < argc)
remoteHost = argv[++i];
else if (arg == "-p" && i + 1 < argc)
remotePort = (short)atoi(argv[++i]);
else if (arg == "-ra" && i + 1 < argc)
remoteAlias = Public(dev::fromHex(argv[++i]));
else
remoteHost = argv[i];
}
Host ph("Test", NetworkPreferences(listenPort));
if (!remoteHost.empty() && !remoteAlias)
ph.addNode(remoteAlias, bi::address::from_string(remoteHost), remotePort, remotePort);
this_thread::sleep_for(chrono::milliseconds(200));
return 0;
}
<commit_msg>Improve addNode functionality when addNode is called during network startup.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file peer.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
* Peer Network test functions.
*/
#include <boost/test/unit_test.hpp>
#include <chrono>
#include <thread>
#include <libp2p/Host.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
BOOST_AUTO_TEST_SUITE(p2p)
BOOST_AUTO_TEST_CASE(host)
{
auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 10;
NetworkPreferences host1prefs("127.0.0.1", 30301, false);
NetworkPreferences host2prefs("127.0.0.1", 30302, false);
Host host1("Test", host1prefs);
host1.start();
Host host2("Test", host2prefs);
auto node2 = host2.id();
host2.start();
host1.addNode(node2, bi::address::from_string("127.0.0.1"), host2prefs.listenPort, host2prefs.listenPort);
this_thread::sleep_for(chrono::seconds(3));
auto host1peerCount = host1.peerCount();
auto host2peerCount = host2.peerCount();
BOOST_REQUIRE_EQUAL(host1peerCount, 1);
BOOST_REQUIRE_EQUAL(host2peerCount, 1);
g_logVerbosity = oldLogVerbosity;
}
BOOST_AUTO_TEST_CASE(networkConfig)
{
Host save("Test", NetworkPreferences(false));
bytes store(save.saveNetwork());
Host restore("Test", NetworkPreferences(false), bytesConstRef(&store));
BOOST_REQUIRE(save.id() == restore.id());
}
BOOST_AUTO_TEST_CASE(save_nodes)
{
std::list<Host*> hosts;
for (auto i:{0,1,2,3,4,5})
{
Host* h = new Host("Test", NetworkPreferences("127.0.0.1", 30300 + i, false));
h->setIdealPeerCount(10);
// starting host is required so listenport is available
h->start();
while (!h->haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2));
hosts.push_back(h);
}
Host& host = *hosts.front();
for (auto const& h: hosts)
host.addNode(h->id(), bi::address::from_string("127.0.0.1"), h->listenPort(), h->listenPort());
Host& host2 = *hosts.back();
for (auto const& h: hosts)
host2.addNode(h->id(), bi::address::from_string("127.0.0.1"), h->listenPort(), h->listenPort());
this_thread::sleep_for(chrono::milliseconds(2000));
bytes firstHostNetwork(host.saveNetwork());
bytes secondHostNetwork(host.saveNetwork());
BOOST_REQUIRE_EQUAL(sha3(firstHostNetwork), sha3(secondHostNetwork));
BOOST_CHECK_EQUAL(host.peerCount(), 5);
BOOST_CHECK_EQUAL(host2.peerCount(), 5);
RLP r(firstHostNetwork);
BOOST_REQUIRE(r.itemCount() == 3);
BOOST_REQUIRE(r[0].toInt<unsigned>() == dev::p2p::c_protocolVersion);
BOOST_REQUIRE_EQUAL(r[1].toBytes().size(), 32); // secret
BOOST_REQUIRE_EQUAL(r[2].itemCount(), 5);
}
BOOST_AUTO_TEST_SUITE_END()
int peerTest(int argc, char** argv)
{
Public remoteAlias;
short listenPort = 30303;
string remoteHost;
short remotePort = 30303;
for (int i = 1; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-l" && i + 1 < argc)
listenPort = (short)atoi(argv[++i]);
else if (arg == "-r" && i + 1 < argc)
remoteHost = argv[++i];
else if (arg == "-p" && i + 1 < argc)
remotePort = (short)atoi(argv[++i]);
else if (arg == "-ra" && i + 1 < argc)
remoteAlias = Public(dev::fromHex(argv[++i]));
else
remoteHost = argv[i];
}
Host ph("Test", NetworkPreferences(listenPort));
if (!remoteHost.empty() && !remoteAlias)
ph.addNode(remoteAlias, bi::address::from_string(remoteHost), remotePort, remotePort);
this_thread::sleep_for(chrono::milliseconds(200));
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2011 by Ivan Safrin
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 "PolySound.h"
#include <vorbis/vorbisfile.h>
#include "PolyString.h"
#include "PolyLogger.h"
#include "OSBasics.h"
#include <string>
#include <vector>
using namespace std;
using namespace Polycode;
size_t custom_readfunc(void *ptr, size_t size, size_t nmemb, void *datasource) {
OSFILE *file = (OSFILE*) datasource;
return OSBasics::read(ptr, size, nmemb, file);
}
int custom_seekfunc(void *datasource, ogg_int64_t offset, int whence){
OSFILE *file = (OSFILE*) datasource;
return OSBasics::seek(file, offset, whence);
}
int custom_closefunc(void *datasource) {
OSFILE *file = (OSFILE*) datasource;
return OSBasics::close(file);
}
long custom_tellfunc(void *datasource) {
OSFILE *file = (OSFILE*) datasource;
return OSBasics::tell(file);
}
Sound::Sound(const String& fileName) {
String extension;
size_t found;
found=fileName.rfind(".");
if (found!=string::npos) {
extension = fileName.substr(found+1);
} else {
extension = "";
}
ALuint buffer;
if(extension == "wav" || extension == "WAV") {
buffer = loadWAV(fileName);
} else if(extension == "ogg" || extension == "OGG") {
buffer = loadOGG(fileName);
}
soundSource = GenSource(buffer);
setIsPositional(false);
}
Sound::~Sound() {
Logger::log("destroying sound...\n");
alDeleteSources(1,&soundSource);
}
void Sound::soundCheck(bool result, const String& err) {
if(!result)
soundError(err);
}
void Sound::soundError(const String& err) {
Logger::log("SOUND ERROR: %s\n", err.c_str());
}
unsigned long Sound::readByte32(const unsigned char buffer[4]) {
#if TAU_BIG_ENDIAN
return (buffer[0] << 24) + (buffer[1] << 16) + (buffer[2] << 8) + buffer[3];
#else
return (buffer[3] << 24) + (buffer[2] << 16) + (buffer[1] << 8) + buffer[0];
#endif
}
unsigned short Sound::readByte16(const unsigned char buffer[2]) {
#if TAU_BIG_ENDIAN
return (buffer[0] << 8) + buffer[1];
#else
return (buffer[1] << 8) + buffer[0];
#endif
}
void Sound::Play(bool loop) {
if(!loop) {
alSourcei(soundSource, AL_LOOPING, AL_FALSE);
} else {
alSourcei(soundSource, AL_LOOPING, AL_TRUE);
}
alSourcePlay(soundSource);
}
bool Sound::isPlaying() {
ALenum state;
alGetSourcei(soundSource, AL_SOURCE_STATE, &state);
return (state == AL_PLAYING);
}
void Sound::setVolume(Number newVolume) {
alSourcef(soundSource, AL_GAIN, newVolume);
}
void Sound::setPitch(Number newPitch) {
alSourcef(soundSource, AL_PITCH, newPitch);
}
void Sound::setSoundPosition(Vector3 position) {
if(isPositional)
alSource3f(soundSource,AL_POSITION, position.x, position.y, position.z);
}
void Sound::setSoundVelocity(Vector3 velocity) {
if(isPositional)
alSource3f(soundSource,AL_VELOCITY, velocity.x, velocity.y, velocity.z);
}
void Sound::setSoundDirection(Vector3 direction) {
if(isPositional)
alSource3f(soundSource,AL_DIRECTION, direction.x, direction.y, direction.z);
}
void Sound::setPositionalProperties(Number referenceDistance, Number maxDistance) {
alSourcef(soundSource,AL_REFERENCE_DISTANCE, referenceDistance);
alSourcef(soundSource,AL_MAX_DISTANCE, maxDistance);
}
void Sound::setIsPositional(bool isPositional) {
this->isPositional = isPositional;
if(isPositional) {
alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_FALSE);
} else {
alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_TRUE);
alSource3f(soundSource,AL_POSITION, 0,0,0);
alSource3f(soundSource,AL_VELOCITY, 0,0,0);
alSource3f(soundSource,AL_DIRECTION, 0,0,0);
}
}
void Sound::checkALError(const String& operation) {
ALenum error = alGetError();
if(error != AL_NO_ERROR) {
switch(error) {
case AL_NO_ERROR:
soundError(operation + ": " +ALNoErrorStr);
break;
case AL_INVALID_NAME:
soundError(operation +": " + ALInvalidNameStr);
break;
case AL_INVALID_ENUM:
soundError(operation + ": " +ALInvalidEnumStr);
break;
case AL_INVALID_VALUE:
soundError(operation + ": " +ALInvalidValueStr);
break;
case AL_INVALID_OPERATION:
soundError(operation + ": " +ALInvalidOpStr);
break;
case AL_OUT_OF_MEMORY:
soundError(operation + ": " +ALOutOfMemoryStr);
break;
default:
soundError(operation + ": " +ALOtherErrorStr);
break;
}
}
}
void Sound::Stop() {
alSourceStop(soundSource);
}
ALuint Sound::GenSource() {
ALuint source;
bool looping = false;
ALfloat sourcePos[] = {0.0, 0.0, 0.0};
ALfloat sourceVel[] = {0.0, 0.0, 0.0};
alGetError();
alGenSources(1, &source);
checkALError("Generating sources");
alSourcef(source, AL_PITCH, 1.0);
alSourcef(source, AL_GAIN, 1.0);
alSourcefv(source, AL_POSITION, sourcePos);
alSourcefv(source, AL_VELOCITY, sourceVel);
alSourcei(source, AL_LOOPING, looping);
checkALError("Setting source properties");
return source;
}
ALuint Sound::GenSource(ALuint buffer) {
alGetError();
ALuint source = GenSource();
alSourcei(source, AL_BUFFER, buffer);
checkALError("Setting source buffer");
return source;
}
ALuint Sound::loadOGG(const String& fileName) {
vector<char> buffer;
ALuint bufferID = AL_NONE;
alGenBuffers(1, &bufferID);
int endian = 0; // 0 for Little-Endian, 1 for Big-Endian
int bitStream;
long bytes;
char array[BUFFER_SIZE]; // Local fixed size array
OSFILE *f;
ALenum format;
ALsizei freq;
// Open for binary reading
f = OSBasics::open(fileName.c_str(), "rb");
if(!f) {
soundError("Error loading OGG file!\n");
return bufferID;
}
vorbis_info *pInfo;
OggVorbis_File oggFile;
ov_callbacks callbacks;
callbacks.read_func = custom_readfunc;
callbacks.seek_func = custom_seekfunc;
callbacks.close_func = custom_closefunc;
callbacks.tell_func = custom_tellfunc;
ov_open_callbacks( (void*)f, &oggFile, NULL, 0, callbacks);
// ov_open(f, &oggFile, NULL, 0);
// Get some information about the OGG file
pInfo = ov_info(&oggFile, -1);
// Check the number of channels... always use 16-bit samples
if (pInfo->channels == 1)
format = AL_FORMAT_MONO16;
else
format = AL_FORMAT_STEREO16;
// end if
// The frequency of the sampling rate
freq = pInfo->rate;
do {
// Read up to a buffer's worth of decoded sound data
bytes = ov_read(&oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream);
// Append to end of buffer
buffer.insert(buffer.end(), array, array + bytes);
} while (bytes > 0);
ov_clear(&oggFile);
alBufferData(bufferID, format, &buffer[0], static_cast<ALsizei>(buffer.size()), freq);
OSBasics::close(f);
f = NULL;
return bufferID;
}
ALuint Sound::loadWAV(const String& fileName) {
long bytes;
vector <char> data;
ALenum format;
ALsizei freq;
// Local resources
OSFILE *f = NULL;
char *array = NULL;
ALuint buffer = AL_NONE;
alGetError();
// Open for binary reading
f = OSBasics::open(fileName.c_str(), "rb");
if (!f)
soundError("LoadWav: Could not load wav from " + fileName);
// buffers
char magic[5];
magic[4] = '\0';
unsigned char buffer32[4];
unsigned char buffer16[2];
// check magic
soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
soundCheck(String(magic) == "RIFF", "LoadWav: Wrong wav file format. This file is not a .wav file (no RIFF magic): "+ fileName );
// skip 4 bytes (file size)
OSBasics::seek(f,4,SEEK_CUR);
// check file format
soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
soundCheck(String(magic) == "WAVE", "LoadWav: Wrong wav file format. This file is not a .wav file (no WAVE format): "+ fileName );
// check 'fmt ' sub chunk (1)
soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
soundCheck(String(magic) == "fmt ", "LoadWav: Wrong wav file format. This file is not a .wav file (no 'fmt ' subchunk): "+ fileName );
// read (1)'s size
soundCheck(OSBasics::read(buffer32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned long subChunk1Size = readByte32(buffer32);
soundCheck(subChunk1Size >= 16, "Wrong wav file format. This file is not a .wav file ('fmt ' chunk too small, truncated file?): "+ fileName );
// check PCM audio format
soundCheck(OSBasics::read(buffer16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned short audioFormat = readByte16(buffer16);
soundCheck(audioFormat == 1, "LoadWav: Wrong wav file format. This file is not a .wav file (audio format is not PCM): "+ fileName );
// read number of channels
soundCheck(OSBasics::read(buffer16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned short channels = readByte16(buffer16);
// read frequency (sample rate)
soundCheck(OSBasics::read(buffer32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned long frequency = readByte32(buffer32);
// skip 6 bytes (Byte rate (4), Block align (2))
OSBasics::seek(f,6,SEEK_CUR);
// read bits per sample
soundCheck(OSBasics::read(buffer16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned short bps = readByte16(buffer16);
if (channels == 1)
format = (bps == 8) ? AL_FORMAT_MONO8 : AL_FORMAT_MONO16;
else
format = (bps == 8) ? AL_FORMAT_STEREO8 : AL_FORMAT_STEREO16;
// check 'data' sub chunk (2)
soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
soundCheck(String(magic) == "data", "LoadWav: Wrong wav file format. This file is not a .wav file (no data subchunk): "+ fileName );
soundCheck(OSBasics::read(buffer32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned long subChunk2Size = readByte32(buffer32);
// The frequency of the sampling rate
freq = frequency;
soundCheck(sizeof(freq) == sizeof(frequency), "LoadWav: freq and frequency different sizes");
array = new char[BUFFER_SIZE];
while (data.size() != subChunk2Size) {
// Read up to a buffer's worth of decoded sound data
bytes = OSBasics::read(array, 1, BUFFER_SIZE, f);
if (bytes <= 0)
break;
if (data.size() + bytes > subChunk2Size)
bytes = subChunk2Size - data.size();
// Append to end of buffer
data.insert(data.end(), array, array + bytes);
};
delete []array;
array = NULL;
OSBasics::close(f);
f = NULL;
alGenBuffers(1, &buffer);
soundCheck(alGetError() == AL_NO_ERROR, "LoadWav: Could not generate buffer");
soundCheck(AL_NONE != buffer, "LoadWav: Could not generate buffer");
alBufferData(buffer, format, &data[0], data.size(), freq);
soundCheck(alGetError() == AL_NO_ERROR, "LoadWav: Could not load buffer data");
return buffer;
// if (buffer)
// if (alIsBuffer(buffer) == AL_TRUE)
// alDeleteBuffers(1, &buffer);
//
// if (array)
// delete []array;
//
// if (f)
// OSBasics::close(f);
//
// throw (e);
}
<commit_msg>PolySound changes no longer useful<commit_after>/*
Copyright (C) 2011 by Ivan Safrin
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 "PolySound.h"
#include <vorbis/vorbisfile.h>
#include "PolyString.h"
#include "PolyLogger.h"
#include "OSBasics.h"
#include <string>
#include <vector>
using namespace std;
using namespace Polycode;
size_t custom_readfunc(void *ptr, size_t size, size_t nmemb, void *datasource) {
OSFILE *file = (OSFILE*) datasource;
return OSBasics::read(ptr, size, nmemb, file);
}
int custom_seekfunc(void *datasource, ogg_int64_t offset, int whence){
OSFILE *file = (OSFILE*) datasource;
return OSBasics::seek(file, offset, whence);
}
int custom_closefunc(void *datasource) {
OSFILE *file = (OSFILE*) datasource;
return OSBasics::close(file);
}
long custom_tellfunc(void *datasource) {
OSFILE *file = (OSFILE*) datasource;
return OSBasics::tell(file);
}
Sound::Sound(const String& fileName) {
String extension;
size_t found;
found=fileName.rfind(".");
if (found!=string::npos) {
extension = fileName.substr(found+1);
} else {
extension = "";
}
ALuint buffer;
if(extension == "wav" || extension == "WAV") {
buffer = loadWAV(fileName);
} else if(extension == "ogg" || extension == "OGG") {
buffer = loadOGG(fileName);
}
soundSource = GenSource(buffer);
setIsPositional(false);
}
Sound::~Sound() {
Logger::log("destroying sound...\n");
alDeleteSources(1,&soundSource);
}
void Sound::soundCheck(bool result, const String& err) {
if(!result)
soundError(err);
}
void Sound::soundError(const String& err) {
Logger::log("SOUND ERROR: %s\n", err.c_str());
}
unsigned long Sound::readByte32(const unsigned char buffer[4]) {
#if TAU_BIG_ENDIAN
return (buffer[0] << 24) + (buffer[1] << 16) + (buffer[2] << 8) + buffer[3];
#else
return (buffer[3] << 24) + (buffer[2] << 16) + (buffer[1] << 8) + buffer[0];
#endif
}
unsigned short Sound::readByte16(const unsigned char buffer[2]) {
#if TAU_BIG_ENDIAN
return (buffer[0] << 8) + buffer[1];
#else
return (buffer[1] << 8) + buffer[0];
#endif
}
void Sound::Play(bool loop) {
if(!loop) {
alSourcei(soundSource, AL_LOOPING, AL_FALSE);
} else {
alSourcei(soundSource, AL_LOOPING, AL_TRUE);
}
alSourcePlay(soundSource);
}
bool Sound::isPlaying() {
ALenum state;
alGetSourcei(soundSource, AL_SOURCE_STATE, &state);
return (state == AL_PLAYING);
}
void Sound::setVolume(Number newVolume) {
alSourcef(soundSource, AL_GAIN, newVolume);
}
void Sound::setPitch(Number newPitch) {
alSourcef(soundSource, AL_PITCH, newPitch);
}
void Sound::setSoundPosition(Vector3 position) {
if(isPositional)
alSource3f(soundSource,AL_POSITION, position.x, position.y, position.z);
}
void Sound::setSoundVelocity(Vector3 velocity) {
if(isPositional)
alSource3f(soundSource,AL_VELOCITY, velocity.x, velocity.y, velocity.z);
}
void Sound::setSoundDirection(Vector3 direction) {
if(isPositional)
alSource3f(soundSource,AL_DIRECTION, direction.x, direction.y, direction.z);
}
void Sound::setPositionalProperties(Number referenceDistance, Number maxDistance) {
alSourcef(soundSource,AL_REFERENCE_DISTANCE, referenceDistance);
alSourcef(soundSource,AL_MAX_DISTANCE, maxDistance);
}
void Sound::setIsPositional(bool isPositional) {
this->isPositional = isPositional;
if(isPositional) {
alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_FALSE);
} else {
alSourcei(soundSource, AL_SOURCE_RELATIVE, AL_TRUE);
alSource3f(soundSource,AL_POSITION, 0,0,0);
alSource3f(soundSource,AL_VELOCITY, 0,0,0);
alSource3f(soundSource,AL_DIRECTION, 0,0,0);
}
}
void Sound::checkALError(const String& operation) {
ALenum error = alGetError();
if(error != AL_NO_ERROR) {
switch(error) {
case AL_NO_ERROR:
soundError(operation + ": " +ALNoErrorStr);
break;
case AL_INVALID_NAME:
soundError(operation +": " + ALInvalidNameStr);
break;
case AL_INVALID_ENUM:
soundError(operation + ": " +ALInvalidEnumStr);
break;
case AL_INVALID_VALUE:
soundError(operation + ": " +ALInvalidValueStr);
break;
case AL_INVALID_OPERATION:
soundError(operation + ": " +ALInvalidOpStr);
break;
case AL_OUT_OF_MEMORY:
soundError(operation + ": " +ALOutOfMemoryStr);
break;
default:
soundError(operation + ": " +ALOtherErrorStr);
break;
}
}
}
void Sound::Stop() {
alSourceStop(soundSource);
}
ALuint Sound::GenSource() {
ALuint source;
bool looping = false;
ALfloat sourcePos[] = {0.0, 0.0, 0.0};
ALfloat sourceVel[] = {0.0, 0.0, 0.0};
alGetError();
alGenSources(1, &source);
checkALError("Generating sources");
alSourcef(source, AL_PITCH, 1.0);
alSourcef(source, AL_GAIN, 1.0);
alSourcefv(source, AL_POSITION, sourcePos);
alSourcefv(source, AL_VELOCITY, sourceVel);
alSourcei(source, AL_LOOPING, looping);
checkALError("Setting source properties");
return source;
}
ALuint Sound::GenSource(ALuint buffer) {
alGetError();
ALuint source = GenSource();
alSourcei(source, AL_BUFFER, buffer);
checkALError("Setting source buffer");
return source;
}
ALuint Sound::loadOGG(const String& fileName) {
vector<char> buffer;
ALuint bufferID = AL_NONE;
alGenBuffers(1, &bufferID);
int endian = 0; // 0 for Little-Endian, 1 for Big-Endian
int bitStream;
long bytes;
char array[BUFFER_SIZE]; // Local fixed size array
OSFILE *f;
ALenum format;
ALsizei freq;
// Open for binary reading
f = OSBasics::open(fileName.c_str(), "rb");
if(!f) {
soundError("Error loading OGG file!\n");
return bufferID;
}
vorbis_info *pInfo;
OggVorbis_File oggFile;
ov_callbacks callbacks;
callbacks.read_func = custom_readfunc;
callbacks.seek_func = custom_seekfunc;
callbacks.close_func = custom_closefunc;
callbacks.tell_func = custom_tellfunc;
ov_open_callbacks( (void*)f, &oggFile, NULL, 0, callbacks);
// ov_open(f, &oggFile, NULL, 0);
// Get some information about the OGG file
pInfo = ov_info(&oggFile, -1);
// Check the number of channels... always use 16-bit samples
if (pInfo->channels == 1)
format = AL_FORMAT_MONO16;
else
format = AL_FORMAT_STEREO16;
// end if
// The frequency of the sampling rate
freq = pInfo->rate;
do {
// Read up to a buffer's worth of decoded sound data
bytes = ov_read(&oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream);
// Append to end of buffer
buffer.insert(buffer.end(), array, array + bytes);
} while (bytes > 0);
ov_clear(&oggFile);
alBufferData(bufferID, format, &buffer[0], static_cast<ALsizei>(buffer.size()), freq);
return bufferID;
}
ALuint Sound::loadWAV(const String& fileName) {
long bytes;
vector <char> data;
ALenum format;
ALsizei freq;
// Local resources
OSFILE *f = NULL;
char *array = NULL;
ALuint buffer = AL_NONE;
alGetError();
// Open for binary reading
f = OSBasics::open(fileName.c_str(), "rb");
if (!f)
soundError("LoadWav: Could not load wav from " + fileName);
// buffers
char magic[5];
magic[4] = '\0';
unsigned char buffer32[4];
unsigned char buffer16[2];
// check magic
soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
soundCheck(String(magic) == "RIFF", "LoadWav: Wrong wav file format. This file is not a .wav file (no RIFF magic): "+ fileName );
// skip 4 bytes (file size)
OSBasics::seek(f,4,SEEK_CUR);
// check file format
soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
soundCheck(String(magic) == "WAVE", "LoadWav: Wrong wav file format. This file is not a .wav file (no WAVE format): "+ fileName );
// check 'fmt ' sub chunk (1)
soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
soundCheck(String(magic) == "fmt ", "LoadWav: Wrong wav file format. This file is not a .wav file (no 'fmt ' subchunk): "+ fileName );
// read (1)'s size
soundCheck(OSBasics::read(buffer32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned long subChunk1Size = readByte32(buffer32);
soundCheck(subChunk1Size >= 16, "Wrong wav file format. This file is not a .wav file ('fmt ' chunk too small, truncated file?): "+ fileName );
// check PCM audio format
soundCheck(OSBasics::read(buffer16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned short audioFormat = readByte16(buffer16);
soundCheck(audioFormat == 1, "LoadWav: Wrong wav file format. This file is not a .wav file (audio format is not PCM): "+ fileName );
// read number of channels
soundCheck(OSBasics::read(buffer16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned short channels = readByte16(buffer16);
// read frequency (sample rate)
soundCheck(OSBasics::read(buffer32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned long frequency = readByte32(buffer32);
// skip 6 bytes (Byte rate (4), Block align (2))
OSBasics::seek(f,6,SEEK_CUR);
// read bits per sample
soundCheck(OSBasics::read(buffer16,2,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned short bps = readByte16(buffer16);
if (channels == 1)
format = (bps == 8) ? AL_FORMAT_MONO8 : AL_FORMAT_MONO16;
else
format = (bps == 8) ? AL_FORMAT_STEREO8 : AL_FORMAT_STEREO16;
// check 'data' sub chunk (2)
soundCheck(OSBasics::read(magic,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
soundCheck(String(magic) == "data", "LoadWav: Wrong wav file format. This file is not a .wav file (no data subchunk): "+ fileName );
soundCheck(OSBasics::read(buffer32,4,1,f) == 1, "LoadWav: Cannot read wav file "+ fileName );
unsigned long subChunk2Size = readByte32(buffer32);
// The frequency of the sampling rate
freq = frequency;
soundCheck(sizeof(freq) == sizeof(frequency), "LoadWav: freq and frequency different sizes");
array = new char[BUFFER_SIZE];
while (data.size() != subChunk2Size) {
// Read up to a buffer's worth of decoded sound data
bytes = OSBasics::read(array, 1, BUFFER_SIZE, f);
if (bytes <= 0)
break;
if (data.size() + bytes > subChunk2Size)
bytes = subChunk2Size - data.size();
// Append to end of buffer
data.insert(data.end(), array, array + bytes);
};
delete []array;
array = NULL;
OSBasics::close(f);
f = NULL;
alGenBuffers(1, &buffer);
soundCheck(alGetError() == AL_NO_ERROR, "LoadWav: Could not generate buffer");
soundCheck(AL_NONE != buffer, "LoadWav: Could not generate buffer");
alBufferData(buffer, format, &data[0], data.size(), freq);
soundCheck(alGetError() == AL_NO_ERROR, "LoadWav: Could not load buffer data");
return buffer;
// if (buffer)
// if (alIsBuffer(buffer) == AL_TRUE)
// alDeleteBuffers(1, &buffer);
//
// if (array)
// delete []array;
//
// if (f)
// OSBasics::close(f);
//
// throw (e);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtp_receiver_video.h"
#include <cassert> //assert
#include <cstring> // memcpy()
#include <math.h>
#include "critical_section_wrapper.h"
#include "receiver_fec.h"
#include "rtp_rtcp_impl.h"
#include "rtp_utility.h"
#include "trace.h"
namespace webrtc {
WebRtc_UWord32 BitRateBPS(WebRtc_UWord16 x )
{
return (x & 0x3fff) * WebRtc_UWord32(pow(10.0f,(2 + (x >> 14))));
}
RTPReceiverVideo::RTPReceiverVideo(const WebRtc_Word32 id,
ModuleRtpRtcpImpl* owner)
: _id(id),
_criticalSectionReceiverVideo(
CriticalSectionWrapper::CreateCriticalSection()),
_currentFecFrameDecoded(false),
_receiveFEC(NULL) {
}
RTPReceiverVideo::~RTPReceiverVideo() {
delete _criticalSectionReceiverVideo;
delete _receiveFEC;
}
ModuleRTPUtility::Payload* RTPReceiverVideo::RegisterReceiveVideoPayload(
const char payloadName[RTP_PAYLOAD_NAME_SIZE],
const WebRtc_Word8 payloadType,
const WebRtc_UWord32 maxRate) {
RtpVideoCodecTypes videoType = kRtpNoVideo;
if (ModuleRTPUtility::StringCompare(payloadName, "VP8", 3)) {
videoType = kRtpVp8Video;
} else if (ModuleRTPUtility::StringCompare(payloadName, "I420", 4)) {
videoType = kRtpNoVideo;
} else if (ModuleRTPUtility::StringCompare(payloadName, "ULPFEC", 6)) {
// store this
if (_receiveFEC == NULL) {
_receiveFEC = new ReceiverFEC(_id, this);
}
_receiveFEC->SetPayloadTypeFEC(payloadType);
videoType = kRtpFecVideo;
} else {
return NULL;
}
ModuleRTPUtility::Payload* payload = new ModuleRTPUtility::Payload;
payload->name[RTP_PAYLOAD_NAME_SIZE - 1] = 0;
strncpy(payload->name, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
payload->typeSpecific.Video.videoCodecType = videoType;
payload->typeSpecific.Video.maxRate = maxRate;
payload->audio = false;
return payload;
}
// we have no critext when calling this
// we are not allowed to have any critsects when calling
// CallbackOfReceivedPayloadData
WebRtc_Word32 RTPReceiverVideo::ParseVideoCodecSpecific(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength,
const RtpVideoCodecTypes videoType,
const bool isRED,
const WebRtc_UWord8* incomingRtpPacket,
const WebRtc_UWord16 incomingRtpPacketSize,
const WebRtc_Word64 nowMS) {
WebRtc_Word32 retVal = 0;
_criticalSectionReceiverVideo->Enter();
if (isRED) {
if(_receiveFEC == NULL) {
_criticalSectionReceiverVideo->Leave();
return -1;
}
bool FECpacket = false;
retVal = _receiveFEC->AddReceivedFECPacket(
rtpHeader,
incomingRtpPacket,
payloadDataLength,
FECpacket);
if (retVal != -1) {
retVal = _receiveFEC->ProcessReceivedFEC();
}
_criticalSectionReceiverVideo->Leave();
if(retVal == 0 && FECpacket) {
// Callback with the received FEC packet.
// The normal packets are delivered after parsing.
// This contains the original RTP packet header but with
// empty payload and data length.
rtpHeader->frameType = kFrameEmpty;
// We need this for the routing.
WebRtc_Word32 retVal = SetCodecType(videoType, rtpHeader);
if(retVal != 0) {
return retVal;
}
// Pass the length of FEC packets so that they can be accounted for in
// the bandwidth estimator.
retVal = CallbackOfReceivedPayloadData(NULL, payloadDataLength,
rtpHeader);
}
} else {
// will leave the _criticalSectionReceiverVideo critsect
retVal = ParseVideoCodecSpecificSwitch(rtpHeader,
payloadData,
payloadDataLength,
videoType);
}
return retVal;
}
WebRtc_Word32 RTPReceiverVideo::BuildRTPheader(
const WebRtcRTPHeader* rtpHeader,
WebRtc_UWord8* dataBuffer) const {
dataBuffer[0] = static_cast<WebRtc_UWord8>(0x80); // version 2
dataBuffer[1] = static_cast<WebRtc_UWord8>(rtpHeader->header.payloadType);
if (rtpHeader->header.markerBit) {
dataBuffer[1] |= kRtpMarkerBitMask; // MarkerBit is 1
}
ModuleRTPUtility::AssignUWord16ToBuffer(dataBuffer + 2,
rtpHeader->header.sequenceNumber);
ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer + 4,
rtpHeader->header.timestamp);
ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer + 8,
rtpHeader->header.ssrc);
WebRtc_Word32 rtpHeaderLength = 12;
// Add the CSRCs if any
if (rtpHeader->header.numCSRCs > 0) {
if (rtpHeader->header.numCSRCs > 16) {
// error
assert(false);
}
WebRtc_UWord8* ptr = &dataBuffer[rtpHeaderLength];
for (WebRtc_UWord32 i = 0; i < rtpHeader->header.numCSRCs; ++i) {
ModuleRTPUtility::AssignUWord32ToBuffer(ptr,
rtpHeader->header.arrOfCSRCs[i]);
ptr +=4;
}
dataBuffer[0] = (dataBuffer[0]&0xf0) | rtpHeader->header.numCSRCs;
// Update length of header
rtpHeaderLength += sizeof(WebRtc_UWord32)*rtpHeader->header.numCSRCs;
}
return rtpHeaderLength;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveRecoveredPacketCallback(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
// TODO(pwestin) Re-factor this to avoid the messy critsect handling.
_criticalSectionReceiverVideo->Enter();
_currentFecFrameDecoded = true;
ModuleRTPUtility::Payload* payload = NULL;
if (PayloadTypeToPayload(rtpHeader->header.payloadType, payload) != 0) {
_criticalSectionReceiverVideo->Leave();
return -1;
}
// here we can re-create the original lost packet so that we can use it for
// the relay we need to re-create the RED header too
WebRtc_UWord8 recoveredPacket[IP_PACKET_SIZE];
WebRtc_UWord16 rtpHeaderLength = (WebRtc_UWord16)BuildRTPheader(
rtpHeader, recoveredPacket);
const WebRtc_UWord8 REDForFECHeaderLength = 1;
// replace pltype
recoveredPacket[1] &= 0x80; // reset
recoveredPacket[1] += REDPayloadType(); // replace with RED payload type
// add RED header
recoveredPacket[rtpHeaderLength] = rtpHeader->header.payloadType;
// f-bit always 0
memcpy(recoveredPacket + rtpHeaderLength + REDForFECHeaderLength, payloadData,
payloadDataLength);
return ParseVideoCodecSpecificSwitch(
rtpHeader,
payloadData,
payloadDataLength,
payload->typeSpecific.Video.videoCodecType);
}
WebRtc_Word32 RTPReceiverVideo::SetCodecType(const RtpVideoCodecTypes videoType,
WebRtcRTPHeader* rtpHeader) const {
switch (videoType) {
case kRtpNoVideo:
rtpHeader->type.Video.codec = kRTPVideoGeneric;
break;
case kRtpVp8Video:
rtpHeader->type.Video.codec = kRTPVideoVP8;
break;
case kRtpFecVideo:
rtpHeader->type.Video.codec = kRTPVideoFEC;
break;
}
return 0;
}
WebRtc_Word32 RTPReceiverVideo::ParseVideoCodecSpecificSwitch(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength,
const RtpVideoCodecTypes videoType) {
WebRtc_Word32 retVal = SetCodecType(videoType, rtpHeader);
if (retVal != 0) {
_criticalSectionReceiverVideo->Leave();
return retVal;
}
WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, _id, "%s(timestamp:%u)",
__FUNCTION__, rtpHeader->header.timestamp);
// All receive functions release _criticalSectionReceiverVideo before
// returning.
switch (videoType) {
case kRtpNoVideo:
return ReceiveGenericCodec(rtpHeader, payloadData, payloadDataLength);
case kRtpVp8Video:
return ReceiveVp8Codec(rtpHeader, payloadData, payloadDataLength);
case kRtpFecVideo:
break;
}
_criticalSectionReceiverVideo->Leave();
return -1;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveVp8Codec(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
bool success;
ModuleRTPUtility::RTPPayload parsedPacket;
if (payloadDataLength == 0) {
success = true;
parsedPacket.info.VP8.dataLength = 0;
} else {
ModuleRTPUtility::RTPPayloadParser rtpPayloadParser(kRtpVp8Video,
payloadData,
payloadDataLength,
_id);
success = rtpPayloadParser.Parse(parsedPacket);
}
// from here down we only work on local data
_criticalSectionReceiverVideo->Leave();
if (!success) {
return -1;
}
if (parsedPacket.info.VP8.dataLength == 0) {
// we have an "empty" VP8 packet, it's ok, could be one way video
// Inform the jitter buffer about this packet.
rtpHeader->frameType = kFrameEmpty;
if (CallbackOfReceivedPayloadData(NULL, 0, rtpHeader) != 0) {
return -1;
}
return 0;
}
rtpHeader->frameType = (parsedPacket.frameType == ModuleRTPUtility::kIFrame) ?
kVideoFrameKey : kVideoFrameDelta;
RTPVideoHeaderVP8 *toHeader = &rtpHeader->type.Video.codecHeader.VP8;
ModuleRTPUtility::RTPPayloadVP8 *fromHeader = &parsedPacket.info.VP8;
rtpHeader->type.Video.isFirstPacket = fromHeader->beginningOfPartition
&& (fromHeader->partitionID == 0);
toHeader->pictureId = fromHeader->hasPictureID ? fromHeader->pictureID :
kNoPictureId;
toHeader->tl0PicIdx = fromHeader->hasTl0PicIdx ? fromHeader->tl0PicIdx :
kNoTl0PicIdx;
if (fromHeader->hasTID) {
toHeader->temporalIdx = fromHeader->tID;
toHeader->layerSync = fromHeader->layerSync;
} else {
toHeader->temporalIdx = kNoTemporalIdx;
toHeader->layerSync = false;
}
toHeader->keyIdx = fromHeader->hasKeyIdx ? fromHeader->keyIdx : kNoKeyIdx;
toHeader->frameWidth = fromHeader->frameWidth;
toHeader->frameHeight = fromHeader->frameHeight;
toHeader->partitionId = fromHeader->partitionID;
toHeader->beginningOfPartition = fromHeader->beginningOfPartition;
if(CallbackOfReceivedPayloadData(parsedPacket.info.VP8.data,
parsedPacket.info.VP8.dataLength,
rtpHeader) != 0) {
return -1;
}
return 0;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveGenericCodec(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
rtpHeader->frameType = kVideoFrameKey;
if(((SequenceNumber() + 1) == rtpHeader->header.sequenceNumber) &&
(TimeStamp() != rtpHeader->header.timestamp)) {
rtpHeader->type.Video.isFirstPacket = true;
}
_criticalSectionReceiverVideo->Leave();
if(CallbackOfReceivedPayloadData(payloadData, payloadDataLength,
rtpHeader) != 0) {
return -1;
}
return 0;
}
} // namespace webrtc
<commit_msg>Update parsed non ref frame info. Review URL: https://webrtc-codereview.appspot.com/932015<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtp_receiver_video.h"
#include <cassert> //assert
#include <cstring> // memcpy()
#include <math.h>
#include "critical_section_wrapper.h"
#include "receiver_fec.h"
#include "rtp_rtcp_impl.h"
#include "rtp_utility.h"
#include "trace.h"
namespace webrtc {
WebRtc_UWord32 BitRateBPS(WebRtc_UWord16 x )
{
return (x & 0x3fff) * WebRtc_UWord32(pow(10.0f,(2 + (x >> 14))));
}
RTPReceiverVideo::RTPReceiverVideo(const WebRtc_Word32 id,
ModuleRtpRtcpImpl* owner)
: _id(id),
_criticalSectionReceiverVideo(
CriticalSectionWrapper::CreateCriticalSection()),
_currentFecFrameDecoded(false),
_receiveFEC(NULL) {
}
RTPReceiverVideo::~RTPReceiverVideo() {
delete _criticalSectionReceiverVideo;
delete _receiveFEC;
}
ModuleRTPUtility::Payload* RTPReceiverVideo::RegisterReceiveVideoPayload(
const char payloadName[RTP_PAYLOAD_NAME_SIZE],
const WebRtc_Word8 payloadType,
const WebRtc_UWord32 maxRate) {
RtpVideoCodecTypes videoType = kRtpNoVideo;
if (ModuleRTPUtility::StringCompare(payloadName, "VP8", 3)) {
videoType = kRtpVp8Video;
} else if (ModuleRTPUtility::StringCompare(payloadName, "I420", 4)) {
videoType = kRtpNoVideo;
} else if (ModuleRTPUtility::StringCompare(payloadName, "ULPFEC", 6)) {
// store this
if (_receiveFEC == NULL) {
_receiveFEC = new ReceiverFEC(_id, this);
}
_receiveFEC->SetPayloadTypeFEC(payloadType);
videoType = kRtpFecVideo;
} else {
return NULL;
}
ModuleRTPUtility::Payload* payload = new ModuleRTPUtility::Payload;
payload->name[RTP_PAYLOAD_NAME_SIZE - 1] = 0;
strncpy(payload->name, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
payload->typeSpecific.Video.videoCodecType = videoType;
payload->typeSpecific.Video.maxRate = maxRate;
payload->audio = false;
return payload;
}
// we have no critext when calling this
// we are not allowed to have any critsects when calling
// CallbackOfReceivedPayloadData
WebRtc_Word32 RTPReceiverVideo::ParseVideoCodecSpecific(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength,
const RtpVideoCodecTypes videoType,
const bool isRED,
const WebRtc_UWord8* incomingRtpPacket,
const WebRtc_UWord16 incomingRtpPacketSize,
const WebRtc_Word64 nowMS) {
WebRtc_Word32 retVal = 0;
_criticalSectionReceiverVideo->Enter();
if (isRED) {
if(_receiveFEC == NULL) {
_criticalSectionReceiverVideo->Leave();
return -1;
}
bool FECpacket = false;
retVal = _receiveFEC->AddReceivedFECPacket(
rtpHeader,
incomingRtpPacket,
payloadDataLength,
FECpacket);
if (retVal != -1) {
retVal = _receiveFEC->ProcessReceivedFEC();
}
_criticalSectionReceiverVideo->Leave();
if(retVal == 0 && FECpacket) {
// Callback with the received FEC packet.
// The normal packets are delivered after parsing.
// This contains the original RTP packet header but with
// empty payload and data length.
rtpHeader->frameType = kFrameEmpty;
// We need this for the routing.
WebRtc_Word32 retVal = SetCodecType(videoType, rtpHeader);
if(retVal != 0) {
return retVal;
}
// Pass the length of FEC packets so that they can be accounted for in
// the bandwidth estimator.
retVal = CallbackOfReceivedPayloadData(NULL, payloadDataLength,
rtpHeader);
}
} else {
// will leave the _criticalSectionReceiverVideo critsect
retVal = ParseVideoCodecSpecificSwitch(rtpHeader,
payloadData,
payloadDataLength,
videoType);
}
return retVal;
}
WebRtc_Word32 RTPReceiverVideo::BuildRTPheader(
const WebRtcRTPHeader* rtpHeader,
WebRtc_UWord8* dataBuffer) const {
dataBuffer[0] = static_cast<WebRtc_UWord8>(0x80); // version 2
dataBuffer[1] = static_cast<WebRtc_UWord8>(rtpHeader->header.payloadType);
if (rtpHeader->header.markerBit) {
dataBuffer[1] |= kRtpMarkerBitMask; // MarkerBit is 1
}
ModuleRTPUtility::AssignUWord16ToBuffer(dataBuffer + 2,
rtpHeader->header.sequenceNumber);
ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer + 4,
rtpHeader->header.timestamp);
ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer + 8,
rtpHeader->header.ssrc);
WebRtc_Word32 rtpHeaderLength = 12;
// Add the CSRCs if any
if (rtpHeader->header.numCSRCs > 0) {
if (rtpHeader->header.numCSRCs > 16) {
// error
assert(false);
}
WebRtc_UWord8* ptr = &dataBuffer[rtpHeaderLength];
for (WebRtc_UWord32 i = 0; i < rtpHeader->header.numCSRCs; ++i) {
ModuleRTPUtility::AssignUWord32ToBuffer(ptr,
rtpHeader->header.arrOfCSRCs[i]);
ptr +=4;
}
dataBuffer[0] = (dataBuffer[0]&0xf0) | rtpHeader->header.numCSRCs;
// Update length of header
rtpHeaderLength += sizeof(WebRtc_UWord32)*rtpHeader->header.numCSRCs;
}
return rtpHeaderLength;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveRecoveredPacketCallback(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
// TODO(pwestin) Re-factor this to avoid the messy critsect handling.
_criticalSectionReceiverVideo->Enter();
_currentFecFrameDecoded = true;
ModuleRTPUtility::Payload* payload = NULL;
if (PayloadTypeToPayload(rtpHeader->header.payloadType, payload) != 0) {
_criticalSectionReceiverVideo->Leave();
return -1;
}
// here we can re-create the original lost packet so that we can use it for
// the relay we need to re-create the RED header too
WebRtc_UWord8 recoveredPacket[IP_PACKET_SIZE];
WebRtc_UWord16 rtpHeaderLength = (WebRtc_UWord16)BuildRTPheader(
rtpHeader, recoveredPacket);
const WebRtc_UWord8 REDForFECHeaderLength = 1;
// replace pltype
recoveredPacket[1] &= 0x80; // reset
recoveredPacket[1] += REDPayloadType(); // replace with RED payload type
// add RED header
recoveredPacket[rtpHeaderLength] = rtpHeader->header.payloadType;
// f-bit always 0
memcpy(recoveredPacket + rtpHeaderLength + REDForFECHeaderLength, payloadData,
payloadDataLength);
return ParseVideoCodecSpecificSwitch(
rtpHeader,
payloadData,
payloadDataLength,
payload->typeSpecific.Video.videoCodecType);
}
WebRtc_Word32 RTPReceiverVideo::SetCodecType(const RtpVideoCodecTypes videoType,
WebRtcRTPHeader* rtpHeader) const {
switch (videoType) {
case kRtpNoVideo:
rtpHeader->type.Video.codec = kRTPVideoGeneric;
break;
case kRtpVp8Video:
rtpHeader->type.Video.codec = kRTPVideoVP8;
break;
case kRtpFecVideo:
rtpHeader->type.Video.codec = kRTPVideoFEC;
break;
}
return 0;
}
WebRtc_Word32 RTPReceiverVideo::ParseVideoCodecSpecificSwitch(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength,
const RtpVideoCodecTypes videoType) {
WebRtc_Word32 retVal = SetCodecType(videoType, rtpHeader);
if (retVal != 0) {
_criticalSectionReceiverVideo->Leave();
return retVal;
}
WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, _id, "%s(timestamp:%u)",
__FUNCTION__, rtpHeader->header.timestamp);
// All receive functions release _criticalSectionReceiverVideo before
// returning.
switch (videoType) {
case kRtpNoVideo:
return ReceiveGenericCodec(rtpHeader, payloadData, payloadDataLength);
case kRtpVp8Video:
return ReceiveVp8Codec(rtpHeader, payloadData, payloadDataLength);
case kRtpFecVideo:
break;
}
_criticalSectionReceiverVideo->Leave();
return -1;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveVp8Codec(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
bool success;
ModuleRTPUtility::RTPPayload parsedPacket;
if (payloadDataLength == 0) {
success = true;
parsedPacket.info.VP8.dataLength = 0;
} else {
ModuleRTPUtility::RTPPayloadParser rtpPayloadParser(kRtpVp8Video,
payloadData,
payloadDataLength,
_id);
success = rtpPayloadParser.Parse(parsedPacket);
}
// from here down we only work on local data
_criticalSectionReceiverVideo->Leave();
if (!success) {
return -1;
}
if (parsedPacket.info.VP8.dataLength == 0) {
// we have an "empty" VP8 packet, it's ok, could be one way video
// Inform the jitter buffer about this packet.
rtpHeader->frameType = kFrameEmpty;
if (CallbackOfReceivedPayloadData(NULL, 0, rtpHeader) != 0) {
return -1;
}
return 0;
}
rtpHeader->frameType = (parsedPacket.frameType == ModuleRTPUtility::kIFrame) ?
kVideoFrameKey : kVideoFrameDelta;
RTPVideoHeaderVP8 *toHeader = &rtpHeader->type.Video.codecHeader.VP8;
ModuleRTPUtility::RTPPayloadVP8 *fromHeader = &parsedPacket.info.VP8;
rtpHeader->type.Video.isFirstPacket = fromHeader->beginningOfPartition
&& (fromHeader->partitionID == 0);
toHeader->nonReference = fromHeader->nonReferenceFrame;
toHeader->pictureId = fromHeader->hasPictureID ? fromHeader->pictureID :
kNoPictureId;
toHeader->tl0PicIdx = fromHeader->hasTl0PicIdx ? fromHeader->tl0PicIdx :
kNoTl0PicIdx;
if (fromHeader->hasTID) {
toHeader->temporalIdx = fromHeader->tID;
toHeader->layerSync = fromHeader->layerSync;
} else {
toHeader->temporalIdx = kNoTemporalIdx;
toHeader->layerSync = false;
}
toHeader->keyIdx = fromHeader->hasKeyIdx ? fromHeader->keyIdx : kNoKeyIdx;
toHeader->frameWidth = fromHeader->frameWidth;
toHeader->frameHeight = fromHeader->frameHeight;
toHeader->partitionId = fromHeader->partitionID;
toHeader->beginningOfPartition = fromHeader->beginningOfPartition;
if(CallbackOfReceivedPayloadData(parsedPacket.info.VP8.data,
parsedPacket.info.VP8.dataLength,
rtpHeader) != 0) {
return -1;
}
return 0;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveGenericCodec(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
rtpHeader->frameType = kVideoFrameKey;
if(((SequenceNumber() + 1) == rtpHeader->header.sequenceNumber) &&
(TimeStamp() != rtpHeader->header.timestamp)) {
rtpHeader->type.Video.isFirstPacket = true;
}
_criticalSectionReceiverVideo->Leave();
if(CallbackOfReceivedPayloadData(payloadData, payloadDataLength,
rtpHeader) != 0) {
return -1;
}
return 0;
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#include "interface.h"
#ifdef WIN32
#include <stdio.h>
#include <Windows.h>
#include <Iphlpapi.h>
int getInterfaces(std::vector<DataHolder> *holder) {
PIP_ADAPTER_INFO AdapterInfo;
DWORD dwBufLen = sizeof(AdapterInfo);
char *mac_addr = (char *)malloc(17);
AdapterInfo = (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO));
if (AdapterInfo == NULL)
return -1;
if (GetAdaptersInfo(AdapterInfo, &dwBufLen) == ERROR_BUFFER_OVERFLOW) {
free(AdapterInfo);
AdapterInfo = (IP_ADAPTER_INFO *)malloc(dwBufLen);
if (AdapterInfo == NULL)
return -1;
}
if (GetAdaptersInfo(AdapterInfo, &dwBufLen) == NO_ERROR) {
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
do {
sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X",
pAdapterInfo->Address [0], pAdapterInfo->Address [1],
pAdapterInfo->Address [2], pAdapterInfo->Address [3],
pAdapterInfo->Address [4], pAdapterInfo->Address [5]);
DataHolder d;
d.ip = pAdapterInfo->IpAddressList.IpAddress.String;
d.mask = pAdapterInfo->IpAddressList.IpMask.String;
d.mac = mac_addr;
d.gateway = pAdapterInfo->GatewayList.IpAddress.String;
d.adapter = pAdapterInfo->AdapterName;
d.description = pAdapterInfo->Description;
d.flags = pAdapterInfo->DhcpEnabled;
d.type = pAdapterInfo->Type;
holder->push_back(d);
IP_ADDR_STRING *ips = pAdapterInfo->IpAddressList.Next;
while (ips) {
d.ip = ips->IpAddress.String;
d.mask = ips->IpMask.String;
holder->push_back(d);
ips = ips->Next;
}
pAdapterInfo = pAdapterInfo->Next;
} while (pAdapterInfo);
}
free(AdapterInfo);
return 0;
}
#else
#ifdef linux
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void print_ip(struct ifaddrs *ifaddrs_ptr, void *addr_ptr, std::string *s) {
if (addr_ptr) {
char address [INET6_ADDRSTRLEN];
inet_ntop(ifaddrs_ptr->ifa_addr->sa_family, addr_ptr, address, sizeof(address));
*s = address;
} else {
*s = "";
}
}
void *get_addr_ptr(struct sockaddr *sockaddr_ptr) {
void *addr_ptr = 0;
if (sockaddr_ptr->sa_family == AF_INET)
addr_ptr = &((struct sockaddr_in *)sockaddr_ptr)->sin_addr;
else
if (sockaddr_ptr->sa_family == AF_INET6)
addr_ptr = &((struct sockaddr_in6 *)sockaddr_ptr)->sin6_addr;
return addr_ptr;
}
void print_internet_address(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
void *addr_ptr;
if (!ifaddrs_ptr->ifa_addr)
return;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_addr);
print_ip(ifaddrs_ptr, addr_ptr, &d->ip);
}
void print_netmask(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
void *addr_ptr;
if (!ifaddrs_ptr->ifa_netmask) {
d->mask = "";
return;
}
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_netmask);
print_ip(ifaddrs_ptr, addr_ptr, &d->mask);
}
void print_internet_interface(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
char mac_addr [18];
mac_addr [17] = 0;
print_internet_address(ifaddrs_ptr, d);
print_netmask(ifaddrs_ptr, d);
/* P2P interface destination */
if (ifaddrs_ptr->ifa_dstaddr) {
void *addr_ptr;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_dstaddr);
print_ip(ifaddrs_ptr, addr_ptr, &d->gateway);
}
/* Interface broadcast address */
if (ifaddrs_ptr->ifa_broadaddr) {
void *addr_ptr;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_broadaddr);
print_ip(ifaddrs_ptr, addr_ptr, &d->gateway);
}
int family = ifaddrs_ptr->ifa_addr->sa_family;
if (family == PF_PACKET) {
struct sockaddr *sdl = (struct sockaddr *)(ifaddrs_ptr->ifa_addr);
unsigned char *ptr = (unsigned char *)sdl->sa_data;
ptr += 10;
sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3), *(ptr + 4), *(ptr + 5));
d->mac = mac_addr;
}
}
void print_ifaddrs(struct ifaddrs *ifaddrs_ptr, std::vector<DataHolder> *holder) {
while (ifaddrs_ptr) {
DataHolder d;
d.adapter = ifaddrs_ptr->ifa_name;
d.description = ifaddrs_ptr->ifa_name;
d.flags = ifaddrs_ptr->ifa_flags;
if (ifaddrs_ptr->ifa_addr) {
d.type = ifaddrs_ptr->ifa_addr->sa_family;
if ((ifaddrs_ptr->ifa_addr->sa_family == AF_INET) || (ifaddrs_ptr->ifa_addr->sa_family == AF_INET6) || (ifaddrs_ptr->ifa_addr->sa_family == PF_PACKET)) {
print_internet_interface(ifaddrs_ptr, &d);
holder->push_back(d);
}
}
ifaddrs_ptr = ifaddrs_ptr->ifa_next;
}
}
#else
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if_types.h>
#include <string.h>
void print_ip(struct ifaddrs *ifaddrs_ptr, void *addr_ptr, std::string *s) {
if (addr_ptr) {
char address [INET6_ADDRSTRLEN];
inet_ntop(ifaddrs_ptr->ifa_addr->sa_family, addr_ptr, address, sizeof(address));
*s = address;
} else {
*s = "";
}
}
void *get_addr_ptr(struct sockaddr *sockaddr_ptr) {
void *addr_ptr = 0;
if (sockaddr_ptr->sa_family == AF_INET)
addr_ptr = &((struct sockaddr_in *)sockaddr_ptr)->sin_addr;
else
if (sockaddr_ptr->sa_family == AF_INET6)
addr_ptr = &((struct sockaddr_in6 *)sockaddr_ptr)->sin6_addr;
return addr_ptr;
}
void print_internet_address(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
void *addr_ptr;
if (!ifaddrs_ptr->ifa_addr)
return;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_addr);
print_ip(ifaddrs_ptr, addr_ptr, &d->ip);
}
void print_netmask(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
void *addr_ptr;
if (!ifaddrs_ptr->ifa_netmask) {
d->mask = "";
return;
}
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_netmask);
print_ip(ifaddrs_ptr, addr_ptr, &d->mask);
}
void print_mac_address(const unsigned char *ptr, DataHolder *d) {
int mac_addr_offset;
char mac_addr [18];
mac_addr [17] = 0;
sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3), *(ptr + 4), *(ptr + 5));
d->mac = mac_addr;
}
void print_af_link(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
struct sockaddr_dl *sdl;
sdl = (struct sockaddr_dl *)ifaddrs_ptr->ifa_addr;
if (sdl->sdl_type == IFT_ETHER)
print_mac_address((unsigned char *)LLADDR(sdl), d);
else
if (sdl->sdl_type == IFT_LOOP)
d->mac = "00:00:00:00:00:00";
else
if (sdl->sdl_type == IFT_USB)
d->mac = "usb";
else
d->mac = "";
}
void print_internet_interface(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
print_internet_address(ifaddrs_ptr, d);
print_netmask(ifaddrs_ptr, d);
/* P2P interface destination */
if (ifaddrs_ptr->ifa_dstaddr) {
void *addr_ptr;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_dstaddr);
print_ip(ifaddrs_ptr, addr_ptr, &d->gateway);
}
/* Interface broadcast address */
if (ifaddrs_ptr->ifa_broadaddr) {
void *addr_ptr;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_broadaddr);
print_ip(ifaddrs_ptr, addr_ptr, &d->gateway);
}
}
void print_ifaddrs(struct ifaddrs *ifaddrs_ptr, std::vector<DataHolder> *holder) {
while (ifaddrs_ptr) {
DataHolder d;
d.adapter = ifaddrs_ptr->ifa_name;
d.description = ifaddrs_ptr->ifa_name;
d.flags = ifaddrs_ptr->ifa_flags;
d.type = ifaddrs_ptr->ifa_addr->sa_family;
if ((ifaddrs_ptr->ifa_addr->sa_family == AF_INET) || (ifaddrs_ptr->ifa_addr->sa_family == AF_INET6)) {
print_internet_interface(ifaddrs_ptr, &d);
holder->push_back(d);
} else
if (ifaddrs_ptr->ifa_addr->sa_family == AF_LINK) {
print_af_link(ifaddrs_ptr, &d);
holder->push_back(d);
}
ifaddrs_ptr = ifaddrs_ptr->ifa_next;
}
}
#endif
int getInterfaces(std::vector<DataHolder> *holder) {
struct ifaddrs *ifaddrs_ptr;
int status = getifaddrs(&ifaddrs_ptr);
if (status == -1)
return -1;
print_ifaddrs(ifaddrs_ptr, holder);
freeifaddrs(ifaddrs_ptr);
return 0;
}
#endif
<commit_msg>IFT_USB not defined on OS X<commit_after>#include "interface.h"
#ifdef WIN32
#include <stdio.h>
#include <Windows.h>
#include <Iphlpapi.h>
int getInterfaces(std::vector<DataHolder> *holder) {
PIP_ADAPTER_INFO AdapterInfo;
DWORD dwBufLen = sizeof(AdapterInfo);
char *mac_addr = (char *)malloc(17);
AdapterInfo = (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO));
if (AdapterInfo == NULL)
return -1;
if (GetAdaptersInfo(AdapterInfo, &dwBufLen) == ERROR_BUFFER_OVERFLOW) {
free(AdapterInfo);
AdapterInfo = (IP_ADAPTER_INFO *)malloc(dwBufLen);
if (AdapterInfo == NULL)
return -1;
}
if (GetAdaptersInfo(AdapterInfo, &dwBufLen) == NO_ERROR) {
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
do {
sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X",
pAdapterInfo->Address [0], pAdapterInfo->Address [1],
pAdapterInfo->Address [2], pAdapterInfo->Address [3],
pAdapterInfo->Address [4], pAdapterInfo->Address [5]);
DataHolder d;
d.ip = pAdapterInfo->IpAddressList.IpAddress.String;
d.mask = pAdapterInfo->IpAddressList.IpMask.String;
d.mac = mac_addr;
d.gateway = pAdapterInfo->GatewayList.IpAddress.String;
d.adapter = pAdapterInfo->AdapterName;
d.description = pAdapterInfo->Description;
d.flags = pAdapterInfo->DhcpEnabled;
d.type = pAdapterInfo->Type;
holder->push_back(d);
IP_ADDR_STRING *ips = pAdapterInfo->IpAddressList.Next;
while (ips) {
d.ip = ips->IpAddress.String;
d.mask = ips->IpMask.String;
holder->push_back(d);
ips = ips->Next;
}
pAdapterInfo = pAdapterInfo->Next;
} while (pAdapterInfo);
}
free(AdapterInfo);
return 0;
}
#else
#ifdef linux
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void print_ip(struct ifaddrs *ifaddrs_ptr, void *addr_ptr, std::string *s) {
if (addr_ptr) {
char address [INET6_ADDRSTRLEN];
inet_ntop(ifaddrs_ptr->ifa_addr->sa_family, addr_ptr, address, sizeof(address));
*s = address;
} else {
*s = "";
}
}
void *get_addr_ptr(struct sockaddr *sockaddr_ptr) {
void *addr_ptr = 0;
if (sockaddr_ptr->sa_family == AF_INET)
addr_ptr = &((struct sockaddr_in *)sockaddr_ptr)->sin_addr;
else
if (sockaddr_ptr->sa_family == AF_INET6)
addr_ptr = &((struct sockaddr_in6 *)sockaddr_ptr)->sin6_addr;
return addr_ptr;
}
void print_internet_address(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
void *addr_ptr;
if (!ifaddrs_ptr->ifa_addr)
return;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_addr);
print_ip(ifaddrs_ptr, addr_ptr, &d->ip);
}
void print_netmask(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
void *addr_ptr;
if (!ifaddrs_ptr->ifa_netmask) {
d->mask = "";
return;
}
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_netmask);
print_ip(ifaddrs_ptr, addr_ptr, &d->mask);
}
void print_internet_interface(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
char mac_addr [18];
mac_addr [17] = 0;
print_internet_address(ifaddrs_ptr, d);
print_netmask(ifaddrs_ptr, d);
/* P2P interface destination */
if (ifaddrs_ptr->ifa_dstaddr) {
void *addr_ptr;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_dstaddr);
print_ip(ifaddrs_ptr, addr_ptr, &d->gateway);
}
/* Interface broadcast address */
if (ifaddrs_ptr->ifa_broadaddr) {
void *addr_ptr;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_broadaddr);
print_ip(ifaddrs_ptr, addr_ptr, &d->gateway);
}
int family = ifaddrs_ptr->ifa_addr->sa_family;
if (family == PF_PACKET) {
struct sockaddr *sdl = (struct sockaddr *)(ifaddrs_ptr->ifa_addr);
unsigned char *ptr = (unsigned char *)sdl->sa_data;
ptr += 10;
sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3), *(ptr + 4), *(ptr + 5));
d->mac = mac_addr;
}
}
void print_ifaddrs(struct ifaddrs *ifaddrs_ptr, std::vector<DataHolder> *holder) {
while (ifaddrs_ptr) {
DataHolder d;
d.adapter = ifaddrs_ptr->ifa_name;
d.description = ifaddrs_ptr->ifa_name;
d.flags = ifaddrs_ptr->ifa_flags;
if (ifaddrs_ptr->ifa_addr) {
d.type = ifaddrs_ptr->ifa_addr->sa_family;
if ((ifaddrs_ptr->ifa_addr->sa_family == AF_INET) || (ifaddrs_ptr->ifa_addr->sa_family == AF_INET6) || (ifaddrs_ptr->ifa_addr->sa_family == PF_PACKET)) {
print_internet_interface(ifaddrs_ptr, &d);
holder->push_back(d);
}
}
ifaddrs_ptr = ifaddrs_ptr->ifa_next;
}
}
#else
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if_types.h>
#include <string.h>
void print_ip(struct ifaddrs *ifaddrs_ptr, void *addr_ptr, std::string *s) {
if (addr_ptr) {
char address [INET6_ADDRSTRLEN];
inet_ntop(ifaddrs_ptr->ifa_addr->sa_family, addr_ptr, address, sizeof(address));
*s = address;
} else {
*s = "";
}
}
void *get_addr_ptr(struct sockaddr *sockaddr_ptr) {
void *addr_ptr = 0;
if (sockaddr_ptr->sa_family == AF_INET)
addr_ptr = &((struct sockaddr_in *)sockaddr_ptr)->sin_addr;
else
if (sockaddr_ptr->sa_family == AF_INET6)
addr_ptr = &((struct sockaddr_in6 *)sockaddr_ptr)->sin6_addr;
return addr_ptr;
}
void print_internet_address(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
void *addr_ptr;
if (!ifaddrs_ptr->ifa_addr)
return;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_addr);
print_ip(ifaddrs_ptr, addr_ptr, &d->ip);
}
void print_netmask(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
void *addr_ptr;
if (!ifaddrs_ptr->ifa_netmask) {
d->mask = "";
return;
}
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_netmask);
print_ip(ifaddrs_ptr, addr_ptr, &d->mask);
}
void print_mac_address(const unsigned char *ptr, DataHolder *d) {
int mac_addr_offset;
char mac_addr [18];
mac_addr [17] = 0;
sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3), *(ptr + 4), *(ptr + 5));
d->mac = mac_addr;
}
void print_af_link(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
struct sockaddr_dl *sdl;
sdl = (struct sockaddr_dl *)ifaddrs_ptr->ifa_addr;
if (sdl->sdl_type == IFT_ETHER)
print_mac_address((unsigned char *)LLADDR(sdl), d);
else
if (sdl->sdl_type == IFT_LOOP)
d->mac = "00:00:00:00:00:00";
else
#ifdef IFT_USB
if (sdl->sdl_type == IFT_USB)
d->mac = "usb";
else
#endif
d->mac = "";
}
void print_internet_interface(struct ifaddrs *ifaddrs_ptr, DataHolder *d) {
print_internet_address(ifaddrs_ptr, d);
print_netmask(ifaddrs_ptr, d);
/* P2P interface destination */
if (ifaddrs_ptr->ifa_dstaddr) {
void *addr_ptr;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_dstaddr);
print_ip(ifaddrs_ptr, addr_ptr, &d->gateway);
}
/* Interface broadcast address */
if (ifaddrs_ptr->ifa_broadaddr) {
void *addr_ptr;
addr_ptr = get_addr_ptr(ifaddrs_ptr->ifa_broadaddr);
print_ip(ifaddrs_ptr, addr_ptr, &d->gateway);
}
}
void print_ifaddrs(struct ifaddrs *ifaddrs_ptr, std::vector<DataHolder> *holder) {
while (ifaddrs_ptr) {
DataHolder d;
d.adapter = ifaddrs_ptr->ifa_name;
d.description = ifaddrs_ptr->ifa_name;
d.flags = ifaddrs_ptr->ifa_flags;
d.type = ifaddrs_ptr->ifa_addr->sa_family;
if ((ifaddrs_ptr->ifa_addr->sa_family == AF_INET) || (ifaddrs_ptr->ifa_addr->sa_family == AF_INET6)) {
print_internet_interface(ifaddrs_ptr, &d);
holder->push_back(d);
} else
if (ifaddrs_ptr->ifa_addr->sa_family == AF_LINK) {
print_af_link(ifaddrs_ptr, &d);
holder->push_back(d);
}
ifaddrs_ptr = ifaddrs_ptr->ifa_next;
}
}
#endif
int getInterfaces(std::vector<DataHolder> *holder) {
struct ifaddrs *ifaddrs_ptr;
int status = getifaddrs(&ifaddrs_ptr);
if (status == -1)
return -1;
print_ifaddrs(ifaddrs_ptr, holder);
freeifaddrs(ifaddrs_ptr);
return 0;
}
#endif
<|endoftext|> |
<commit_before>#include "Common.h"
#include "Engine.h"
CCommon::CCommon(void)
{
}
CCommon::~CCommon(void)
{
}
vec3 CCommon::GetTransformDirection(const mat4& matTransform, const vec3& vUP)
{
return MakeRotationFromYZ(matTransform.getColumn3(1), vUP) * vec3(0.0f, -1.0f, 0.0f);
}
int CCommon::GetIntersectionPosition(vec3& vRetPoint, const vec3& p0, const vec3& p1, int nMask /*= 2|4*/)
{
vec3 n;
int s;
g_Engine.pWorld->GetIntersection(p0, p1, nMask, vRetPoint, n, s);
return s >= 0;
}
int CCommon::GetIntersectionObject(CBRObject** vRetObject, const vec3& p0, const vec3& p1, int nMask /*= 2|4*/)
{
vec3 p, n;
int s;
*vRetObject = g_Engine.pWorld->GetIntersection(p0, p1, nMask, p, n, s);
return s >= 0;
}
float CCommon::CalcAxisScale(const mat4& modelview, float fov, vec4 objectPosW, float sizeInPixels, float viewHeight)
{
float worldHeight;
// World height on origin's z value
vec4 objPosV;
objPosV = modelview * objectPosW;
worldHeight = 2.0f * CMathCore::Abs(objPosV.z) * (float)CMathCore::Tan(fov / 2.0f * DEG2RAD);
return sizeInPixels * (worldHeight / viewHeight);
}<commit_msg>GetIntersectionObject<commit_after>#include "Common.h"
#include "Engine.h"
CCommon::CCommon(void)
{
}
CCommon::~CCommon(void)
{
}
vec3 CCommon::GetTransformDirection(const mat4& matTransform, const vec3& vUP)
{
return MakeRotationFromYZ(matTransform.getColumn3(1), vUP) * vec3(0.0f, -1.0f, 0.0f);
}
int CCommon::GetIntersectionPosition(vec3& vRetPoint, const vec3& p0, const vec3& p1, int nMask /*= 2|4*/)
{
vec3 n;
int s;
g_Engine.pWorld->GetIntersection(p0, p1, nMask, vRetPoint, n, s);
return s >= 0;
}
int CCommon::GetIntersectionObject(CBRObject** vRetObject, const vec3& p0, const vec3& p1, int nMask /*= 2|4*/)
{
vec3 p, n;
int s;
vRetObject = NULL;
*vRetObject = g_Engine.pWorld->GetIntersection(p0, p1, nMask, p, n, s);
return s >= 0;
}
float CCommon::CalcAxisScale(const mat4& modelview, float fov, vec4 objectPosW, float sizeInPixels, float viewHeight)
{
float worldHeight;
// World height on origin's z value
vec4 objPosV;
objPosV = modelview * objectPosW;
worldHeight = 2.0f * CMathCore::Abs(objPosV.z) * (float)CMathCore::Tan(fov / 2.0f * DEG2RAD);
return sizeInPixels * (worldHeight / viewHeight);
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "Config.h"
#include "version.h"
using namespace boost::program_options;
namespace i2p {
namespace config {
options_description m_OptionsDesc;
variables_map m_Options;
void Init() {
options_description general("General options");
general.add_options()
("help,h", "Show this message")
("conf,c", value<std::string>()->default_value(""), "Path to main i2pd config file (default: try ~/.i2pd/i2p.conf or /var/lib/i2pd/i2p.conf)")
("tunconf", value<std::string>()->default_value(""), "Path to config with tunnels list and options (default: try ~/.i2pd/tunnels.cfg or /var/lib/i2pd/tunnels.cfg)")
("pidfile", value<std::string>()->default_value(""), "Write pidfile to given path")
("log", value<bool>()->zero_tokens(), "Write logs to file instead stdout")
("loglevel", value<std::string>()->default_value("info"), "Set the minimal level of log messages (debug, info, warn, error)")
("host", value<std::string>()->default_value(""), "External IP (deprecated)")
("port,p", value<uint16_t>()->default_value(4567), "Port to listen for incoming connections")
("ipv6,6", value<bool>()->zero_tokens(), "Enable communication through ipv6")
("daemon", value<bool>()->zero_tokens(), "Router will go to background after start")
("service", value<bool>()->zero_tokens(), "Router will use system folders like '/var/lib/i2pd'")
("notransit", value<bool>()->zero_tokens(), "Router will not forward transit traffic")
("floodfill", value<bool>()->zero_tokens(), "Router will try to become floodfill")
("bandwidth", value<char>()->default_value('O'), "Bandwidth limiting: L - 32kbps, O - 256Kbps, P - unlimited")
;
options_description httpserver("HTTP Server options");
httpserver.add_options()
("http.enabled", value<bool>()->default_value(true), "Enable or disable webconsole")
("http.address", value<std::string>()->default_value("127.0.0.1"), "Webconsole listen address")
("http.port", value<uint16_t>()->default_value(7070), "Webconsole listen port")
;
options_description httpproxy("HTTP Proxy options");
httpproxy.add_options()
("httpproxy.enabled", value<bool>()->default_value(true), "Enable or disable HTTP Proxy")
("httpproxy.address", value<std::string>()->default_value("127.0.0.1"), "HTTP Proxy listen address")
("httpproxy.port", value<uint16_t>()->default_value(4446), "HTTP Proxy listen port")
("httpproxy.keys", value<std::string>()->default_value("httpproxy-keys.dat"), "HTTP Proxy encryption keys")
;
options_description socksproxy("SOCKS Proxy options");
socksproxy.add_options()
("socksproxy.enabled", value<bool>()->default_value(true), "Enable or disable SOCKS Proxy")
("socksproxy.address", value<std::string>()->default_value("127.0.0.1"), "SOCKS Proxy listen address")
("socksproxy.port", value<uint16_t>()->default_value(4447), "SOCKS Proxy listen port")
("socksproxy.keys", value<std::string>()->default_value("socksproxy-keys.dat"), "SOCKS Proxy encryption keys")
;
options_description sam("SAM bridge options");
sam.add_options()
("sam.enabled", value<bool>()->default_value(false), "Enable or disable SAM Application bridge")
("sam.address", value<std::string>()->default_value("127.0.0.1"), "SAM listen address")
("sam.port", value<uint16_t>()->default_value(7656), "SAM listen port")
;
options_description bob("BOB options");
bob.add_options()
("bob.enabled", value<bool>()->default_value(false), "Enable or disable BOB command channel")
("bob.address", value<std::string>()->default_value("127.0.0.1"), "BOB listen address")
("bob.port", value<uint16_t>()->default_value(2827), "BOB listen port")
;
options_description i2pcontrol("I2PControl options");
i2pcontrol.add_options()
("i2pcontrol.enabled", value<bool>()->default_value(false), "Enable or disable I2P Control Protocol")
("i2pcontrol.address", value<std::string>()->default_value("127.0.0.1"), "I2PCP listen address")
("i2pcontrol.port", value<uint16_t>()->default_value(7650), "I2PCP listen port")
;
m_OptionsDesc
.add(general)
.add(httpserver)
.add(httpproxy)
.add(socksproxy)
.add(sam)
.add(bob)
.add(i2pcontrol)
;
}
void ParseCmdline(int argc, char* argv[]) {
try {
store(parse_command_line(argc, argv, m_OptionsDesc), m_Options);
} catch (boost::program_options::error e) {
std::cerr << "args: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
if (m_Options.count("help")) {
std::cout << "i2pd version " << I2PD_VERSION << " (" << I2P_VERSION << ")" << std::endl;
std::cout << m_OptionsDesc;
exit(EXIT_SUCCESS);
}
}
void ParseConfig(const std::string& path) {
std::ifstream config(path, std::ios::in);
if (!config.is_open()) {
std::cerr << "missing/unreadable config file: " << path << std::endl;
exit(EXIT_FAILURE);
}
try {
store(boost::program_options::parse_config_file(config, m_OptionsDesc), m_Options);
} catch (boost::program_options::error e) {
std::cerr << e.what() << std::endl;
exit(EXIT_FAILURE);
};
}
void Finalize() {
notify(m_Options);
};
} // namespace config
} // namespace i2p
<commit_msg>* add new option 'i2pcontrol.password'<commit_after>/*
* Copyright (c) 2013-2016, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include "Config.h"
#include "version.h"
using namespace boost::program_options;
namespace i2p {
namespace config {
options_description m_OptionsDesc;
variables_map m_Options;
void Init() {
options_description general("General options");
general.add_options()
("help,h", "Show this message")
("conf,c", value<std::string>()->default_value(""), "Path to main i2pd config file (default: try ~/.i2pd/i2p.conf or /var/lib/i2pd/i2p.conf)")
("tunconf", value<std::string>()->default_value(""), "Path to config with tunnels list and options (default: try ~/.i2pd/tunnels.cfg or /var/lib/i2pd/tunnels.cfg)")
("pidfile", value<std::string>()->default_value(""), "Write pidfile to given path")
("log", value<bool>()->zero_tokens(), "Write logs to file instead stdout")
("loglevel", value<std::string>()->default_value("info"), "Set the minimal level of log messages (debug, info, warn, error)")
("host", value<std::string>()->default_value(""), "External IP (deprecated)")
("port,p", value<uint16_t>()->default_value(4567), "Port to listen for incoming connections")
("ipv6,6", value<bool>()->zero_tokens(), "Enable communication through ipv6")
("daemon", value<bool>()->zero_tokens(), "Router will go to background after start")
("service", value<bool>()->zero_tokens(), "Router will use system folders like '/var/lib/i2pd'")
("notransit", value<bool>()->zero_tokens(), "Router will not forward transit traffic")
("floodfill", value<bool>()->zero_tokens(), "Router will try to become floodfill")
("bandwidth", value<char>()->default_value('O'), "Bandwidth limiting: L - 32kbps, O - 256Kbps, P - unlimited")
;
options_description httpserver("HTTP Server options");
httpserver.add_options()
("http.enabled", value<bool>()->default_value(true), "Enable or disable webconsole")
("http.address", value<std::string>()->default_value("127.0.0.1"), "Webconsole listen address")
("http.port", value<uint16_t>()->default_value(7070), "Webconsole listen port")
;
options_description httpproxy("HTTP Proxy options");
httpproxy.add_options()
("httpproxy.enabled", value<bool>()->default_value(true), "Enable or disable HTTP Proxy")
("httpproxy.address", value<std::string>()->default_value("127.0.0.1"), "HTTP Proxy listen address")
("httpproxy.port", value<uint16_t>()->default_value(4446), "HTTP Proxy listen port")
("httpproxy.keys", value<std::string>()->default_value("httpproxy-keys.dat"), "HTTP Proxy encryption keys")
;
options_description socksproxy("SOCKS Proxy options");
socksproxy.add_options()
("socksproxy.enabled", value<bool>()->default_value(true), "Enable or disable SOCKS Proxy")
("socksproxy.address", value<std::string>()->default_value("127.0.0.1"), "SOCKS Proxy listen address")
("socksproxy.port", value<uint16_t>()->default_value(4447), "SOCKS Proxy listen port")
("socksproxy.keys", value<std::string>()->default_value("socksproxy-keys.dat"), "SOCKS Proxy encryption keys")
;
options_description sam("SAM bridge options");
sam.add_options()
("sam.enabled", value<bool>()->default_value(false), "Enable or disable SAM Application bridge")
("sam.address", value<std::string>()->default_value("127.0.0.1"), "SAM listen address")
("sam.port", value<uint16_t>()->default_value(7656), "SAM listen port")
;
options_description bob("BOB options");
bob.add_options()
("bob.enabled", value<bool>()->default_value(false), "Enable or disable BOB command channel")
("bob.address", value<std::string>()->default_value("127.0.0.1"), "BOB listen address")
("bob.port", value<uint16_t>()->default_value(2827), "BOB listen port")
;
options_description i2pcontrol("I2PControl options");
i2pcontrol.add_options()
("i2pcontrol.enabled", value<bool>()->default_value(false), "Enable or disable I2P Control Protocol")
("i2pcontrol.address", value<std::string>()->default_value("127.0.0.1"), "I2PCP listen address")
("i2pcontrol.port", value<uint16_t>()->default_value(7650), "I2PCP listen port")
("i2pcontrol.password", value<std::string>()->default_value("itoopie"), "I2PCP access password")
;
m_OptionsDesc
.add(general)
.add(httpserver)
.add(httpproxy)
.add(socksproxy)
.add(sam)
.add(bob)
.add(i2pcontrol)
;
}
void ParseCmdline(int argc, char* argv[]) {
try {
store(parse_command_line(argc, argv, m_OptionsDesc), m_Options);
} catch (boost::program_options::error e) {
std::cerr << "args: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
if (m_Options.count("help")) {
std::cout << "i2pd version " << I2PD_VERSION << " (" << I2P_VERSION << ")" << std::endl;
std::cout << m_OptionsDesc;
exit(EXIT_SUCCESS);
}
}
void ParseConfig(const std::string& path) {
std::ifstream config(path, std::ios::in);
if (!config.is_open()) {
std::cerr << "missing/unreadable config file: " << path << std::endl;
exit(EXIT_FAILURE);
}
try {
store(boost::program_options::parse_config_file(config, m_OptionsDesc), m_Options);
} catch (boost::program_options::error e) {
std::cerr << e.what() << std::endl;
exit(EXIT_FAILURE);
};
}
void Finalize() {
notify(m_Options);
};
} // namespace config
} // namespace i2p
<|endoftext|> |
<commit_before>// Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Dialect/Stream/IR/StreamTypes.h"
#include "iree/compiler/Dialect/Stream/IR/StreamOps.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/CommandLine.h"
#include "mlir/IR/DialectImplementation.h"
// clang-format off: must be included after all LLVM/MLIR headers.
#define GET_ATTRDEF_CLASSES
#include "iree/compiler/Dialect/Stream/IR/StreamAttrs.cpp.inc" // IWYU pragma: keep
#include "iree/compiler/Dialect/Stream/IR/StreamEnums.cpp.inc" // IWYU pragma: keep
#define GET_TYPEDEF_CLASSES
#include "iree/compiler/Dialect/Stream/IR/StreamTypes.cpp.inc" // IWYU pragma: keep
// clang-format on
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Stream {
static llvm::cl::opt<Favor> partitioningFavor(
"iree-stream-partitioning-favor",
llvm::cl::desc("Default stream partitioning favor configuration."),
llvm::cl::init(Favor::MaxConcurrency),
llvm::cl::values(
clEnumValN(Favor::Debug, "debug",
"Force debug partitioning (no concurrency or pipelining)."),
clEnumValN(Favor::MinPeakMemory, "min-peak-memory",
"Favor minimizing memory consumption at the cost of "
"additional concurrency."),
clEnumValN(Favor::MaxConcurrency, "max-concurrency",
"Favor maximizing concurrency at the cost of additional "
"memory consumption.")));
//===----------------------------------------------------------------------===//
// #stream.resource_config<...>
//===----------------------------------------------------------------------===//
// static
Attribute ResourceConfigAttr::parse(AsmParser &p, Type type) {
if (failed(p.parseLess()) || failed(p.parseLBrace())) return {};
int64_t maxAllocationSize = 0;
int64_t minBufferOffsetAlignment = 0;
int64_t maxBufferRange = 0;
int64_t minBufferRangeAlignment = 0;
while (failed(p.parseOptionalRBrace())) {
StringRef key;
int64_t value = 0;
if (failed(p.parseKeyword(&key)) || failed(p.parseEqual()) ||
failed(p.parseInteger(value))) {
return {};
}
if (key == "max_allocation_size") {
maxAllocationSize = value;
} else if (key == "min_buffer_offset_alignment") {
minBufferOffsetAlignment = value;
} else if (key == "max_buffer_range") {
maxBufferRange = value;
} else if (key == "min_buffer_range_alignment") {
minBufferRangeAlignment = value;
}
(void)p.parseOptionalComma();
}
if (failed(p.parseGreater())) return {};
return ResourceConfigAttr::get(p.getContext(), maxAllocationSize,
minBufferOffsetAlignment, maxBufferRange,
minBufferRangeAlignment);
}
void ResourceConfigAttr::print(AsmPrinter &p) const {
auto &os = p.getStream();
os << "<{";
os << "max_allocation_size = " << getMaxAllocationSize() << ", ";
os << "min_buffer_offset_alignment = " << getMinBufferOffsetAlignment()
<< ", ";
os << "max_buffer_range = " << getMaxBufferRange() << ", ";
os << "min_buffer_range_alignment = " << getMinBufferRangeAlignment();
os << "}>";
}
// static
ResourceConfigAttr ResourceConfigAttr::intersectBufferConstraints(
ResourceConfigAttr lhs, ResourceConfigAttr rhs) {
if (!lhs) return rhs;
if (!rhs) return lhs;
Builder b(lhs.getContext());
return ResourceConfigAttr::get(
b.getContext(),
std::min(lhs.getMaxAllocationSize(), rhs.getMaxAllocationSize()),
std::max(lhs.getMinBufferOffsetAlignment(),
rhs.getMinBufferOffsetAlignment()),
std::min(lhs.getMaxBufferRange(), rhs.getMaxBufferRange()),
std::max(lhs.getMinBufferRangeAlignment(),
rhs.getMinBufferRangeAlignment()));
}
// static
ResourceConfigAttr ResourceConfigAttr::getDefaultHostConstraints(
MLIRContext *context) {
// Picked to represent what we kind of want on CPU today.
// TODO(#8484): properly choose this value based on target devices. We don't
// yet have the device information up in stream and thus for targets that have
// high alignment requirements (128/256/etc) we are not picking the right
// value here.
uint64_t maxAllocationSize = UINT32_MAX;
uint64_t minBufferOffsetAlignment = 64ull;
uint64_t maxBufferRange = UINT32_MAX;
uint64_t minBufferRangeAlignment = 64ull;
return ResourceConfigAttr::get(context, maxAllocationSize,
minBufferOffsetAlignment, maxBufferRange,
minBufferRangeAlignment);
}
// TODO(benvanik): find a way to go affinity -> resource config.
// For now we just always fall back to the conservative host config.
static ResourceConfigAttr inferResourceConfigFromAffinity(
AffinityAttr affinityAttr) {
return {};
}
// static
ResourceConfigAttr ResourceConfigAttr::lookup(Operation *op) {
auto *context = op->getContext();
auto attrId = StringAttr::get(context, "stream.resources");
while (op) {
if (auto affinityOp = llvm::dyn_cast<AffinityOpInterface>(op)) {
auto affinityAttr = affinityOp.getAffinity();
if (affinityAttr) {
auto attr = inferResourceConfigFromAffinity(affinityAttr);
if (attr) return attr;
}
}
auto attr = op->getAttrOfType<ResourceConfigAttr>(attrId);
if (attr) return attr;
op = op->getParentOp();
}
// No config found; use conservative host config.
return getDefaultHostConstraints(context);
}
//===----------------------------------------------------------------------===//
// #stream.timepoint<...>
//===----------------------------------------------------------------------===//
Attribute TimepointAttr::parse(AsmParser &p, Type type) {
StringRef timeStr;
if (failed(p.parseLess())) return {};
if (failed(p.parseKeyword(&timeStr))) {
return {};
}
if (failed(p.parseGreater())) return {};
if (timeStr != "immediate") {
p.emitError(p.getCurrentLocation(),
"only immediate timepoint attrs are supported");
return {};
}
return TimepointAttr::get(p.getContext(), TimepointType::get(p.getContext()));
}
void TimepointAttr::print(AsmPrinter &p) const {
p << "<";
p << "immediate";
p << ">";
}
//===----------------------------------------------------------------------===//
// #stream.affinity
//===----------------------------------------------------------------------===//
AffinityAttr AffinityAttr::lookup(Operation *op) {
auto attrId = StringAttr::get(op->getContext(), "stream.affinity");
while (op) {
if (auto affinityOp = llvm::dyn_cast<AffinityOpInterface>(op)) {
auto affinity = affinityOp.getAffinity();
if (affinity) return affinity;
}
auto attr = op->getAttrOfType<AffinityAttr>(attrId);
if (attr) return attr;
op = op->getParentOp();
}
return {}; // No affinity found; let caller decide what to do.
}
// static
bool AffinityAttr::areCompatible(AffinityAttr desiredAffinity,
AffinityAttr requiredAffinity) {
// We could do a fuzzier match here (interface isCompatible() etc).
return desiredAffinity == requiredAffinity;
}
//===----------------------------------------------------------------------===//
// #stream.partitioning_config
//===----------------------------------------------------------------------===//
void PartitioningConfigAttr::walkImmediateSubElements(
function_ref<void(Attribute)> walkAttrsFn,
function_ref<void(Type)> walkTypesFn) const {
walkAttrsFn(getFavor());
}
Attribute PartitioningConfigAttr::parse(AsmParser &p, Type type) {
std::string favorStr;
if (failed(p.parseLess())) return {};
if (succeeded(p.parseOptionalStar())) {
favorStr = "size";
} else if (failed(p.parseString(&favorStr))) {
return {};
}
if (failed(p.parseGreater())) return {};
auto favor = symbolizeFavor(favorStr);
if (!favor.hasValue()) {
p.emitError(p.getNameLoc(), "unknown favor value: ") << favorStr;
return {};
}
return PartitioningConfigAttr::get(
FavorAttr::get(p.getContext(), favor.getValue()));
}
void PartitioningConfigAttr::print(AsmPrinter &p) const {
p << "<";
p << "favor-";
p << stringifyFavor(getFavor().getValue());
p << ">";
}
PartitioningConfigAttr PartitioningConfigAttr::lookup(Operation *op) {
auto attrId = StringAttr::get(op->getContext(), "stream.partitioning");
while (op) {
auto attr = op->getAttrOfType<PartitioningConfigAttr>(attrId);
if (attr) return attr;
op = op->getParentOp();
}
// No config found; use defaults.
auto favorAttr = FavorAttr::get(attrId.getContext(), partitioningFavor);
return PartitioningConfigAttr::get(favorAttr);
}
//===----------------------------------------------------------------------===//
// !stream.resource<lifetime>
//===----------------------------------------------------------------------===//
static llvm::Optional<Lifetime> parseLifetime(StringRef str) {
if (str == "*") {
return Lifetime::Unknown;
} else if (str == "external") {
return Lifetime::External;
} else if (str == "staging") {
return Lifetime::Staging;
} else if (str == "transient") {
return Lifetime::Transient;
} else if (str == "variable") {
return Lifetime::Variable;
} else if (str == "constant") {
return Lifetime::Constant;
} else {
return llvm::None;
}
}
static void printLifetime(Lifetime lifetime, llvm::raw_ostream &os) {
if (lifetime == Lifetime::Unknown) {
os << "*";
} else {
os << stringifyLifetime(lifetime).lower();
}
}
Type ResourceType::parse(AsmParser &p) {
StringRef lifetimeStr;
if (failed(p.parseLess())) return {};
if (succeeded(p.parseOptionalStar())) {
lifetimeStr = "*";
} else if (failed(p.parseKeyword(&lifetimeStr))) {
return {};
}
if (failed(p.parseGreater())) return {};
auto lifetime = parseLifetime(lifetimeStr);
if (!lifetime.hasValue()) {
p.emitError(p.getNameLoc(), "unknown lifetime value: ") << lifetimeStr;
return {};
}
return ResourceType::get(p.getContext(), lifetime.getValue());
}
void ResourceType::print(AsmPrinter &p) const {
p << "<";
printLifetime(getLifetime(), p.getStream());
p << ">";
}
bool ResourceType::isAccessStorageCompatible(Type accessType) const {
if (auto resourceType = accessType.dyn_cast<ResourceType>()) {
// We could allow widening loads or stores here but today we require
// transfers to accomplish that.
return accessType == resourceType;
}
return accessType.isa<ShapedType>();
}
Value ResourceType::inferSizeFromValue(Location loc, Value value,
OpBuilder &builder) const {
return builder.createOrFold<IREE::Stream::ResourceSizeOp>(
loc, builder.getIndexType(), value);
}
//===----------------------------------------------------------------------===//
// Dialect registration
//===----------------------------------------------------------------------===//
#include "iree/compiler/Dialect/Stream/IR/StreamOpInterfaces.cpp.inc" // IWYU pragma: keep
#include "iree/compiler/Dialect/Stream/IR/StreamTypeInterfaces.cpp.inc" // IWYU pragma: keep
void StreamDialect::registerAttributes() {
// Register command line flags:
(void)partitioningFavor;
addAttributes<
#define GET_ATTRDEF_LIST
#include "iree/compiler/Dialect/Stream/IR/StreamAttrs.cpp.inc" // IWYU pragma: keep
>();
}
void StreamDialect::registerTypes() {
addTypes<
#define GET_TYPEDEF_LIST
#include "iree/compiler/Dialect/Stream/IR/StreamTypes.cpp.inc" // IWYU pragma: keep
>();
}
} // namespace Stream
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Expose a flag to control default stream alignment value. (#8518)<commit_after>// Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Dialect/Stream/IR/StreamTypes.h"
#include "iree/compiler/Dialect/Stream/IR/StreamOps.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/CommandLine.h"
#include "mlir/IR/DialectImplementation.h"
// clang-format off: must be included after all LLVM/MLIR headers.
#define GET_ATTRDEF_CLASSES
#include "iree/compiler/Dialect/Stream/IR/StreamAttrs.cpp.inc" // IWYU pragma: keep
#include "iree/compiler/Dialect/Stream/IR/StreamEnums.cpp.inc" // IWYU pragma: keep
#define GET_TYPEDEF_CLASSES
#include "iree/compiler/Dialect/Stream/IR/StreamTypes.cpp.inc" // IWYU pragma: keep
// clang-format on
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Stream {
static llvm::cl::opt<Favor> partitioningFavor(
"iree-stream-partitioning-favor",
llvm::cl::desc("Default stream partitioning favor configuration."),
llvm::cl::init(Favor::MaxConcurrency),
llvm::cl::values(
clEnumValN(Favor::Debug, "debug",
"Force debug partitioning (no concurrency or pipelining)."),
clEnumValN(Favor::MinPeakMemory, "min-peak-memory",
"Favor minimizing memory consumption at the cost of "
"additional concurrency."),
clEnumValN(Favor::MaxConcurrency, "max-concurrency",
"Favor maximizing concurrency at the cost of additional "
"memory consumption.")));
// TODO(#8506): remove the flag once the bug is fixed.
static llvm::cl::opt<uint64_t> streamDefaultBufferAlignment(
"iree-stream-default-buffer-alignment",
llvm::cl::desc("the default value of stream alignment"),
llvm::cl::init(64ull));
//===----------------------------------------------------------------------===//
// #stream.resource_config<...>
//===----------------------------------------------------------------------===//
// static
Attribute ResourceConfigAttr::parse(AsmParser &p, Type type) {
if (failed(p.parseLess()) || failed(p.parseLBrace())) return {};
int64_t maxAllocationSize = 0;
int64_t minBufferOffsetAlignment = 0;
int64_t maxBufferRange = 0;
int64_t minBufferRangeAlignment = 0;
while (failed(p.parseOptionalRBrace())) {
StringRef key;
int64_t value = 0;
if (failed(p.parseKeyword(&key)) || failed(p.parseEqual()) ||
failed(p.parseInteger(value))) {
return {};
}
if (key == "max_allocation_size") {
maxAllocationSize = value;
} else if (key == "min_buffer_offset_alignment") {
minBufferOffsetAlignment = value;
} else if (key == "max_buffer_range") {
maxBufferRange = value;
} else if (key == "min_buffer_range_alignment") {
minBufferRangeAlignment = value;
}
(void)p.parseOptionalComma();
}
if (failed(p.parseGreater())) return {};
return ResourceConfigAttr::get(p.getContext(), maxAllocationSize,
minBufferOffsetAlignment, maxBufferRange,
minBufferRangeAlignment);
}
void ResourceConfigAttr::print(AsmPrinter &p) const {
auto &os = p.getStream();
os << "<{";
os << "max_allocation_size = " << getMaxAllocationSize() << ", ";
os << "min_buffer_offset_alignment = " << getMinBufferOffsetAlignment()
<< ", ";
os << "max_buffer_range = " << getMaxBufferRange() << ", ";
os << "min_buffer_range_alignment = " << getMinBufferRangeAlignment();
os << "}>";
}
// static
ResourceConfigAttr ResourceConfigAttr::intersectBufferConstraints(
ResourceConfigAttr lhs, ResourceConfigAttr rhs) {
if (!lhs) return rhs;
if (!rhs) return lhs;
Builder b(lhs.getContext());
return ResourceConfigAttr::get(
b.getContext(),
std::min(lhs.getMaxAllocationSize(), rhs.getMaxAllocationSize()),
std::max(lhs.getMinBufferOffsetAlignment(),
rhs.getMinBufferOffsetAlignment()),
std::min(lhs.getMaxBufferRange(), rhs.getMaxBufferRange()),
std::max(lhs.getMinBufferRangeAlignment(),
rhs.getMinBufferRangeAlignment()));
}
// static
ResourceConfigAttr ResourceConfigAttr::getDefaultHostConstraints(
MLIRContext *context) {
// Picked to represent what we kind of want on CPU today.
// TODO(#8484): properly choose this value based on target devices. We don't
// yet have the device information up in stream and thus for targets that have
// high alignment requirements (128/256/etc) we are not picking the right
// value here.
uint64_t maxAllocationSize = UINT32_MAX;
uint64_t minBufferOffsetAlignment = streamDefaultBufferAlignment;
uint64_t maxBufferRange = UINT32_MAX;
uint64_t minBufferRangeAlignment = streamDefaultBufferAlignment;
return ResourceConfigAttr::get(context, maxAllocationSize,
minBufferOffsetAlignment, maxBufferRange,
minBufferRangeAlignment);
}
// TODO(benvanik): find a way to go affinity -> resource config.
// For now we just always fall back to the conservative host config.
static ResourceConfigAttr inferResourceConfigFromAffinity(
AffinityAttr affinityAttr) {
return {};
}
// static
ResourceConfigAttr ResourceConfigAttr::lookup(Operation *op) {
auto *context = op->getContext();
auto attrId = StringAttr::get(context, "stream.resources");
while (op) {
if (auto affinityOp = llvm::dyn_cast<AffinityOpInterface>(op)) {
auto affinityAttr = affinityOp.getAffinity();
if (affinityAttr) {
auto attr = inferResourceConfigFromAffinity(affinityAttr);
if (attr) return attr;
}
}
auto attr = op->getAttrOfType<ResourceConfigAttr>(attrId);
if (attr) return attr;
op = op->getParentOp();
}
// No config found; use conservative host config.
return getDefaultHostConstraints(context);
}
//===----------------------------------------------------------------------===//
// #stream.timepoint<...>
//===----------------------------------------------------------------------===//
Attribute TimepointAttr::parse(AsmParser &p, Type type) {
StringRef timeStr;
if (failed(p.parseLess())) return {};
if (failed(p.parseKeyword(&timeStr))) {
return {};
}
if (failed(p.parseGreater())) return {};
if (timeStr != "immediate") {
p.emitError(p.getCurrentLocation(),
"only immediate timepoint attrs are supported");
return {};
}
return TimepointAttr::get(p.getContext(), TimepointType::get(p.getContext()));
}
void TimepointAttr::print(AsmPrinter &p) const {
p << "<";
p << "immediate";
p << ">";
}
//===----------------------------------------------------------------------===//
// #stream.affinity
//===----------------------------------------------------------------------===//
AffinityAttr AffinityAttr::lookup(Operation *op) {
auto attrId = StringAttr::get(op->getContext(), "stream.affinity");
while (op) {
if (auto affinityOp = llvm::dyn_cast<AffinityOpInterface>(op)) {
auto affinity = affinityOp.getAffinity();
if (affinity) return affinity;
}
auto attr = op->getAttrOfType<AffinityAttr>(attrId);
if (attr) return attr;
op = op->getParentOp();
}
return {}; // No affinity found; let caller decide what to do.
}
// static
bool AffinityAttr::areCompatible(AffinityAttr desiredAffinity,
AffinityAttr requiredAffinity) {
// We could do a fuzzier match here (interface isCompatible() etc).
return desiredAffinity == requiredAffinity;
}
//===----------------------------------------------------------------------===//
// #stream.partitioning_config
//===----------------------------------------------------------------------===//
void PartitioningConfigAttr::walkImmediateSubElements(
function_ref<void(Attribute)> walkAttrsFn,
function_ref<void(Type)> walkTypesFn) const {
walkAttrsFn(getFavor());
}
Attribute PartitioningConfigAttr::parse(AsmParser &p, Type type) {
std::string favorStr;
if (failed(p.parseLess())) return {};
if (succeeded(p.parseOptionalStar())) {
favorStr = "size";
} else if (failed(p.parseString(&favorStr))) {
return {};
}
if (failed(p.parseGreater())) return {};
auto favor = symbolizeFavor(favorStr);
if (!favor.hasValue()) {
p.emitError(p.getNameLoc(), "unknown favor value: ") << favorStr;
return {};
}
return PartitioningConfigAttr::get(
FavorAttr::get(p.getContext(), favor.getValue()));
}
void PartitioningConfigAttr::print(AsmPrinter &p) const {
p << "<";
p << "favor-";
p << stringifyFavor(getFavor().getValue());
p << ">";
}
PartitioningConfigAttr PartitioningConfigAttr::lookup(Operation *op) {
auto attrId = StringAttr::get(op->getContext(), "stream.partitioning");
while (op) {
auto attr = op->getAttrOfType<PartitioningConfigAttr>(attrId);
if (attr) return attr;
op = op->getParentOp();
}
// No config found; use defaults.
auto favorAttr = FavorAttr::get(attrId.getContext(), partitioningFavor);
return PartitioningConfigAttr::get(favorAttr);
}
//===----------------------------------------------------------------------===//
// !stream.resource<lifetime>
//===----------------------------------------------------------------------===//
static llvm::Optional<Lifetime> parseLifetime(StringRef str) {
if (str == "*") {
return Lifetime::Unknown;
} else if (str == "external") {
return Lifetime::External;
} else if (str == "staging") {
return Lifetime::Staging;
} else if (str == "transient") {
return Lifetime::Transient;
} else if (str == "variable") {
return Lifetime::Variable;
} else if (str == "constant") {
return Lifetime::Constant;
} else {
return llvm::None;
}
}
static void printLifetime(Lifetime lifetime, llvm::raw_ostream &os) {
if (lifetime == Lifetime::Unknown) {
os << "*";
} else {
os << stringifyLifetime(lifetime).lower();
}
}
Type ResourceType::parse(AsmParser &p) {
StringRef lifetimeStr;
if (failed(p.parseLess())) return {};
if (succeeded(p.parseOptionalStar())) {
lifetimeStr = "*";
} else if (failed(p.parseKeyword(&lifetimeStr))) {
return {};
}
if (failed(p.parseGreater())) return {};
auto lifetime = parseLifetime(lifetimeStr);
if (!lifetime.hasValue()) {
p.emitError(p.getNameLoc(), "unknown lifetime value: ") << lifetimeStr;
return {};
}
return ResourceType::get(p.getContext(), lifetime.getValue());
}
void ResourceType::print(AsmPrinter &p) const {
p << "<";
printLifetime(getLifetime(), p.getStream());
p << ">";
}
bool ResourceType::isAccessStorageCompatible(Type accessType) const {
if (auto resourceType = accessType.dyn_cast<ResourceType>()) {
// We could allow widening loads or stores here but today we require
// transfers to accomplish that.
return accessType == resourceType;
}
return accessType.isa<ShapedType>();
}
Value ResourceType::inferSizeFromValue(Location loc, Value value,
OpBuilder &builder) const {
return builder.createOrFold<IREE::Stream::ResourceSizeOp>(
loc, builder.getIndexType(), value);
}
//===----------------------------------------------------------------------===//
// Dialect registration
//===----------------------------------------------------------------------===//
#include "iree/compiler/Dialect/Stream/IR/StreamOpInterfaces.cpp.inc" // IWYU pragma: keep
#include "iree/compiler/Dialect/Stream/IR/StreamTypeInterfaces.cpp.inc" // IWYU pragma: keep
void StreamDialect::registerAttributes() {
// Register command line flags:
(void)partitioningFavor;
addAttributes<
#define GET_ATTRDEF_LIST
#include "iree/compiler/Dialect/Stream/IR/StreamAttrs.cpp.inc" // IWYU pragma: keep
>();
}
void StreamDialect::registerTypes() {
addTypes<
#define GET_TYPEDEF_LIST
#include "iree/compiler/Dialect/Stream/IR/StreamTypes.cpp.inc" // IWYU pragma: keep
>();
}
} // namespace Stream
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, 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 the Willow Garage 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/planning_request_adapter/planning_request_adapter.h>
#include <moveit/trajectory_processing/iterative_time_parameterization.h>
#include <class_loader/class_loader.h>
#include <ros/console.h>
/*
#include <ReflexxesAPI.h>
#include <RMLPositionFlags.h>
#include <RMLPositionInputParameters.h>
#include <RMLPositionOutputParameters.h>
*/
namespace default_planner_request_adapters
{
class AddTimeParameterization : public planning_request_adapter::PlanningRequestAdapter
{
public:
AddTimeParameterization() : planning_request_adapter::PlanningRequestAdapter()
{
}
/*
void reflexxesComputeTime(robot_trajectory::RobotTrajectory &traj) const
{
boost::scoped_ptr<ReflexxesAPI> RML;
boost::scoped_ptr<RMLPositionInputParameters> IP;
boost::scoped_ptr<RMLPositionOutputParameters> OP;
RMLPositionFlags Flags;
// ********************************************************************
// Creating all relevant objects of the Reflexxes Motion Library
RML.reset(new ReflexxesAPI(7, 0.01));
IP.reset(new RMLPositionInputParameters(7));
OP.reset(new RMLPositionOutputParameters(7));
std::vector<double> v;
traj.getFirstWayPoint().getJointStateGroup(traj.getGroup()->getName())->getVariableValues(v);
for (int i = 0; i < 7 ; ++i)
{
IP->CurrentPositionVector->VecData [i] = v[i]; // rad
IP->CurrentVelocityVector->VecData [i] = 0.0 ; // rad/s
IP->CurrentAccelerationVector->VecData [i] = 0.0 ; // not needed for type 2
IP->MaxVelocityVector->VecData [i] = 1.5 ; // rad/s
IP->MaxAccelerationVector->VecData [i] = 1.0 ; //
IP->MaxJerkVector->VecData [i] = 0.1 ; // not needed for type 2
IP->TargetPositionVector->VecData [i] = v[i]; // first waypoint
IP->TargetVelocityVector->VecData [i] = 0.0 ; // velocity at first waypoint
IP->SelectionVector->VecData [i] = true ;
}
bool error = false;
for (std::size_t i = 1 ; !error && i < traj.getWayPointCount() ; ++i)
{
int ResultValue = 0;
double totalt = 0.0;
while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
{
// ****************************************************************
// Wait for the next timer tick
// (not implemented in this example in order to keep it simple)
// ****************************************************************
// Calling the Reflexxes OTG algorithm
ResultValue = RML->RMLPosition(*IP, OP.get(), Flags);
if (ResultValue < 0)
{
printf("An error occurred (%d).\n", ResultValue );
error = true;
break;
}
totalt += 0.01;
// ****************************************************************
// Here, the new state of motion, that is
//
// - OP->NewPositionVector
// - OP->NewVelocityVector
// - OP->NewAccelerationVector
//
// can be used as input values for lower level controllers. In the
// most simple case, a position controller in actuator space is
// used, but the computed state can be applied to many other
// controllers (e.g., Cartesian impedance controllers,
// operational space controllers).
// ****************************************************************
// ****************************************************************
// Feed the output values of the current control cycle back to
// input values of the next control cycle
*IP->CurrentPositionVector = *OP->NewPositionVector ;
*IP->CurrentVelocityVector = *OP->NewVelocityVector ;
*IP->CurrentAccelerationVector = *OP->NewAccelerationVector ;
}
std::cout << "T" << i << " :" << totalt << std::endl;
traj.setWayPointDurationFromPrevious(i, totalt);
traj.getWayPoint(i).getJointStateGroup(traj.getGroup()->getName())->getVariableValues(v);
for (int k = 0 ; k < 7 ; ++k)
IP->TargetPositionVector->VecData[k] = v[k];
}
}
*/
virtual std::string getDescription() const { return "Add Time Parameterization"; }
virtual bool adaptAndPlan(const PlannerFn &planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest &req,
planning_interface::MotionPlanResponse &res,
std::vector<std::size_t> &added_path_index) const
{
bool result = planner(planning_scene, req, res);
if (result && res.trajectory_)
{
ROS_DEBUG("Running '%s'", getDescription().c_str());
time_param_.computeTimeStamps(*res.trajectory_, req.start_state);
}
return result;
}
private:
trajectory_processing::IterativeParabolicTimeParameterization time_param_;
};
}
CLASS_LOADER_REGISTER_CLASS(default_planner_request_adapters::AddTimeParameterization,
planning_request_adapter::PlanningRequestAdapter);
<commit_msg>update API<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, 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 the Willow Garage 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.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/planning_request_adapter/planning_request_adapter.h>
#include <moveit/trajectory_processing/iterative_time_parameterization.h>
#include <class_loader/class_loader.h>
#include <ros/console.h>
/*
#include <ReflexxesAPI.h>
#include <RMLPositionFlags.h>
#include <RMLPositionInputParameters.h>
#include <RMLPositionOutputParameters.h>
*/
namespace default_planner_request_adapters
{
class AddTimeParameterization : public planning_request_adapter::PlanningRequestAdapter
{
public:
AddTimeParameterization() : planning_request_adapter::PlanningRequestAdapter()
{
}
/*
void reflexxesComputeTime(robot_trajectory::RobotTrajectory &traj) const
{
boost::scoped_ptr<ReflexxesAPI> RML;
boost::scoped_ptr<RMLPositionInputParameters> IP;
boost::scoped_ptr<RMLPositionOutputParameters> OP;
RMLPositionFlags Flags;
// ********************************************************************
// Creating all relevant objects of the Reflexxes Motion Library
RML.reset(new ReflexxesAPI(7, 0.01));
IP.reset(new RMLPositionInputParameters(7));
OP.reset(new RMLPositionOutputParameters(7));
std::vector<double> v;
traj.getFirstWayPoint().getJointStateGroup(traj.getGroup()->getName())->getVariableValues(v);
for (int i = 0; i < 7 ; ++i)
{
IP->CurrentPositionVector->VecData [i] = v[i]; // rad
IP->CurrentVelocityVector->VecData [i] = 0.0 ; // rad/s
IP->CurrentAccelerationVector->VecData [i] = 0.0 ; // not needed for type 2
IP->MaxVelocityVector->VecData [i] = 1.5 ; // rad/s
IP->MaxAccelerationVector->VecData [i] = 1.0 ; //
IP->MaxJerkVector->VecData [i] = 0.1 ; // not needed for type 2
IP->TargetPositionVector->VecData [i] = v[i]; // first waypoint
IP->TargetVelocityVector->VecData [i] = 0.0 ; // velocity at first waypoint
IP->SelectionVector->VecData [i] = true ;
}
bool error = false;
for (std::size_t i = 1 ; !error && i < traj.getWayPointCount() ; ++i)
{
int ResultValue = 0;
double totalt = 0.0;
while (ResultValue != ReflexxesAPI::RML_FINAL_STATE_REACHED)
{
// ****************************************************************
// Wait for the next timer tick
// (not implemented in this example in order to keep it simple)
// ****************************************************************
// Calling the Reflexxes OTG algorithm
ResultValue = RML->RMLPosition(*IP, OP.get(), Flags);
if (ResultValue < 0)
{
printf("An error occurred (%d).\n", ResultValue );
error = true;
break;
}
totalt += 0.01;
// ****************************************************************
// Here, the new state of motion, that is
//
// - OP->NewPositionVector
// - OP->NewVelocityVector
// - OP->NewAccelerationVector
//
// can be used as input values for lower level controllers. In the
// most simple case, a position controller in actuator space is
// used, but the computed state can be applied to many other
// controllers (e.g., Cartesian impedance controllers,
// operational space controllers).
// ****************************************************************
// ****************************************************************
// Feed the output values of the current control cycle back to
// input values of the next control cycle
*IP->CurrentPositionVector = *OP->NewPositionVector ;
*IP->CurrentVelocityVector = *OP->NewVelocityVector ;
*IP->CurrentAccelerationVector = *OP->NewAccelerationVector ;
}
std::cout << "T" << i << " :" << totalt << std::endl;
traj.setWayPointDurationFromPrevious(i, totalt);
traj.getWayPoint(i).getJointStateGroup(traj.getGroup()->getName())->getVariableValues(v);
for (int k = 0 ; k < 7 ; ++k)
IP->TargetPositionVector->VecData[k] = v[k];
}
}
*/
virtual std::string getDescription() const { return "Add Time Parameterization"; }
virtual bool adaptAndPlan(const PlannerFn &planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest &req,
planning_interface::MotionPlanResponse &res,
std::vector<std::size_t> &added_path_index) const
{
bool result = planner(planning_scene, req, res);
if (result && res.trajectory_)
{
ROS_DEBUG("Running '%s'", getDescription().c_str());
time_param_.computeTimeStamps(*res.trajectory_);
}
return result;
}
private:
trajectory_processing::IterativeParabolicTimeParameterization time_param_;
};
}
CLASS_LOADER_REGISTER_CLASS(default_planner_request_adapters::AddTimeParameterization,
planning_request_adapter::PlanningRequestAdapter);
<|endoftext|> |
<commit_before>#include "THClStorage.h"
#include "THClGeneral.h"
#include "THAtomic.h"
#include "THClKernels.h"
#include "EasyCL.h"
#include "templates/TemplatedKernel.h"
#include "util/StatefulTimer.h"
#include <stdexcept>
#include <iostream>
using namespace std;
static std::string getGetKernelSource();
static std::string getSetKernelSource();
//int state->trace = 0;
// this runs an entire kernel to get one value. Clearly this is going to be pretty slow, but
// at least it's more or less compatible, and comparable, to how cutorch does it
void THClStorage_set(THClState *state, THClStorage *self, long index, float value)
{
//// cout << "set size=" << self->size << " index=" << index << " value=" << value << endl;
THArgCheck((index >= 0) && (index < self->size), 2, "index out of bounds");
THArgCheck(self->wrapper != 0, 1, "storage argument not initialized, is empty");
// if( self->wrapper->isDeviceDirty() ) { // we have to do this, since we're going to copy it all back again
// // although I suppose we could set via a kernel perhaps
// // either way, this function is pretty inefficient right now :-P
// if(state->trace) cout << "wrapper->copyToHost() size " << self->size << endl;
// self->wrapper->copyToHost();
// }
// self->data[index] = value;
// if(state->trace) cout << "wrapper->copyToDevice() size " << self->size << endl;
// self->wrapper->copyToDevice();
const char *uniqueName = __FILE__ ":set";
EasyCL *cl = self->cl; // cant remember if this is a good idea or not :-P
CLKernel *kernel = 0;
if(cl->kernelExists(uniqueName)) {
kernel = cl->getKernel(uniqueName);
} else {
TemplatedKernel kernelBuilder(cl);
kernel = kernelBuilder.buildKernel( uniqueName, __FILE__, getSetKernelSource(), "THClStorageSet" );
}
kernel->inout(self->wrapper);
kernel->in(index);
kernel->in(value);
kernel->run_1d(1, 1);
if(state->addFinish) cl->finish();
}
// this runs an entire kernel to get one value. Clearly this is going to be pretty slow, but
// at least it's more or less compatible, and comparable, to how cutorch does it
// lgfgs expects a working implementation of this method
float THClStorage_get(THClState *state, const THClStorage *self, long index)
{
//// printf("THClStorage_get\n");
THArgCheck((index >= 0) && (index < self->size), 2, "index out of bounds");
THArgCheck(self->wrapper != 0, 1, "storage argument not initialized, is empty");
// if( self->wrapper->isDeviceDirty() ) {
// if(state->trace) cout << "wrapper->copyToHost()" << endl;
// self->wrapper->copyToHost();
// }
// return self->data[index];
const char *uniqueName = __FILE__ ":get";
EasyCL *cl = self->cl; // cant remember if this is a good idea or not :-P
CLKernel *kernel = 0;
if(cl->kernelExists(uniqueName)) {
kernel = cl->getKernel(uniqueName);
} else {
TemplatedKernel kernelBuilder(cl);
kernel = kernelBuilder.buildKernel( uniqueName, __FILE__, getGetKernelSource(), "THClStorageGet" );
}
float res;
kernel->out(1, &res);
kernel->in(self->wrapper);
kernel->in(index);
kernel->run_1d(1, 1);
if(state->addFinish) cl->finish();
return res;
}
THClStorage* THClStorage_new(THClState *state)
{
return THClStorage_newv2(state, state->currentDevice);
}
THClStorage* THClStorage_newv2(THClState *state, const int device)
{
THClStorage *storage = (THClStorage*)THAlloc(sizeof(THClStorage));
storage->device = device;
storage->cl = THClState_getClv2(state, storage->device);
// storage->device = -1;
storage->data = NULL;
storage->wrapper = 0;
storage->size = 0;
storage->refcount = 1;
storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE | TH_STORAGE_FREEMEM;
return storage;
}
THClStorage* THClStorage_newWithSize(THClState *state, int device, long size)
{
THArgCheck(size >= 0, 2, "invalid size");
if(size > 0)
{
StatefulTimer::timeCheck("THClStorage_newWithSize START");
THClStorage *storage = (THClStorage*)THAlloc(sizeof(THClStorage));
float *data = new float[size];
storage->device = device;
storage->cl = THClState_getClv2(state, storage->device);
CLWrapper *wrapper = storage->cl->wrap( size, data );
if(state->trace) cout << "new wrapper, size " << size << endl;
if(state->trace) cout << "wrapper->createOnDevice()" << endl;
wrapper->createOnDevice();
storage->data = data;
storage->wrapper = wrapper;
storage->size = size;
storage->refcount = 1;
storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE | TH_STORAGE_FREEMEM;
StatefulTimer::timeCheck("THClStorage_newWithSize END");
return storage;
}
else
{
return THClStorage_newv2(state, device);
}
}
THClStorage* THClStorage_newWithSize1(THClState *state, int device, float data0)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *self = THClStorage_newWithSize(state, 1);
// THClStorage_set(state, self, 0, data0);
// return self;
}
THClStorage* THClStorage_newWithSize2(THClState *state, int device, float data0, float data1)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *self = THClStorage_newWithSize(state, 2);
// THClStorage_set(state, self, 0, data0);
// THClStorage_set(state, self, 1, data1);
// return self;
}
THClStorage* THClStorage_newWithSize3(THClState *state, int device, float data0, float data1, float data2)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *self = THClStorage_newWithSize(state, 3);
// THClStorage_set(state, self, 0, data0);
// THClStorage_set(state, self, 1, data1);
// THClStorage_set(state, self, 2, data2);
// return self;
}
THClStorage* THClStorage_newWithSize4(THClState *state, int device, float data0, float data1, float data2, float data3)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *self = THClStorage_newWithSize(state, 4);
// THClStorage_set(state, self, 0, data0);
// THClStorage_set(state, self, 1, data1);
// THClStorage_set(state, self, 2, data2);
// THClStorage_set(state, self, 3, data3);
// return self;
}
THClStorage* THClStorage_newWithMapping(THClState *state, int device, const char *fileName, long size, int isShared)
{
THError("not available yet for THClStorage");
return NULL;
}
THClStorage* THClStorage_newWithData(THClState *state, int device, float *data, long size)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *storage = (THClStorage*)THAlloc(sizeof(THClStorage));
// storage->data = data;
// storage->size = size;
// storage->refcount = 1;
// storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE | TH_STORAGE_FREEMEM;
// return storage;
}
void THClStorage_retain(THClState *state, THClStorage *self)
{
if(self && (self->flag & TH_STORAGE_REFCOUNTED))
THAtomicIncrementRef(&self->refcount);
}
void THClStorage_free(THClState *state, THClStorage *self)
{
if(!(self->flag & TH_STORAGE_REFCOUNTED))
return;
if (THAtomicDecrementRef(&self->refcount))
{
if(self->flag & TH_STORAGE_FREEMEM) {
StatefulTimer::timeCheck("THClStorage_free START");
if(state->trace && self->size > 0) cout << "delete wrapper, size " << self->size << endl;
delete self->wrapper;
delete self->data;
StatefulTimer::timeCheck("THClStorage_newWithSize END");
}
THFree(self);
}
}
void THClStorage_fill(THClState *state, THClStorage *self, float value)
{
StatefulTimer::timeCheck("THClStorage_fill START");
for( int i = 0; i < self->size; i++ ) {
self->data[i] = value;
}
self->wrapper->copyToDevice();
if(state->trace) cout << "wrapper->copyToDevice() size" << self->size << endl;
StatefulTimer::timeCheck("THClStorage_fill END");
}
void THClStorage_resize(THClState *state, THClStorage *self, long size)
{
StatefulTimer::timeCheck("THClStorage_resize START");
if( size <= self->size ) {
return;
}
delete self->wrapper;
if(state->trace && self->size > 0) cout << "delete wrapper" << endl;
delete[] self->data;
self->data = new float[size];
EasyCL *cl = self->cl;
self->wrapper = cl->wrap( size, self->data );
self->wrapper->createOnDevice();
if(state->trace) cout << "new wrapper, size " << size << endl;
self->size = size;
StatefulTimer::timeCheck("THClStorage_resize END");
}
std::string getGetKernelSource() {
// [[[cog
// import stringify
// stringify.write_kernel( "kernel", "THClStorageGet.cl" )
// ]]]
// generated using cog, from THClStorageGet.cl:
const char * kernelSource =
"kernel void THClStorageGet(global float *res, global float *data, long index) {\n"
" if(get_global_id(0) == 0) {\n"
" res[0] = data[index];\n"
" }\n"
"}\n"
"\n"
"";
// [[[end]]]
return kernelSource;
}
std::string getSetKernelSource() {
// [[[cog
// import stringify
// stringify.write_kernel( "kernel", "THClStorageSet.cl" )
// ]]]
// generated using cog, from THClStorageSet.cl:
const char * kernelSource =
"kernel void THClStorageSet(global float *data, long index, float value) {\n"
" if(get_global_id(0) == 0) {\n"
" data[index] = value;\n"
" }\n"
"}\n"
"\n"
"";
// [[[end]]]
return kernelSource;
}
<commit_msg>experiment iwth int64_t for os x<commit_after>#include "THClStorage.h"
#include "THClGeneral.h"
#include "THAtomic.h"
#include "THClKernels.h"
#include "EasyCL.h"
#include "templates/TemplatedKernel.h"
#include "util/StatefulTimer.h"
#include <stdexcept>
#include <iostream>
using namespace std;
static std::string getGetKernelSource();
static std::string getSetKernelSource();
//int state->trace = 0;
// this runs an entire kernel to get one value. Clearly this is going to be pretty slow, but
// at least it's more or less compatible, and comparable, to how cutorch does it
void THClStorage_set(THClState *state, THClStorage *self, long index, float value)
{
//// cout << "set size=" << self->size << " index=" << index << " value=" << value << endl;
THArgCheck((index >= 0) && (index < self->size), 2, "index out of bounds");
THArgCheck(self->wrapper != 0, 1, "storage argument not initialized, is empty");
// if( self->wrapper->isDeviceDirty() ) { // we have to do this, since we're going to copy it all back again
// // although I suppose we could set via a kernel perhaps
// // either way, this function is pretty inefficient right now :-P
// if(state->trace) cout << "wrapper->copyToHost() size " << self->size << endl;
// self->wrapper->copyToHost();
// }
// self->data[index] = value;
// if(state->trace) cout << "wrapper->copyToDevice() size " << self->size << endl;
// self->wrapper->copyToDevice();
const char *uniqueName = __FILE__ ":set";
EasyCL *cl = self->cl; // cant remember if this is a good idea or not :-P
CLKernel *kernel = 0;
if(cl->kernelExists(uniqueName)) {
kernel = cl->getKernel(uniqueName);
} else {
TemplatedKernel kernelBuilder(cl);
kernel = kernelBuilder.buildKernel( uniqueName, __FILE__, getSetKernelSource(), "THClStorageSet" );
}
kernel->inout(self->wrapper);
kernel->in((int64_t)index);
kernel->in(value);
kernel->run_1d(1, 1);
if(state->addFinish) cl->finish();
}
// this runs an entire kernel to get one value. Clearly this is going to be pretty slow, but
// at least it's more or less compatible, and comparable, to how cutorch does it
// lgfgs expects a working implementation of this method
float THClStorage_get(THClState *state, const THClStorage *self, long index)
{
//// printf("THClStorage_get\n");
THArgCheck((index >= 0) && (index < self->size), 2, "index out of bounds");
THArgCheck(self->wrapper != 0, 1, "storage argument not initialized, is empty");
// if( self->wrapper->isDeviceDirty() ) {
// if(state->trace) cout << "wrapper->copyToHost()" << endl;
// self->wrapper->copyToHost();
// }
// return self->data[index];
const char *uniqueName = __FILE__ ":get";
EasyCL *cl = self->cl; // cant remember if this is a good idea or not :-P
CLKernel *kernel = 0;
if(cl->kernelExists(uniqueName)) {
kernel = cl->getKernel(uniqueName);
} else {
TemplatedKernel kernelBuilder(cl);
kernel = kernelBuilder.buildKernel( uniqueName, __FILE__, getGetKernelSource(), "THClStorageGet" );
}
float res;
kernel->out(1, &res);
kernel->in(self->wrapper);
kernel->in((int64_t)index);
kernel->run_1d(1, 1);
if(state->addFinish) cl->finish();
return res;
}
THClStorage* THClStorage_new(THClState *state)
{
return THClStorage_newv2(state, state->currentDevice);
}
THClStorage* THClStorage_newv2(THClState *state, const int device)
{
THClStorage *storage = (THClStorage*)THAlloc(sizeof(THClStorage));
storage->device = device;
storage->cl = THClState_getClv2(state, storage->device);
// storage->device = -1;
storage->data = NULL;
storage->wrapper = 0;
storage->size = 0;
storage->refcount = 1;
storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE | TH_STORAGE_FREEMEM;
return storage;
}
THClStorage* THClStorage_newWithSize(THClState *state, int device, long size)
{
THArgCheck(size >= 0, 2, "invalid size");
if(size > 0)
{
StatefulTimer::timeCheck("THClStorage_newWithSize START");
THClStorage *storage = (THClStorage*)THAlloc(sizeof(THClStorage));
float *data = new float[size];
storage->device = device;
storage->cl = THClState_getClv2(state, storage->device);
CLWrapper *wrapper = storage->cl->wrap( size, data );
if(state->trace) cout << "new wrapper, size " << size << endl;
if(state->trace) cout << "wrapper->createOnDevice()" << endl;
wrapper->createOnDevice();
storage->data = data;
storage->wrapper = wrapper;
storage->size = size;
storage->refcount = 1;
storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE | TH_STORAGE_FREEMEM;
StatefulTimer::timeCheck("THClStorage_newWithSize END");
return storage;
}
else
{
return THClStorage_newv2(state, device);
}
}
THClStorage* THClStorage_newWithSize1(THClState *state, int device, float data0)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *self = THClStorage_newWithSize(state, 1);
// THClStorage_set(state, self, 0, data0);
// return self;
}
THClStorage* THClStorage_newWithSize2(THClState *state, int device, float data0, float data1)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *self = THClStorage_newWithSize(state, 2);
// THClStorage_set(state, self, 0, data0);
// THClStorage_set(state, self, 1, data1);
// return self;
}
THClStorage* THClStorage_newWithSize3(THClState *state, int device, float data0, float data1, float data2)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *self = THClStorage_newWithSize(state, 3);
// THClStorage_set(state, self, 0, data0);
// THClStorage_set(state, self, 1, data1);
// THClStorage_set(state, self, 2, data2);
// return self;
}
THClStorage* THClStorage_newWithSize4(THClState *state, int device, float data0, float data1, float data2, float data3)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *self = THClStorage_newWithSize(state, 4);
// THClStorage_set(state, self, 0, data0);
// THClStorage_set(state, self, 1, data1);
// THClStorage_set(state, self, 2, data2);
// THClStorage_set(state, self, 3, data3);
// return self;
}
THClStorage* THClStorage_newWithMapping(THClState *state, int device, const char *fileName, long size, int isShared)
{
THError("not available yet for THClStorage");
return NULL;
}
THClStorage* THClStorage_newWithData(THClState *state, int device, float *data, long size)
{
THError("not available yet for THClStorage");
return NULL;
// THClStorage *storage = (THClStorage*)THAlloc(sizeof(THClStorage));
// storage->data = data;
// storage->size = size;
// storage->refcount = 1;
// storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE | TH_STORAGE_FREEMEM;
// return storage;
}
void THClStorage_retain(THClState *state, THClStorage *self)
{
if(self && (self->flag & TH_STORAGE_REFCOUNTED))
THAtomicIncrementRef(&self->refcount);
}
void THClStorage_free(THClState *state, THClStorage *self)
{
if(!(self->flag & TH_STORAGE_REFCOUNTED))
return;
if (THAtomicDecrementRef(&self->refcount))
{
if(self->flag & TH_STORAGE_FREEMEM) {
StatefulTimer::timeCheck("THClStorage_free START");
if(state->trace && self->size > 0) cout << "delete wrapper, size " << self->size << endl;
delete self->wrapper;
delete self->data;
StatefulTimer::timeCheck("THClStorage_newWithSize END");
}
THFree(self);
}
}
void THClStorage_fill(THClState *state, THClStorage *self, float value)
{
StatefulTimer::timeCheck("THClStorage_fill START");
for( int i = 0; i < self->size; i++ ) {
self->data[i] = value;
}
self->wrapper->copyToDevice();
if(state->trace) cout << "wrapper->copyToDevice() size" << self->size << endl;
StatefulTimer::timeCheck("THClStorage_fill END");
}
void THClStorage_resize(THClState *state, THClStorage *self, long size)
{
StatefulTimer::timeCheck("THClStorage_resize START");
if( size <= self->size ) {
return;
}
delete self->wrapper;
if(state->trace && self->size > 0) cout << "delete wrapper" << endl;
delete[] self->data;
self->data = new float[size];
EasyCL *cl = self->cl;
self->wrapper = cl->wrap( size, self->data );
self->wrapper->createOnDevice();
if(state->trace) cout << "new wrapper, size " << size << endl;
self->size = size;
StatefulTimer::timeCheck("THClStorage_resize END");
}
std::string getGetKernelSource() {
// [[[cog
// import stringify
// stringify.write_kernel( "kernel", "THClStorageGet.cl" )
// ]]]
// generated using cog, from THClStorageGet.cl:
const char * kernelSource =
"kernel void THClStorageGet(global float *res, global float *data, long index) {\n"
" if(get_global_id(0) == 0) {\n"
" res[0] = data[index];\n"
" }\n"
"}\n"
"\n"
"";
// [[[end]]]
return kernelSource;
}
std::string getSetKernelSource() {
// [[[cog
// import stringify
// stringify.write_kernel( "kernel", "THClStorageSet.cl" )
// ]]]
// generated using cog, from THClStorageSet.cl:
const char * kernelSource =
"kernel void THClStorageSet(global float *data, long index, float value) {\n"
" if(get_global_id(0) == 0) {\n"
" data[index] = value;\n"
" }\n"
"}\n"
"\n"
"";
// [[[end]]]
return kernelSource;
}
<|endoftext|> |
<commit_before>// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/*!
* @file AESGCMGMAC_Transform.cpp
*/
#include "AESGCMGMAC_Transform.h"
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <cstring>
using namespace eprosima::fastrtps::rtps::security;
AESGCMGMAC_Transform::AESGCMGMAC_Transform(){}
AESGCMGMAC_Transform::~AESGCMGMAC_Transform(){}
bool AESGCMGMAC_Transform::encode_serialized_payload(
std::vector<uint8_t> &encoded_buffer,
std::vector<uint8_t> &extra_inline_qos,
const std::vector<uint8_t> &plain_buffer,
const DatawriterCryptoHandle &sending_datawriter_crypto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::encode_datawriter_submessage(
std::vector<uint8_t> &encoded_rtps_submessage,
const std::vector<uint8_t> &plain_rtps_submessage,
const DatawriterCryptoHandle &sending_datawriter_crypto,
const std::vector<DatareaderCryptoHandle> receiving_datareader_crypto_list,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::encode_datareader_submessage(
std::vector<uint8_t> &encoded_rtps_submessage,
const std::vector<uint8_t> &plain_rtps_submessage,
const DatareaderCryptoHandle &sending_datareader_crypto,
const std::vector<DatawriterCryptoHandle> &receiving_datawriter_crypto_list,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::encode_rtps_message(
std::vector<uint8_t> &encoded_rtps_message,
const std::vector<uint8_t> &plain_rtps_message,
ParticipantCryptoHandle &sending_crypto,
const std::vector<ParticipantCryptoHandle*> &receiving_crypto_list,
SecurityException &exception){
AESGCMGMAC_ParticipantCryptoHandle& local_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(sending_crypto);
CipherData *m_cipherdata = nullptr;
//Step 1 - Find the CriptoData associated to the Participant
{
std::map<CryptoTransformKeyId,CipherData>::iterator it= status.find(local_participant->ParticipantKeyMaterial.sender_key_id);
if(it == status.end()){
//First time the Participant sends data - Init struct
CipherData new_data;
new_data.master_key_id = local_participant->ParticipantKeyMaterial.sender_key_id;
RAND_bytes( (unsigned char *)(&(new_data.session_id)), sizeof(uint16_t));
new_data.max_blocks_per_session= 12000;//TODO (Santi) - This ough to be configurable
new_data.session_block_counter= new_data.max_blocks_per_session; //Set to maximum so computation of new SessionKey is triggered
status[local_participant->ParticipantKeyMaterial.sender_key_id] = new_data;
it= status.find(local_participant->ParticipantKeyMaterial.sender_key_id);
m_cipherdata = &(it->second);
}else{
m_cipherdata = &(it->second);
}
}
//Step 2 - If the maximum number of blocks have been processed, generate a new SessionKey
if(m_cipherdata->session_block_counter >= m_cipherdata->max_blocks_per_session){
m_cipherdata->session_id += 1;
//Computation of SessionKey - Either because it has expired or because its the Participants first message
unsigned char *source = (unsigned char*)malloc(32 + 10 + 32 + 2);
memcpy(source, local_participant->ParticipantKeyMaterial.master_sender_key.data(), 32);
char seq[] = "SessionKey";
memcpy(source+32, seq, 10);
memcpy(source+32+10, local_participant->ParticipantKeyMaterial.master_salt.data(),32);
memcpy(source+32+10+32, &(m_cipherdata->session_id),4);
if(!EVP_Digest(source, 32+10+32+2, (unsigned char*)&(m_cipherdata->SessionKey), NULL, EVP_sha256(), NULL)){
//logError(CRYPTOGRAPHY, "Could not compute sha256");
delete(source);
return false;
}
delete(source);
//ReceiverSpecific keys shall be computed on site
m_cipherdata->session_block_counter = 0;
}
//Step 2.5 - Build remaining NONCE elements
uint64_t initialization_vector_suffix; //iv suffix changes with every operation
RAND_bytes( (unsigned char*)(&initialization_vector_suffix), sizeof(uint64_t) );
std::array<uint8_t,12> initialization_vector; //96 bytes, session_id + suffix
memcpy(initialization_vector.data(),&(m_cipherdata->session_id),4);
memcpy(initialization_vector.data()+4,&initialization_vector_suffix,8);
//Step 3 - Build SecureDataHeader
SecureDataHeader header;
header.transform_identifier.transformation_kind = local_participant->ParticipantKeyMaterial.transformation_kind;
header.transform_identifier.transformation_key_id = local_participant->ParticipantKeyMaterial.sender_key_id;
memcpy( &(header.session_id), &(m_cipherdata->session_id), 4);
memcpy( &(header.initialization_vector_suffix), &initialization_vector_suffix, 8);
//Step 4 -Cypher the plain rtps message -> SecureDataBody
OpenSSL_add_all_ciphers();
int rv = RAND_load_file("/dev/urandom", 32); //Init random number gen
size_t enc_length = plain_rtps_message.size()*3;
std::vector<uint8_t> output;
output.resize(enc_length,'\0');
unsigned char tag[AES_BLOCK_SIZE]; //Container for the Authentication Tag
int actual_size=0, final_size=0;
EVP_CIPHER_CTX* e_ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(e_ctx, EVP_aes_128_gcm(), (const unsigned char*)plain_rtps_message.data(), initialization_vector.data());
EVP_EncryptUpdate(e_ctx, output.data(), &actual_size, (const unsigned char*)plain_rtps_message.data(), plain_rtps_message.size());
EVP_EncryptFinal(e_ctx, output.data() + actual_size, &final_size);
EVP_CIPHER_CTX_ctrl(e_ctx, EVP_CTRL_GCM_GET_TAG, 16, tag);
output.resize(actual_size+final_size);
EVP_CIPHER_CTX_free(e_ctx);
//Step 4.5 - Copy the results into SecureDataBody
SecureDataBody body;
body.secure_data.resize(output.size());
memcpy(body.secure_data.data(),output.data(),output.size());
//Step 5 - Build Secure DataTag
SecureDataTag dataTag;
memcpy(dataTag.common_mac.data(),tag, 16);
//for(int i=0; i < no_macs; i++)
//tag.receiver_specific_macs; //Placeholder
//Step 5 - Assemble the message
encoded_rtps_message.clear();
//Header
for(int i=0;i < 4; i++) encoded_rtps_message.push_back( header.transform_identifier.transformation_kind.at(i) );
for(int i=0;i < 4; i++) encoded_rtps_message.push_back( header.transform_identifier.transformation_key_id.at(i) );
for(int i=0;i < 4; i++) encoded_rtps_message.push_back( header.session_id.at(i) );
for(int i=0;i < 8; i++) encoded_rtps_message.push_back( header.initialization_vector_suffix.at(i) );
//Body
//TODO (Santi) Set length
for(int i=0;i < body.secure_data.size();i++) encoded_rtps_message.push_back( body.secure_data.at(i) );
//Tag
for(int i=0;i < 16; i++) encoded_rtps_message.push_back( dataTag.common_mac.at(i) );
/*
for(int j=0; j< no_macs; j++){
//TODO (Santi) Set length
for(int i=0;
}
*/
return false;
}
bool AESGCMGMAC_Transform::decode_rtps_message(
std::vector<uint8_t> &plain_buffer,
const std::vector<uint8_t> &encoded_buffer,
const ParticipantCryptoHandle &receiving_crypto,
const ParticipantCryptoHandle &sending_crypto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::preprocess_secure_submsg(
DatawriterCryptoHandle &datawriter_crypto,
DatareaderCryptoHandle &datareader_crypto,
SecureSubmessageCategory_t &secure_submessage_category,
const std::vector<uint8_t> encoded_rtps_submessage,
const ParticipantCryptoHandle &receiving_crypto,
const ParticipantCryptoHandle &sending_crypto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::decode_datawriter_submessage(
std::vector<uint8_t> &plain_rtps_submessage,
const std::vector<uint8_t> &encoded_rtps_submessage,
const DatareaderCryptoHandle &receiving_datareader_crypto,
const DatawriterCryptoHandle &sending_datawriter_cryupto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::decode_datareader_submessage(
std::vector<uint8_t> &plain_rtps_submessage,
const std::vector<uint8_t> &encoded_rtps_submessage,
const DatawriterCryptoHandle &receiving_datawriter_crypto,
const DatareaderCryptoHandle &sending_datareader_crypto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::decode_serialized_payload(
std::vector<uint8_t> &plain_buffer,
const std::vector<uint8_t> &encoded_buffer,
const std::vector<uint8_t> &inline_qos,
const DatareaderCryptoHandle &receiving_datareader_crypto,
const DatawriterCryptoHandle &sending_datawriter_crypto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
<commit_msg>Deserialization of encrypted rtps message<commit_after>// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/*!
* @file AESGCMGMAC_Transform.cpp
*/
#include "AESGCMGMAC_Transform.h"
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <cstring>
using namespace eprosima::fastrtps::rtps::security;
AESGCMGMAC_Transform::AESGCMGMAC_Transform(){}
AESGCMGMAC_Transform::~AESGCMGMAC_Transform(){}
bool AESGCMGMAC_Transform::encode_serialized_payload(
std::vector<uint8_t> &encoded_buffer,
std::vector<uint8_t> &extra_inline_qos,
const std::vector<uint8_t> &plain_buffer,
const DatawriterCryptoHandle &sending_datawriter_crypto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::encode_datawriter_submessage(
std::vector<uint8_t> &encoded_rtps_submessage,
const std::vector<uint8_t> &plain_rtps_submessage,
const DatawriterCryptoHandle &sending_datawriter_crypto,
const std::vector<DatareaderCryptoHandle> receiving_datareader_crypto_list,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::encode_datareader_submessage(
std::vector<uint8_t> &encoded_rtps_submessage,
const std::vector<uint8_t> &plain_rtps_submessage,
const DatareaderCryptoHandle &sending_datareader_crypto,
const std::vector<DatawriterCryptoHandle> &receiving_datawriter_crypto_list,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::encode_rtps_message(
std::vector<uint8_t> &encoded_rtps_message,
const std::vector<uint8_t> &plain_rtps_message,
ParticipantCryptoHandle &sending_crypto,
const std::vector<ParticipantCryptoHandle*> &receiving_crypto_list,
SecurityException &exception){
AESGCMGMAC_ParticipantCryptoHandle& local_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(sending_crypto);
CipherData *m_cipherdata = nullptr;
//Step 1 - Find the CriptoData associated to the Participant
{
std::map<CryptoTransformKeyId,CipherData>::iterator it= status.find(local_participant->ParticipantKeyMaterial.sender_key_id);
if(it == status.end()){
//First time the Participant sends data - Init struct
CipherData new_data;
new_data.master_key_id = local_participant->ParticipantKeyMaterial.sender_key_id;
RAND_bytes( (unsigned char *)(&(new_data.session_id)), sizeof(uint16_t));
new_data.max_blocks_per_session= 12000;//TODO (Santi) - This ough to be configurable
new_data.session_block_counter= new_data.max_blocks_per_session; //Set to maximum so computation of new SessionKey is triggered
status[local_participant->ParticipantKeyMaterial.sender_key_id] = new_data;
it= status.find(local_participant->ParticipantKeyMaterial.sender_key_id);
m_cipherdata = &(it->second);
}else{
m_cipherdata = &(it->second);
}
}
//Step 2 - If the maximum number of blocks have been processed, generate a new SessionKey
if(m_cipherdata->session_block_counter >= m_cipherdata->max_blocks_per_session){
m_cipherdata->session_id += 1;
//Computation of SessionKey - Either because it has expired or because its the Participants first message
unsigned char *source = (unsigned char*)malloc(32 + 10 + 32 + 2);
memcpy(source, local_participant->ParticipantKeyMaterial.master_sender_key.data(), 32);
char seq[] = "SessionKey";
memcpy(source+32, seq, 10);
memcpy(source+32+10, local_participant->ParticipantKeyMaterial.master_salt.data(),32);
memcpy(source+32+10+32, &(m_cipherdata->session_id),4);
if(!EVP_Digest(source, 32+10+32+2, (unsigned char*)&(m_cipherdata->SessionKey), NULL, EVP_sha256(), NULL)){
//logError(CRYPTOGRAPHY, "Could not compute sha256");
delete(source);
return false;
}
delete(source);
//ReceiverSpecific keys shall be computed on site
m_cipherdata->session_block_counter = 0;
}
//Step 2.5 - Build remaining NONCE elements
uint64_t initialization_vector_suffix; //iv suffix changes with every operation
RAND_bytes( (unsigned char*)(&initialization_vector_suffix), sizeof(uint64_t) );
std::array<uint8_t,12> initialization_vector; //96 bytes, session_id + suffix
memcpy(initialization_vector.data(),&(m_cipherdata->session_id),4);
memcpy(initialization_vector.data()+4,&initialization_vector_suffix,8);
//Step 3 - Build SecureDataHeader
SecureDataHeader header;
header.transform_identifier.transformation_kind = local_participant->ParticipantKeyMaterial.transformation_kind;
header.transform_identifier.transformation_key_id = local_participant->ParticipantKeyMaterial.sender_key_id;
memcpy( &(header.session_id), &(m_cipherdata->session_id), 4);
memcpy( &(header.initialization_vector_suffix), &initialization_vector_suffix, 8);
//Step 4 -Cypher the plain rtps message -> SecureDataBody
OpenSSL_add_all_ciphers();
int rv = RAND_load_file("/dev/urandom", 32); //Init random number gen
size_t enc_length = plain_rtps_message.size()*3;
std::vector<uint8_t> output;
output.resize(enc_length,'\0');
unsigned char tag[AES_BLOCK_SIZE]; //Container for the Authentication Tag
int actual_size=0, final_size=0;
EVP_CIPHER_CTX* e_ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(e_ctx, EVP_aes_128_gcm(), (const unsigned char*)plain_rtps_message.data(), initialization_vector.data());
EVP_EncryptUpdate(e_ctx, output.data(), &actual_size, (const unsigned char*)plain_rtps_message.data(), plain_rtps_message.size());
EVP_EncryptFinal(e_ctx, output.data() + actual_size, &final_size);
EVP_CIPHER_CTX_ctrl(e_ctx, EVP_CTRL_GCM_GET_TAG, 16, tag);
output.resize(actual_size+final_size);
EVP_CIPHER_CTX_free(e_ctx);
//Step 4.5 - Copy the results into SecureDataBody
SecureDataBody body;
body.secure_data.resize(output.size());
memcpy(body.secure_data.data(),output.data(),output.size());
//Step 5 - Build Secure DataTag
SecureDataTag dataTag;
memcpy(dataTag.common_mac.data(),tag, 16);
//for(int i=0; i < no_macs; i++)
//tag.receiver_specific_macs; //Placeholder
//Step 5 - Assemble the message
encoded_rtps_message.clear();
//Header
for(int i=0;i < 4; i++) encoded_rtps_message.push_back( header.transform_identifier.transformation_kind.at(i) );
for(int i=0;i < 4; i++) encoded_rtps_message.push_back( header.transform_identifier.transformation_key_id.at(i) );
for(int i=0;i < 4; i++) encoded_rtps_message.push_back( header.session_id.at(i) );
for(int i=0;i < 8; i++) encoded_rtps_message.push_back( header.initialization_vector_suffix.at(i) );
//Body
long body_length = body.secure_data.size();
for(int i=0;i < sizeof(long); i++) encoded_rtps_message.push_back( *( (uint8_t*)&body_length + i) );
for(int i=0;i < body_length;i++) encoded_rtps_message.push_back( body.secure_data.at(i) );
//Tag
for(int i=0;i < 16; i++) encoded_rtps_message.push_back( dataTag.common_mac.at(i) );
//TODO (Santi) Deal with receiver_specific MACs
/*
for(int j=0; j< no_macs; j++){
//TODO (Santi) Set length
for(int i=0;
}
*/
return true;
}
bool AESGCMGMAC_Transform::decode_rtps_message(
std::vector<uint8_t> &plain_buffer,
const std::vector<uint8_t> &encoded_buffer,
const ParticipantCryptoHandle &receiving_crypto,
const ParticipantCryptoHandle &sending_crypto,
SecurityException &exception){
//Fun reverse order process;
SecureDataHeader header;
SecureDataBody body;
SecureDataTag tag;
//Header
for(int i=0;i<4;i++) header.transform_identifier.transformation_kind.at(i) = ( encoded_buffer.at( i ) );
for(int i=0;i<4;i++) header.transform_identifier.transformation_key_id.at(i) = ( encoded_buffer.at( i+4 ) );
for(int i=0;i<4;i++) header.session_id.at(i) = ( encoded_buffer.at( i+8 ) );
for(int i=0;i<8;i++) header.initialization_vector_suffix.at(i) = ( encoded_buffer.at( i+12 ) );
//Body
long body_length = 0;
memcpy(&body_length, encoded_buffer.data()+20, sizeof(long));
for(int i=0;i < body_length; i++) body.secure_data.push_back( encoded_buffer.at( i+20+sizeof(long) ) );
//Tag
for(int i=0;i < 16; i++) tag.common_mac.at(i) = ( encoded_buffer.at( i+20+sizeof(long)+body_length ) );
//TODO (Santi) Deal with receiver_specific MACs
//Auth message
//Decode message
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::preprocess_secure_submsg(
DatawriterCryptoHandle &datawriter_crypto,
DatareaderCryptoHandle &datareader_crypto,
SecureSubmessageCategory_t &secure_submessage_category,
const std::vector<uint8_t> encoded_rtps_submessage,
const ParticipantCryptoHandle &receiving_crypto,
const ParticipantCryptoHandle &sending_crypto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::decode_datawriter_submessage(
std::vector<uint8_t> &plain_rtps_submessage,
const std::vector<uint8_t> &encoded_rtps_submessage,
const DatareaderCryptoHandle &receiving_datareader_crypto,
const DatawriterCryptoHandle &sending_datawriter_cryupto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::decode_datareader_submessage(
std::vector<uint8_t> &plain_rtps_submessage,
const std::vector<uint8_t> &encoded_rtps_submessage,
const DatawriterCryptoHandle &receiving_datawriter_crypto,
const DatareaderCryptoHandle &sending_datareader_crypto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
bool AESGCMGMAC_Transform::decode_serialized_payload(
std::vector<uint8_t> &plain_buffer,
const std::vector<uint8_t> &encoded_buffer,
const std::vector<uint8_t> &inline_qos,
const DatareaderCryptoHandle &receiving_datareader_crypto,
const DatawriterCryptoHandle &sending_datawriter_crypto,
SecurityException &exception){
exception = SecurityException("Not implemented");
return false;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2005-2009, Thorvald Natvig <thorvald@natvig.com>
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.
*/
#include "UserModel.h"
#include "UserView.h"
#include "MainWindow.h"
#include "ClientUser.h"
#include "Channel.h"
#include "ServerHandler.h"
#include "Log.h"
#include "Global.h"
/*!
\fn bool UserView::event(QEvent *evt)
This implementation contains a special handler to display
custom what's this entries for items. All other events are
passed on.
*/
/*!
\fn void UserView::mouseReleaseEvent(QMouseEvent *evt)
This function is used to create custom behaviour when clicking
on user/channel flags (e.g. showing the comment)
*/
/*!
\fn void UserView::keyboardSearch(const QString &search)
This implementation provides a recursive realtime search over
the whole channel tree. It also features delayed selection
with with automatic expanding of folded channels.
*/
UserDelegate::UserDelegate(QObject *p) : QStyledItemDelegate(p) {
}
void UserDelegate::paint(QPainter * painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
const QAbstractItemModel *m = index.model();
const QModelIndex idxc1 = index.sibling(index.row(), 1);
QVariant data = m->data(idxc1);
QList<QVariant> ql = data.toList();
painter->save();
QStyleOptionViewItemV4 o = option;
initStyleOption(&o, index);
// draw background
o.widget->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &o, painter, o.widget);
// resize rect to exclude the flag icons
o.rect = option.rect.adjusted(0, 0, -18 * ql.count(), 0);
// remove focus state
o.state &= ~QStyle::State_Selected;
o.state &= ~QStyle::State_MouseOver;
o.widget->style()->drawControl(QStyle::CE_ItemViewItem, &o, painter, o.widget);
QRect ps = QRect(option.rect.right() - (ql.size() * 18), option.rect.y(), ql.size() * 18, option.rect.height());
for (int i = 0; i < ql.size(); ++i) {
QRect r = ps;
r.setSize(QSize(16, 16));
r.translate(i * 18 + 1, 1);
QPixmap pixmap = (qvariant_cast<QIcon>(ql[i]).pixmap(QSize(16, 16)));
QPoint p = QStyle::alignedRect(option.direction, option.decorationAlignment, pixmap.size(), r).topLeft();
painter->drawPixmap(p, pixmap);
}
painter->restore();
}
bool UserDelegate::helpEvent(QHelpEvent *evt, QAbstractItemView *view, const QStyleOptionViewItem &option, const QModelIndex &index) {
if (index.isValid()) {
const QAbstractItemModel *m = index.model();
const QModelIndex idxc1 = index.sibling(index.row(), 1);
QVariant data = m->data(idxc1);
QList<QVariant> ql = data.toList();
int offset = 0;
offset = ql.size() * 18;
offset = option.rect.topRight().x() - offset;
if (evt->pos().x() >= offset) {
return QStyledItemDelegate::helpEvent(evt, view, option, idxc1);
}
}
return QStyledItemDelegate::helpEvent(evt, view, option, index);
}
UserView::UserView(QWidget *p) : QTreeView(p) {
setItemDelegate(new UserDelegate(this));
qtSearch = new QTimer(this);
qtSearch->setInterval(QApplication::keyboardInputInterval());
qtSearch->setSingleShot(true);
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(contextMenu(const QPoint &)));
connect(this, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(doubleClick(const QModelIndex &)));
connect(qtSearch, SIGNAL(timeout()), this, SLOT(selectSearchResult()));
}
bool UserView::event(QEvent *evt) {
if (evt->type() == QEvent::WhatsThisClicked) {
QWhatsThisClickedEvent *qwtce = static_cast<QWhatsThisClickedEvent *>(evt);
QDesktopServices::openUrl(qwtce->href());
evt->accept();
return true;
}
return QTreeView::event(evt);
}
void UserView::mouseReleaseEvent(QMouseEvent *evt) {
QPoint qpos = evt->pos();
QModelIndex idx = indexAt(qpos);
if ((evt->button() == Qt::LeftButton) && idx.isValid()) {
UserModel *um = static_cast<UserModel *>(model());
ClientUser *cu = um->getUser(idx);
Channel * c = um->getChannel(idx);
if ((cu && ! cu->qsComment.isEmpty()) ||
(! cu && c && ! c->qsDesc.isEmpty())) {
QRect r = visualRect(idx);
int offset = 18;
if (cu) {
// Calculate pixel offset of comment flag
if (cu->bMute)
offset += 18;
if (cu->bSuppress)
offset += 18;
if (cu->bSelfMute)
offset += 18;
if (cu->bLocalMute)
offset += 18;
if (cu->bSelfDeaf)
offset += 18;
if (cu->bDeaf)
offset += 18;
if (! cu->qsFriendName.isEmpty())
offset += 18;
if (cu->iId >= 0)
offset += 18;
}
offset = r.topRight().x() - offset;
if ((qpos.x() >= offset) && (qpos.x() <= (offset+18))) {
// Clicked on comment flag
QWhatsThis::showText(viewport()->mapToGlobal(r.bottomRight()), Log::validHtml(cu ? cu->qsComment : c->qsDesc), this);
um->seenComment(idx);
return;
}
}
}
QTreeView::mouseReleaseEvent(evt);
}
void UserView::contextMenu(const QPoint &mpos) {
UserModel *um = static_cast<UserModel *>(model());
QModelIndex idx = indexAt(mpos);
if (! idx.isValid())
idx = currentIndex();
else
setCurrentIndex(idx);
User *p = um->getUser(idx);
if (p) {
g.mw->qmUser->popup(mapToGlobal(mpos), g.mw->qaUserMute);
} else {
g.mw->qmChannel->popup(mapToGlobal(mpos), g.mw->qaChannelACL);
}
}
void UserView::doubleClick(const QModelIndex &idx) {
UserModel *um = static_cast<UserModel *>(model());
User *p = um->getUser(idx);
if (p) {
g.mw->on_qaUserTextMessage_triggered();
return;
}
Channel *c = um->getChannel(idx);
if (c) {
// if a channel is double clicked join it
MumbleProto::UserState mpus;
mpus.set_session(g.uiSession);
mpus.set_channel_id(c->iId);
g.sh->sendMessage(mpus);
}
}
void UserView::keyboardSearch(const QString &search) {
if (qtSearch->isActive()) {
qpmiSearch = QPersistentModelIndex();
qtSearch->stop();
}
bool forceSkip = false;
if (tSearch.restart() > (QApplication::keyboardInputInterval() * 1000ULL)) {
qsSearch = QString();
forceSkip = true;
}
bool isBackspace = (search.length() == 1) && (search.at(0).row() == 0) && (search.at(0).cell() == 8);
if (isBackspace) {
if (! qsSearch.isEmpty())
qsSearch = qsSearch.left(qsSearch.length()-1);
} else {
qsSearch += search;
}
// Try default search (which doesn't recurse non-expanded items) and see if it returns something "valid"
QTreeView::keyboardSearch(search);
QModelIndex start = currentIndex();
if (start.isValid() && model()->data(start, Qt::DisplayRole).toString().startsWith(qsSearch, Qt::CaseInsensitive))
return;
if (forceSkip && start.isValid())
start = indexBelow(start);
if (! start.isValid())
start = model()->index(0, 0, QModelIndex());
QModelIndexList qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchStartsWith | Qt::MatchWrap | Qt::MatchRecursive));
if (qmil.count() == 0)
qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchContains | Qt::MatchWrap | Qt::MatchRecursive));
if (qmil.isEmpty())
return;
QModelIndex qmi = qmil.at(0);
QModelIndex p = qmi.parent();
bool visible = true;
while (visible && p.isValid()) {
visible = visible && isExpanded(p);
p = p.parent();
}
if (visible)
selectionModel()->setCurrentIndex(qmi, QItemSelectionModel::ClearAndSelect);
else {
qpmiSearch = qmi;
qtSearch->start();
}
}
void UserView::selectSearchResult() {
if (qpmiSearch.isValid()) {
selectionModel()->setCurrentIndex(qpmiSearch, QItemSelectionModel::ClearAndSelect);
}
qpmiSearch = QPersistentModelIndex();
}
<commit_msg>Rewrite UserView drawing code<commit_after>/* Copyright (C) 2005-2009, Thorvald Natvig <thorvald@natvig.com>
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.
*/
#include "UserModel.h"
#include "UserView.h"
#include "MainWindow.h"
#include "ClientUser.h"
#include "Channel.h"
#include "ServerHandler.h"
#include "Log.h"
#include "Global.h"
/*!
\fn bool UserView::event(QEvent *evt)
This implementation contains a special handler to display
custom what's this entries for items. All other events are
passed on.
*/
/*!
\fn void UserView::mouseReleaseEvent(QMouseEvent *evt)
This function is used to create custom behaviour when clicking
on user/channel flags (e.g. showing the comment)
*/
/*!
\fn void UserView::keyboardSearch(const QString &search)
This implementation provides a recursive realtime search over
the whole channel tree. It also features delayed selection
with with automatic expanding of folded channels.
*/
UserDelegate::UserDelegate(QObject *p) : QStyledItemDelegate(p) {
}
void UserDelegate::paint(QPainter * painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
const QAbstractItemModel *m = index.model();
const QModelIndex idxc1 = index.sibling(index.row(), 1);
QVariant data = m->data(idxc1);
QList<QVariant> ql = data.toList();
painter->save();
QStyleOptionViewItemV4 o = option;
initStyleOption(&o, index);
// draw background
o.widget->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &o, painter, o.widget);
// resize rect to exclude the flag icons
o.rect = option.rect.adjusted(0, 0, -18 * ql.count(), 0);
QIcon::Mode iMode = ((o.state & QStyle::State_Selected) ? QIcon::Selected : QIcon::Normal);
// draw icon
QIcon iP = qvariant_cast<QIcon>(m->data(index, Qt::DecorationRole));
QRect pR = o.widget->style()->subElementRect(QStyle::SE_ItemViewItemDecoration, &o, o.widget);
iP.paint(painter, pR, o.decorationAlignment, iMode, QIcon::On);
// draw text
QFont iF = qvariant_cast<QFont>(m->data(index, Qt::FontRole));
QRect tR = o.widget->style()->subElementRect(QStyle::SE_ItemViewItemText, &o, o.widget);
painter->setFont(iF);
QString iT = painter->fontMetrics().elidedText(qvariant_cast<QString>(m->data(index)), static_cast<const QTreeWidget *>(o.widget)->textElideMode(), tR.width());
o.widget->style()->drawItemText(painter, tR, o.displayAlignment, o.widget->palette(), true, iT, ((o.state & QStyle::State_Selected) ? QPalette::HighlightedText : QPalette::Text));
// draw flag icons
QRect ps = QRect(option.rect.right() - (ql.size() * 18), option.rect.y(), ql.size() * 18, option.rect.height());
for (int i = 0; i < ql.size(); ++i) {
QRect r = ps;
r.setSize(QSize(16, 16));
r.translate(i * 18 + 1, 1);
QRect p = QStyle::alignedRect(option.direction, option.decorationAlignment, r.size(), r);
qvariant_cast<QIcon>(ql[i]).paint(painter, p, option.decorationAlignment, iMode, QIcon::On);
}
painter->restore();
}
bool UserDelegate::helpEvent(QHelpEvent *evt, QAbstractItemView *view, const QStyleOptionViewItem &option, const QModelIndex &index) {
if (index.isValid()) {
const QAbstractItemModel *m = index.model();
const QModelIndex idxc1 = index.sibling(index.row(), 1);
QVariant data = m->data(idxc1);
QList<QVariant> ql = data.toList();
int offset = 0;
offset = ql.size() * 18;
offset = option.rect.topRight().x() - offset;
if (evt->pos().x() >= offset) {
return QStyledItemDelegate::helpEvent(evt, view, option, idxc1);
}
}
return QStyledItemDelegate::helpEvent(evt, view, option, index);
}
UserView::UserView(QWidget *p) : QTreeView(p) {
setItemDelegate(new UserDelegate(this));
qtSearch = new QTimer(this);
qtSearch->setInterval(QApplication::keyboardInputInterval());
qtSearch->setSingleShot(true);
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(contextMenu(const QPoint &)));
connect(this, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(doubleClick(const QModelIndex &)));
connect(qtSearch, SIGNAL(timeout()), this, SLOT(selectSearchResult()));
}
bool UserView::event(QEvent *evt) {
if (evt->type() == QEvent::WhatsThisClicked) {
QWhatsThisClickedEvent *qwtce = static_cast<QWhatsThisClickedEvent *>(evt);
QDesktopServices::openUrl(qwtce->href());
evt->accept();
return true;
}
return QTreeView::event(evt);
}
void UserView::mouseReleaseEvent(QMouseEvent *evt) {
QPoint qpos = evt->pos();
QModelIndex idx = indexAt(qpos);
if ((evt->button() == Qt::LeftButton) && idx.isValid()) {
UserModel *um = static_cast<UserModel *>(model());
ClientUser *cu = um->getUser(idx);
Channel * c = um->getChannel(idx);
if ((cu && ! cu->qsComment.isEmpty()) ||
(! cu && c && ! c->qsDesc.isEmpty())) {
QRect r = visualRect(idx);
int offset = 18;
if (cu) {
// Calculate pixel offset of comment flag
if (cu->bMute)
offset += 18;
if (cu->bSuppress)
offset += 18;
if (cu->bSelfMute)
offset += 18;
if (cu->bLocalMute)
offset += 18;
if (cu->bSelfDeaf)
offset += 18;
if (cu->bDeaf)
offset += 18;
if (! cu->qsFriendName.isEmpty())
offset += 18;
if (cu->iId >= 0)
offset += 18;
}
offset = r.topRight().x() - offset;
if ((qpos.x() >= offset) && (qpos.x() <= (offset+18))) {
// Clicked on comment flag
QWhatsThis::showText(viewport()->mapToGlobal(r.bottomRight()), Log::validHtml(cu ? cu->qsComment : c->qsDesc), this);
um->seenComment(idx);
return;
}
}
}
QTreeView::mouseReleaseEvent(evt);
}
void UserView::contextMenu(const QPoint &mpos) {
UserModel *um = static_cast<UserModel *>(model());
QModelIndex idx = indexAt(mpos);
if (! idx.isValid())
idx = currentIndex();
else
setCurrentIndex(idx);
User *p = um->getUser(idx);
if (p) {
g.mw->qmUser->popup(mapToGlobal(mpos), g.mw->qaUserMute);
} else {
g.mw->qmChannel->popup(mapToGlobal(mpos), g.mw->qaChannelACL);
}
}
void UserView::doubleClick(const QModelIndex &idx) {
UserModel *um = static_cast<UserModel *>(model());
User *p = um->getUser(idx);
if (p) {
g.mw->on_qaUserTextMessage_triggered();
return;
}
Channel *c = um->getChannel(idx);
if (c) {
// if a channel is double clicked join it
MumbleProto::UserState mpus;
mpus.set_session(g.uiSession);
mpus.set_channel_id(c->iId);
g.sh->sendMessage(mpus);
}
}
void UserView::keyboardSearch(const QString &search) {
if (qtSearch->isActive()) {
qpmiSearch = QPersistentModelIndex();
qtSearch->stop();
}
bool forceSkip = false;
if (tSearch.restart() > (QApplication::keyboardInputInterval() * 1000ULL)) {
qsSearch = QString();
forceSkip = true;
}
bool isBackspace = (search.length() == 1) && (search.at(0).row() == 0) && (search.at(0).cell() == 8);
if (isBackspace) {
if (! qsSearch.isEmpty())
qsSearch = qsSearch.left(qsSearch.length()-1);
} else {
qsSearch += search;
}
// Try default search (which doesn't recurse non-expanded items) and see if it returns something "valid"
QTreeView::keyboardSearch(search);
QModelIndex start = currentIndex();
if (start.isValid() && model()->data(start, Qt::DisplayRole).toString().startsWith(qsSearch, Qt::CaseInsensitive))
return;
if (forceSkip && start.isValid())
start = indexBelow(start);
if (! start.isValid())
start = model()->index(0, 0, QModelIndex());
QModelIndexList qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchStartsWith | Qt::MatchWrap | Qt::MatchRecursive));
if (qmil.count() == 0)
qmil = model()->match(start, Qt::DisplayRole, qsSearch, 1, Qt::MatchFlags(Qt::MatchContains | Qt::MatchWrap | Qt::MatchRecursive));
if (qmil.isEmpty())
return;
QModelIndex qmi = qmil.at(0);
QModelIndex p = qmi.parent();
bool visible = true;
while (visible && p.isValid()) {
visible = visible && isExpanded(p);
p = p.parent();
}
if (visible)
selectionModel()->setCurrentIndex(qmi, QItemSelectionModel::ClearAndSelect);
else {
qpmiSearch = qmi;
qtSearch->start();
}
}
void UserView::selectSearchResult() {
if (qpmiSearch.isValid()) {
selectionModel()->setCurrentIndex(qpmiSearch, QItemSelectionModel::ClearAndSelect);
}
qpmiSearch = QPersistentModelIndex();
}
<|endoftext|> |
<commit_before>#include "CameraBase.h"
#include "sys/SysControl.h"
#include "HMDWrapper.h"
#include "Engine.h"
#include "Game.h"
using namespace MathLib;
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
#define CAMERA_BASE_CLAMP 89.9f
CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR)
{
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_fPhiAngle = 0.0f;
m_fThetaAngle = 0.0f;
m_pLastPlayer = NULL;
m_nEnabelMouse = 1;
SetRadius(1.0f);
SetMinThetaAngle(-90.0f);
SetMaxThetaAngle(90.0f);
SetTurning(90.0f);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetEnabled(0);
SetHMDEnabled(1);
}
CCameraBase::~CCameraBase()
{
Leave();
}
void CCameraBase::SetEnabled(int nEnable)
{
if(nEnable)
{
m_pLastPlayer = g_Engine.pGame->GetPlayer();
CPlayer::SetEnabled(nEnable);
g_Engine.pGame->SetPlayer(this);
}
else
{
if (m_pLastPlayer)
{
g_Engine.pGame->SetPlayer(m_pLastPlayer);
CPlayer::SetEnabled(nEnable);
}
}
}
int CCameraBase::IsEnabled() const
{
return CPlayer::IsEnabled();
}
void CCameraBase::SetHMDEnabled(int nEnable)
{
m_nHMDEnable = nEnable;
}
int CCameraBase::IsHMDEnabled() const
{
return m_nHMDEnable;
}
void CCameraBase::SetRadius(float r)
{
m_fRadius = r;
}
float CCameraBase::GetRadius() const
{
return m_fRadius;
}
/******************************************************************************\
*
* Parameters
*
\******************************************************************************/
/*
*/
void CCameraBase::Update_Bounds()
{
m_BoundSphere.Set(vec3_zero,m_fRadius);
m_BoundBox.Set(m_BoundSphere);
Update_World_Position();
}
void CCameraBase::SetMinThetaAngle(float angle)
{
m_fMinThetaAngle = Clamp(angle,-CAMERA_BASE_CLAMP,CAMERA_BASE_CLAMP);
}
float CCameraBase::GetMinThetaAngle() const
{
return m_fMinThetaAngle;
}
/*
*/
void CCameraBase::SetMaxThetaAngle(float angle)
{
m_fMaxThetaAngle = Clamp(angle, -CAMERA_BASE_CLAMP, CAMERA_BASE_CLAMP);
}
float CCameraBase::GetMaxThetaAngle() const
{
return m_fMaxThetaAngle;
}
float CCameraBase::GetTurning() const
{
return m_fTurning;
}
void CCameraBase::SetPhiAngle(float angle)
{
angle = angle - m_fPhiAngle;
m_vDirection = quat(m_vUp, angle) * m_vDirection;
m_fPhiAngle += angle;
FlushTransform();
}
float CCameraBase::GetPhiAngle() const
{
return m_fPhiAngle;
}
void CCameraBase::SetThetaAngle(float angle)
{
angle = Clamp(angle, m_fMinThetaAngle, m_fMaxThetaAngle) - m_fThetaAngle;
m_vDirection = quat(Cross(m_vUp, m_vDirection), angle) * m_vDirection;
m_fThetaAngle += angle;
FlushTransform();
}
float CCameraBase::GetThetaAngle() const
{
return m_fThetaAngle;
}
/*
*
*/
void CCameraBase::SetViewDirection(const vec3 &d)
{
m_vDirection = Normalize(d);
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
FlushTransform();
}
const vec3 &CCameraBase::GetViewDirection() const
{
return m_vDirection;
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "CameraBase.h"
#include "sys/SysControl.h"
#include "HMDWrapper.h"
#include "Engine.h"
#include "Game.h"
using namespace MathLib;
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
#define CAMERA_BASE_CLAMP 89.9f
CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR)
{
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_fPhiAngle = 0.0f;
m_fThetaAngle = 0.0f;
m_pLastPlayer = NULL;
m_nEnabelMouse = 1;
SetRadius(1.0f);
SetMinThetaAngle(-90.0f);
SetMaxThetaAngle(90.0f);
SetTurning(90.0f);
SetViewDirection(vec3(0.0f,1.0f,0.0f));
SetEnabled(0);
SetHMDEnabled(1);
}
CCameraBase::~CCameraBase()
{
Leave();
}
void CCameraBase::SetEnabled(int nEnable)
{
if(nEnable)
{
m_pLastPlayer = g_Engine.pGame->GetPlayer();
CPlayer::SetEnabled(nEnable);
g_Engine.pGame->SetPlayer(this);
}
else
{
if (m_pLastPlayer)
{
g_Engine.pGame->SetPlayer(m_pLastPlayer);
CPlayer::SetEnabled(nEnable);
}
}
}
int CCameraBase::IsEnabled() const
{
return CPlayer::IsEnabled();
}
void CCameraBase::SetHMDEnabled(int nEnable)
{
m_nHMDEnable = nEnable;
}
int CCameraBase::IsHMDEnabled() const
{
return m_nHMDEnable;
}
void CCameraBase::SetRadius(float r)
{
m_fRadius = r;
}
float CCameraBase::GetRadius() const
{
return m_fRadius;
}
/******************************************************************************\
*
* Parameters
*
\******************************************************************************/
/*
*/
void CCameraBase::Update_Bounds()
{
m_BoundSphere.Set(vec3_zero,m_fRadius);
m_BoundBox.Set(m_BoundSphere);
Update_World_Position();
}
void CCameraBase::SetMinThetaAngle(float angle)
{
m_fMinThetaAngle = Clamp(angle,-CAMERA_BASE_CLAMP,CAMERA_BASE_CLAMP);
}
float CCameraBase::GetMinThetaAngle() const
{
return m_fMinThetaAngle;
}
/*
*/
void CCameraBase::SetMaxThetaAngle(float angle)
{
m_fMaxThetaAngle = Clamp(angle, -CAMERA_BASE_CLAMP, CAMERA_BASE_CLAMP);
}
float CCameraBase::GetMaxThetaAngle() const
{
return m_fMaxThetaAngle;
}
float CCameraBase::GetTurning() const
{
return m_fTurning;
}
void CCameraBase::SetPhiAngle(float angle)
{
angle = angle - m_fPhiAngle;
m_vDirection = quat(m_vUp, angle) * m_vDirection;
m_fPhiAngle += angle;
FlushTransform();
}
float CCameraBase::GetPhiAngle() const
{
return m_fPhiAngle;
}
void CCameraBase::SetThetaAngle(float angle)
{
angle = Clamp(angle, m_fMinThetaAngle, m_fMaxThetaAngle) - m_fThetaAngle;
m_vDirection = quat(Cross(m_vUp, m_vDirection), angle) * m_vDirection;
m_fThetaAngle += angle;
FlushTransform();
}
float CCameraBase::GetThetaAngle() const
{
return m_fThetaAngle;
}
/*
*
*/
void CCameraBase::SetViewDirection(const vec3 &d)
{
m_vDirection = Normalize(d);
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// decompose direction
m_fPhiAngle = CMathCore::ATan2(Dot(m_vDirection, tangent), Dot(m_vDirection, binormal)) * RAD2DEG;
FlushTransform();
}
const vec3 &CCameraBase::GetViewDirection() const
{
return m_vDirection;
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ResourceManager.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-04-03 15:54:36 $
*
* 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 SD_FRAMEWORK_RESOURCE_MANAGER_HXX
#define SD_FRAMEWORK_RESOURCE_MANAGER_HXX
#include "MutexOwner.hxx"
#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XCONFIGURATIONCHANGELISTENER_HPP_
#include <com/sun/star/drawing/framework/XConfigurationChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XCONFIGURATIONCONTROLLER_HPP_
#include <com/sun/star/drawing/framework/XConfigurationController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#include <boost/scoped_ptr.hpp>
namespace {
typedef ::cppu::WeakComponentImplHelper1 <
::com::sun::star::drawing::framework::XConfigurationChangeListener
> ResourceManagerInterfaceBase;
} // end of anonymous namespace.
namespace sd { namespace framework {
/** Manage the activation state of one resource depending on the view
in the center pane. The ResourceManager remembers in which
configuration to show and in which to hide the resource. When the
resource is deactivated or activated manually by the user then the
ResourceManager detects this and remembers this for the future.
*/
class ResourceManager
: private sd::MutexOwner,
public ResourceManagerInterfaceBase
{
public:
ResourceManager (
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XController>& rxController,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::framework::XResourceId>& rxResourceId);
virtual ~ResourceManager (void);
void AddActiveMainView (const ::rtl::OUString& rsMainViewURL);
virtual void SAL_CALL disposing (void);
/** Allow the ResourceManager to make resource activation or
deactivation requests.
*/
void Enable (void);
/** Hide the resource. When called the ResourceManager requests the
resource to be deactivated. Until enabled again it does not make
any further requests for resource activation or deactivation.
Call this for instance to hide resources in read-only mode.
*/
void Disable (void);
// XConfigurationChangeListener
virtual void SAL_CALL notifyConfigurationChange (
const com::sun::star::drawing::framework::ConfigurationChangeEvent& rEvent)
throw (com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing (
const com::sun::star::lang::EventObject& rEvent)
throw (com::sun::star::uno::RuntimeException);
protected:
::com::sun::star::uno::Reference<com::sun::star::drawing::framework::XConfigurationController>
mxConfigurationController;
private:
class MainViewContainer;
::boost::scoped_ptr<MainViewContainer> mpActiveMainViewContainer;
::com::sun::star::uno::Reference<
::com::sun::star::drawing::framework::XResourceId> mxResourceId;
::rtl::OUString msCurrentMainViewURL;
bool mbIsEnabled;
void HandleMainViewSwitch (
const ::rtl::OUString& rsViewURL,
const ::com::sun::star::uno::Reference<
com::sun::star::drawing::framework::XConfiguration>& rxConfiguration);
void HandleResourceRequest(
bool bActivation,
const ::com::sun::star::uno::Reference<
com::sun::star::drawing::framework::XConfiguration>& rxConfiguration);
void UpdateForMainViewShell (void);
void Trace (void) const;
};
} } // end of namespace sd::framework
#endif
<commit_msg>INTEGRATION: CWS presenterview (1.2.22); FILE MERGED 2007/06/19 08:19:44 af 1.2.22.1: #i18486# Handle a missing center pane correctly.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ResourceManager.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-04-03 13:39:54 $
*
* 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 SD_FRAMEWORK_RESOURCE_MANAGER_HXX
#define SD_FRAMEWORK_RESOURCE_MANAGER_HXX
#include "MutexOwner.hxx"
#include <com/sun/star/drawing/framework/XConfigurationChangeListener.hpp>
#include <com/sun/star/drawing/framework/XConfigurationController.hpp>
#include <com/sun/star/frame/XController.hpp>
#include <cppuhelper/compbase1.hxx>
#include <boost/scoped_ptr.hpp>
namespace css = ::com::sun::star;
namespace {
typedef ::cppu::WeakComponentImplHelper1 <
::com::sun::star::drawing::framework::XConfigurationChangeListener
> ResourceManagerInterfaceBase;
} // end of anonymous namespace.
namespace sd { namespace framework {
/** Manage the activation state of one resource depending on the view in the
center pane. The ResourceManager remembers in which configuration to
activate and in which to deactivate the resource. When the resource is
deactivated or activated manually by the user then the ResourceManager
detects this and remembers it for the future.
*/
class ResourceManager
: private sd::MutexOwner,
public ResourceManagerInterfaceBase
{
public:
ResourceManager (
const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XController>& rxController,
const ::com::sun::star::uno::Reference<
::com::sun::star::drawing::framework::XResourceId>& rxResourceId);
virtual ~ResourceManager (void);
/** Remember the given URL as one of a center pane view for which to
activate the resource managed by the called object.
*/
void AddActiveMainView (const ::rtl::OUString& rsMainViewURL);
virtual void SAL_CALL disposing (void);
/** Allow the ResourceManager to make resource activation or
deactivation requests.
*/
void Enable (void);
/** Disable the resource management. When called, the ResourceManager
requests the resource to be deactivated. Until enabled again it
does not make any further requests for resource activation or
deactivation.
Call this for example to hide resources in read-only mode.
*/
void Disable (void);
// XConfigurationChangeListener
virtual void SAL_CALL notifyConfigurationChange (
const com::sun::star::drawing::framework::ConfigurationChangeEvent& rEvent)
throw (com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing (
const com::sun::star::lang::EventObject& rEvent)
throw (com::sun::star::uno::RuntimeException);
protected:
::com::sun::star::uno::Reference<com::sun::star::drawing::framework::XConfigurationController>
mxConfigurationController;
private:
class MainViewContainer;
::boost::scoped_ptr<MainViewContainer> mpActiveMainViewContainer;
/// The resource managed by this class.
css::uno::Reference<css::drawing::framework::XResourceId> mxResourceId;
/// The anchor of the main view.
css::uno::Reference<css::drawing::framework::XResourceId> mxMainViewAnchorId;
::rtl::OUString msCurrentMainViewURL;
bool mbIsEnabled;
void HandleMainViewSwitch (
const ::rtl::OUString& rsViewURL,
const ::com::sun::star::uno::Reference<
com::sun::star::drawing::framework::XConfiguration>& rxConfiguration,
const bool bIsActivated);
void HandleResourceRequest(
bool bActivation,
const ::com::sun::star::uno::Reference<
com::sun::star::drawing::framework::XConfiguration>& rxConfiguration);
void UpdateForMainViewShell (void);
void Trace (void) const;
};
} } // end of namespace sd::framework
#endif
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle 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 <cstddef>
#include <functional>
#include "paddle/fluid/memory/detail/memory_block.h"
namespace paddle {
namespace memory {
namespace detail {
MemoryBlock::Desc::Desc(MemoryBlock::Type t, size_t i, size_t s, size_t ts,
MemoryBlock* l, MemoryBlock* r)
: type(t),
index(i),
size(s),
total_size(ts),
left_buddy(l),
right_buddy(r) {}
MemoryBlock::Desc::Desc()
: type(MemoryBlock::INVALID_CHUNK),
index(0),
size(0),
total_size(0),
left_buddy(nullptr),
right_buddy(nullptr) {}
namespace {
template <class T>
inline void hash_combine(std::size_t* seed, const T& v) {
std::hash<T> hasher;
(*seed) ^= hasher(v) + 0x9e3779b9 + ((*seed) << 6) + ((*seed) >> 2);
}
inline size_t hash(const MemoryBlock::Desc& metadata, size_t initial_seed) {
size_t seed = initial_seed;
hash_combine(&seed, static_cast<size_t>(metadata.type));
hash_combine(&seed, metadata.index);
hash_combine(&seed, metadata.size);
hash_combine(&seed, metadata.total_size);
hash_combine(&seed, metadata.left_buddy);
hash_combine(&seed, metadata.right_buddy);
return seed;
}
} // namespace
void MemoryBlock::Desc::UpdateGuards() {
#ifdef PADDLE_WITH_TESTING
guard_begin = hash(*this, 1);
guard_end = hash(*this, 2);
#endif
}
bool MemoryBlock::Desc::CheckGuards() const {
#ifdef PADDLE_WITH_TESTING
return guard_begin == hash(*this, 1) && guard_end == hash(*this, 2);
#else
return true;
#endif
}
} // namespace detail
} // namespace memory
} // namespace paddle
<commit_msg>delete PADDLE_WITH_TESTING in memory_block_desc (#41817)<commit_after>/* Copyright (c) 2016 PaddlePaddle 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 <cstddef>
#include <functional>
#include "paddle/fluid/memory/detail/memory_block.h"
namespace paddle {
namespace memory {
namespace detail {
MemoryBlock::Desc::Desc(MemoryBlock::Type t, size_t i, size_t s, size_t ts,
MemoryBlock* l, MemoryBlock* r)
: type(t),
index(i),
size(s),
total_size(ts),
left_buddy(l),
right_buddy(r) {}
MemoryBlock::Desc::Desc()
: type(MemoryBlock::INVALID_CHUNK),
index(0),
size(0),
total_size(0),
left_buddy(nullptr),
right_buddy(nullptr) {}
namespace {
template <class T>
inline void hash_combine(std::size_t* seed, const T& v) {
std::hash<T> hasher;
(*seed) ^= hasher(v) + 0x9e3779b9 + ((*seed) << 6) + ((*seed) >> 2);
}
inline size_t hash(const MemoryBlock::Desc& metadata, size_t initial_seed) {
size_t seed = initial_seed;
hash_combine(&seed, static_cast<size_t>(metadata.type));
hash_combine(&seed, metadata.index);
hash_combine(&seed, metadata.size);
hash_combine(&seed, metadata.total_size);
hash_combine(&seed, metadata.left_buddy);
hash_combine(&seed, metadata.right_buddy);
return seed;
}
} // namespace
void MemoryBlock::Desc::UpdateGuards() {
guard_begin = hash(*this, 1);
guard_end = hash(*this, 2);
}
bool MemoryBlock::Desc::CheckGuards() const {
return guard_begin == hash(*this, 1) && guard_end == hash(*this, 2);
}
} // namespace detail
} // namespace memory
} // namespace paddle
<|endoftext|> |
<commit_before>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/11/09.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "ptr.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/buffer_scratch.h"
#include "image/iterator.h"
#include "image/threaded_loop.h"
#include "image/utils.h"
#include "image/voxel.h"
#include "math/math.h"
#include <limits>
#include <vector>
using namespace MR;
using namespace App;
const char* operations[] = {
"mean",
"sum",
"product",
"rms",
"var",
"std",
"min",
"max",
"absmax",
"magmax",
NULL
};
void usage ()
{
DESCRIPTION
+ "compute summary statistic (e.g. mean, min, max, ...) on image intensities either across images, or along a specified axis for a single image. "
+ "See also 'mrcalc' to compute per-voxel operations.";
ARGUMENTS
+ Argument ("input", "the input image.").type_image_in ().allow_multiple()
+ Argument ("operation", "the operation to apply, one of: " + join(operations, ", ") + ".").type_choice (operations)
+ Argument ("output", "the output image.").type_image_out ();
OPTIONS
+ Option ("axis", "perform operation along a specified axis of a single input image")
+ Argument ("index").type_integer();
}
typedef float value_type;
typedef Image::BufferPreload<value_type> PreloadBufferType;
typedef PreloadBufferType::voxel_type PreloadVoxelType;
typedef Image::Buffer<value_type> BufferType;
typedef BufferType::voxel_type VoxelType;
class Mean {
public:
Mean () : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
++count;
}
}
value_type result () const {
if (!count)
return NAN;
return sum / count;
}
double sum;
size_t count;
};
class Sum {
public:
Sum () : sum (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
sum += val;
}
value_type result () const {
return sum;
}
double sum;
};
class Product {
public:
Product () : product (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
product += val;
}
value_type result () const {
return product;
}
double product;
};
class RMS {
public:
RMS() : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += Math::pow2 (val);
++count;
}
}
value_type result() const {
if (!count)
return NAN;
return Math::sqrt(sum / count);
}
double sum;
size_t count;
};
class Var {
public:
Var () : sum (0.0), sum_sqr (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
sum_sqr += Math::pow2 (val);
++count;
}
}
value_type result () const {
if (count < 2)
return NAN;
return (sum_sqr - Math::pow2 (sum) / static_cast<double> (count)) / (static_cast<double> (count) - 1.0);
}
double sum, sum_sqr;
size_t count;
};
class Std : public Var {
public:
Std() : Var() { }
value_type result () const { return Math::sqrt (Var::result()); }
};
class Min {
public:
Min () : min (std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val < min)
min = val;
}
value_type result () const { return std::isfinite (min) ? min : NAN; }
value_type min;
};
class Max {
public:
Max () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val > max)
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class AbsMax {
public:
AbsMax () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && Math::abs(val) > max)
max = Math::abs(val);
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class MagMax {
public:
MagMax () : max (-std::numeric_limits<value_type>::infinity()) { }
MagMax (const int i) : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && Math::abs(val) > max)
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
template <class Operation>
class AxisKernel {
public:
AxisKernel (size_t axis) : axis (axis) { }
template <class InputVoxelType, class OutputVoxelType>
void operator() (InputVoxelType& in, OutputVoxelType& out) {
Operation op;
for (in[axis] = 0; in[axis] < in.dim(axis); ++in[axis])
op (in.value());
out.value() = op.result();
}
protected:
const size_t axis;
};
class ImageKernelBase {
public:
ImageKernelBase (const std::string& path) :
output_path (path) { }
virtual ~ImageKernelBase() { }
virtual void process (const Image::Header& image_in) = 0;
protected:
const std::string output_path;
};
template <class Operation>
class ImageKernel : public ImageKernelBase {
protected:
class InitFunctor {
public:
template <class VoxelType>
void operator() (VoxelType& out) const { out.value() = Operation(); }
};
class ProcessFunctor {
public:
template <class VoxelType1, class VoxelType2>
void operator() (VoxelType1& out, VoxelType2& in) const {
Operation op = out.value();
op (in.value());
out.value() = op;
}
};
class ResultFunctor {
public:
template <class VoxelType1, class VoxelType2>
void operator() (VoxelType1& out, VoxelType2& in) const {
Operation op = in.value();
out.value() = op.result();
}
};
public:
ImageKernel (const Image::Header& header, const std::string& path) :
ImageKernelBase (path),
header (header),
buffer (header)
{
typename Image::BufferScratch<Operation>::voxel_type v_buffer (buffer);
Image::ThreadedLoop (v_buffer).run (InitFunctor(), v_buffer);
}
~ImageKernel()
{
Image::Buffer<value_type> out (output_path, header);
Image::Buffer<value_type>::voxel_type v_out (out);
typename Image::BufferScratch<Operation>::voxel_type v_buffer (buffer);
Image::ThreadedLoop (v_buffer).run (ResultFunctor(), v_out, v_buffer);
}
void process (const Image::Header& image_in)
{
Image::Buffer<value_type> in (image_in);
Image::Buffer<value_type>::voxel_type v_in (in);
for (size_t axis = buffer.ndim(); axis < v_in.ndim(); ++axis)
v_in[axis] = 0;
typename Image::BufferScratch<Operation>::voxel_type v_buffer (buffer);
Image::ThreadedLoop (v_buffer).run (ProcessFunctor(), v_buffer, v_in);
}
protected:
const Image::Header& header;
Image::BufferScratch<Operation> buffer;
};
void run ()
{
const size_t num_inputs = argument.size() - 2;
const int op = argument[num_inputs];
const std::string& output_path = argument.back();
Options opt = get_options ("axis");
if (opt.size()) {
if (num_inputs != 1)
throw Exception ("Option -axis only applies if a single input image is used");
const size_t axis = opt[0][0];
PreloadBufferType buffer_in (argument[0], Image::Stride::contiguous_along_axis (axis));
if (axis >= buffer_in.ndim())
throw Exception ("Cannot perform operation along axis " + str (axis) + "; image only has " + str(buffer_in.ndim()) + " axes");
Image::Header header_out (buffer_in);
header_out.datatype() = DataType::Float32;
header_out.dim(axis) = 1;
Image::squeeze_dim (header_out);
BufferType buffer_out (output_path, header_out);
PreloadBufferType::voxel_type vox_in (buffer_in);
BufferType::voxel_type vox_out (buffer_out);
Image::ThreadedLoop loop (std::string("computing ") + operations[op] + " along axis " + str(axis) + "...", buffer_out);
switch (op) {
case 0: loop.run (AxisKernel<Mean> (axis), vox_in, vox_out); return;
case 1: loop.run (AxisKernel<Sum> (axis), vox_in, vox_out); return;
case 2: loop.run (AxisKernel<Product>(axis), vox_in, vox_out); return;
case 3: loop.run (AxisKernel<RMS> (axis), vox_in, vox_out); return;
case 4: loop.run (AxisKernel<Var> (axis), vox_in, vox_out); return;
case 5: loop.run (AxisKernel<Std> (axis), vox_in, vox_out); return;
case 6: loop.run (AxisKernel<Min> (axis), vox_in, vox_out); return;
case 7: loop.run (AxisKernel<Max> (axis), vox_in, vox_out); return;
case 8: loop.run (AxisKernel<AbsMax> (axis), vox_in, vox_out); return;
case 9: loop.run (AxisKernel<MagMax> (axis), vox_in, vox_out); return;
default: assert (0);
}
} else {
if (num_inputs < 2)
throw Exception ("mrmath requires either multiple input images, or the -axis option to be provided");
// Pre-load all image headers
VecPtr<Image::Header> headers_in;
// Header of first input image is the template to which all other input images are compared
headers_in.push_back (new Image::Header (argument[0]));
Image::Header header (*headers_in[0]);
// Wipe any excess unary-dimensional axes
while (header.dim (header.ndim() - 1) == 1)
header.set_ndim (header.ndim() - 1);
// Verify that dimensions of all input images adequately match
for (size_t i = 1; i != num_inputs; ++i) {
const std::string path = argument[i];
headers_in.push_back (new Image::Header (path));
const Image::Header& temp (*headers_in[i]);
if (temp.ndim() < header.ndim())
throw Exception ("Image " + path + " has fewer axes than first imput image " + header.name());
for (size_t axis = 0; axis != header.ndim(); ++axis) {
if (temp.dim(axis) != header.dim(axis))
throw Exception ("Dimensions of image " + path + " do not match those of first input image " + header.name());
}
for (size_t axis = header.ndim(); axis != temp.ndim(); ++axis) {
if (temp.dim(axis) != 1)
throw Exception ("Image " + path + " has axis with non-unary dimension beyond first input image " + header.name());
}
}
// Instantiate a kernel depending on the operation requested
Ptr<ImageKernelBase> kernel;
switch (op) {
case 0: kernel = new ImageKernel<Mean> (header, output_path); break;
case 1: kernel = new ImageKernel<Sum> (header, output_path); break;
case 2: kernel = new ImageKernel<RMS> (header, output_path); break;
case 3: kernel = new ImageKernel<Var> (header, output_path); break;
case 4: kernel = new ImageKernel<Std> (header, output_path); break;
case 5: kernel = new ImageKernel<Min> (header, output_path); break;
case 6: kernel = new ImageKernel<Max> (header, output_path); break;
case 7: kernel = new ImageKernel<AbsMax> (header, output_path); break;
case 8: kernel = new ImageKernel<MagMax> (header, output_path); break;
default: assert (0);
}
// Feed the input images to the kernel one at a time
{
ProgressBar progress (std::string("computing ") + operations[op] + " across "
+ str(headers_in.size()) + " images...", num_inputs);
for (size_t i = 0; i != headers_in.size(); ++i) {
kernel->process (*headers_in[i]);
++progress;
}
}
// Image output is handled by the kernel destructor
}
}
<commit_msg>fixed bug in mrmath introduced in previous commit<commit_after>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/11/09.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "progressbar.h"
#include "ptr.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/buffer_scratch.h"
#include "image/iterator.h"
#include "image/threaded_loop.h"
#include "image/utils.h"
#include "image/voxel.h"
#include "math/math.h"
#include <limits>
#include <vector>
using namespace MR;
using namespace App;
const char* operations[] = {
"mean",
"sum",
"product",
"rms",
"var",
"std",
"min",
"max",
"absmax",
"magmax",
NULL
};
void usage ()
{
DESCRIPTION
+ "compute summary statistic (e.g. mean, min, max, ...) on image intensities either across images, or along a specified axis for a single image. "
+ "See also 'mrcalc' to compute per-voxel operations.";
ARGUMENTS
+ Argument ("input", "the input image.").type_image_in ().allow_multiple()
+ Argument ("operation", "the operation to apply, one of: " + join(operations, ", ") + ".").type_choice (operations)
+ Argument ("output", "the output image.").type_image_out ();
OPTIONS
+ Option ("axis", "perform operation along a specified axis of a single input image")
+ Argument ("index").type_integer();
}
typedef float value_type;
typedef Image::BufferPreload<value_type> PreloadBufferType;
typedef PreloadBufferType::voxel_type PreloadVoxelType;
typedef Image::Buffer<value_type> BufferType;
typedef BufferType::voxel_type VoxelType;
class Mean {
public:
Mean () : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
++count;
}
}
value_type result () const {
if (!count)
return NAN;
return sum / count;
}
double sum;
size_t count;
};
class Sum {
public:
Sum () : sum (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
sum += val;
}
value_type result () const {
return sum;
}
double sum;
};
class Product {
public:
Product () : product (0.0) { }
void operator() (value_type val) {
if (std::isfinite (val))
product += val;
}
value_type result () const {
return product;
}
double product;
};
class RMS {
public:
RMS() : sum (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += Math::pow2 (val);
++count;
}
}
value_type result() const {
if (!count)
return NAN;
return Math::sqrt(sum / count);
}
double sum;
size_t count;
};
class Var {
public:
Var () : sum (0.0), sum_sqr (0.0), count (0) { }
void operator() (value_type val) {
if (std::isfinite (val)) {
sum += val;
sum_sqr += Math::pow2 (val);
++count;
}
}
value_type result () const {
if (count < 2)
return NAN;
return (sum_sqr - Math::pow2 (sum) / static_cast<double> (count)) / (static_cast<double> (count) - 1.0);
}
double sum, sum_sqr;
size_t count;
};
class Std : public Var {
public:
Std() : Var() { }
value_type result () const { return Math::sqrt (Var::result()); }
};
class Min {
public:
Min () : min (std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val < min)
min = val;
}
value_type result () const { return std::isfinite (min) ? min : NAN; }
value_type min;
};
class Max {
public:
Max () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && val > max)
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class AbsMax {
public:
AbsMax () : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && Math::abs(val) > max)
max = Math::abs(val);
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
class MagMax {
public:
MagMax () : max (-std::numeric_limits<value_type>::infinity()) { }
MagMax (const int i) : max (-std::numeric_limits<value_type>::infinity()) { }
void operator() (value_type val) {
if (std::isfinite (val) && Math::abs(val) > max)
max = val;
}
value_type result () const { return std::isfinite (max) ? max : NAN; }
value_type max;
};
template <class Operation>
class AxisKernel {
public:
AxisKernel (size_t axis) : axis (axis) { }
template <class InputVoxelType, class OutputVoxelType>
void operator() (InputVoxelType& in, OutputVoxelType& out) {
Operation op;
for (in[axis] = 0; in[axis] < in.dim(axis); ++in[axis])
op (in.value());
out.value() = op.result();
}
protected:
const size_t axis;
};
class ImageKernelBase {
public:
ImageKernelBase (const std::string& path) :
output_path (path) { }
virtual ~ImageKernelBase() { }
virtual void process (const Image::Header& image_in) = 0;
protected:
const std::string output_path;
};
template <class Operation>
class ImageKernel : public ImageKernelBase {
protected:
class InitFunctor {
public:
template <class VoxelType>
void operator() (VoxelType& out) const { out.value() = Operation(); }
};
class ProcessFunctor {
public:
template <class VoxelType1, class VoxelType2>
void operator() (VoxelType1& out, VoxelType2& in) const {
Operation op = out.value();
op (in.value());
out.value() = op;
}
};
class ResultFunctor {
public:
template <class VoxelType1, class VoxelType2>
void operator() (VoxelType1& out, VoxelType2& in) const {
Operation op = in.value();
out.value() = op.result();
}
};
public:
ImageKernel (const Image::Header& header, const std::string& path) :
ImageKernelBase (path),
header (header),
buffer (header)
{
typename Image::BufferScratch<Operation>::voxel_type v_buffer (buffer);
Image::ThreadedLoop (v_buffer).run (InitFunctor(), v_buffer);
}
~ImageKernel()
{
Image::Buffer<value_type> out (output_path, header);
Image::Buffer<value_type>::voxel_type v_out (out);
typename Image::BufferScratch<Operation>::voxel_type v_buffer (buffer);
Image::ThreadedLoop (v_buffer).run (ResultFunctor(), v_out, v_buffer);
}
void process (const Image::Header& image_in)
{
Image::Buffer<value_type> in (image_in);
Image::Buffer<value_type>::voxel_type v_in (in);
for (size_t axis = buffer.ndim(); axis < v_in.ndim(); ++axis)
v_in[axis] = 0;
typename Image::BufferScratch<Operation>::voxel_type v_buffer (buffer);
Image::ThreadedLoop (v_buffer).run (ProcessFunctor(), v_buffer, v_in);
}
protected:
const Image::Header& header;
Image::BufferScratch<Operation> buffer;
};
void run ()
{
const size_t num_inputs = argument.size() - 2;
const int op = argument[num_inputs];
const std::string& output_path = argument.back();
Options opt = get_options ("axis");
if (opt.size()) {
if (num_inputs != 1)
throw Exception ("Option -axis only applies if a single input image is used");
const size_t axis = opt[0][0];
PreloadBufferType buffer_in (argument[0], Image::Stride::contiguous_along_axis (axis));
if (axis >= buffer_in.ndim())
throw Exception ("Cannot perform operation along axis " + str (axis) + "; image only has " + str(buffer_in.ndim()) + " axes");
Image::Header header_out (buffer_in);
header_out.datatype() = DataType::Float32;
header_out.dim(axis) = 1;
Image::squeeze_dim (header_out);
BufferType buffer_out (output_path, header_out);
PreloadBufferType::voxel_type vox_in (buffer_in);
BufferType::voxel_type vox_out (buffer_out);
Image::ThreadedLoop loop (std::string("computing ") + operations[op] + " along axis " + str(axis) + "...", buffer_out);
switch (op) {
case 0: loop.run (AxisKernel<Mean> (axis), vox_in, vox_out); return;
case 1: loop.run (AxisKernel<Sum> (axis), vox_in, vox_out); return;
case 2: loop.run (AxisKernel<Product>(axis), vox_in, vox_out); return;
case 3: loop.run (AxisKernel<RMS> (axis), vox_in, vox_out); return;
case 4: loop.run (AxisKernel<Var> (axis), vox_in, vox_out); return;
case 5: loop.run (AxisKernel<Std> (axis), vox_in, vox_out); return;
case 6: loop.run (AxisKernel<Min> (axis), vox_in, vox_out); return;
case 7: loop.run (AxisKernel<Max> (axis), vox_in, vox_out); return;
case 8: loop.run (AxisKernel<AbsMax> (axis), vox_in, vox_out); return;
case 9: loop.run (AxisKernel<MagMax> (axis), vox_in, vox_out); return;
default: assert (0);
}
} else {
if (num_inputs < 2)
throw Exception ("mrmath requires either multiple input images, or the -axis option to be provided");
// Pre-load all image headers
VecPtr<Image::Header> headers_in;
// Header of first input image is the template to which all other input images are compared
headers_in.push_back (new Image::Header (argument[0]));
Image::Header header (*headers_in[0]);
// Wipe any excess unary-dimensional axes
while (header.dim (header.ndim() - 1) == 1)
header.set_ndim (header.ndim() - 1);
// Verify that dimensions of all input images adequately match
for (size_t i = 1; i != num_inputs; ++i) {
const std::string path = argument[i];
headers_in.push_back (new Image::Header (path));
const Image::Header& temp (*headers_in[i]);
if (temp.ndim() < header.ndim())
throw Exception ("Image " + path + " has fewer axes than first imput image " + header.name());
for (size_t axis = 0; axis != header.ndim(); ++axis) {
if (temp.dim(axis) != header.dim(axis))
throw Exception ("Dimensions of image " + path + " do not match those of first input image " + header.name());
}
for (size_t axis = header.ndim(); axis != temp.ndim(); ++axis) {
if (temp.dim(axis) != 1)
throw Exception ("Image " + path + " has axis with non-unary dimension beyond first input image " + header.name());
}
}
// Instantiate a kernel depending on the operation requested
Ptr<ImageKernelBase> kernel;
switch (op) {
case 0: kernel = new ImageKernel<Mean> (header, output_path); break;
case 1: kernel = new ImageKernel<Sum> (header, output_path); break;
case 2: kernel = new ImageKernel<Product> (header, output_path); break;
case 3: kernel = new ImageKernel<RMS> (header, output_path); break;
case 4: kernel = new ImageKernel<Var> (header, output_path); break;
case 5: kernel = new ImageKernel<Std> (header, output_path); break;
case 6: kernel = new ImageKernel<Min> (header, output_path); break;
case 7: kernel = new ImageKernel<Max> (header, output_path); break;
case 8: kernel = new ImageKernel<AbsMax> (header, output_path); break;
case 9: kernel = new ImageKernel<MagMax> (header, output_path); break;
default: assert (0);
}
// Feed the input images to the kernel one at a time
{
ProgressBar progress (std::string("computing ") + operations[op] + " across "
+ str(headers_in.size()) + " images...", num_inputs);
for (size_t i = 0; i != headers_in.size(); ++i) {
kernel->process (*headers_in[i]);
++progress;
}
}
// Image output is handled by the kernel destructor
}
}
<|endoftext|> |
<commit_before><commit_msg>we need to put the step_delay in microseconds, not milliseconds.<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <set>
#include "memory_manager.hpp"
class firstfit_manager : public memory_manager
{
using compare_function = std::function<bool(const block&, const block&)>;
std::multiset<block, compare_function> free_blocks;
public:
firstfit_manager(unsigned int memory_size,
compare_function comp = compare_increasing_size)
: memory_manager(memory_size), free_blocks(comp)
{
free_blocks.emplace_hint(free_blocks.begin(), 0, memory_size);
};
virtual block alloc(unsigned int size)
{
if (size > free_size)
return block();
free_size -= size;
for (auto it = free_blocks.begin(); it != free_blocks.end(); ++it)
{
if (it->size > size)
{
block result = *it;
free_blocks.emplace_hint(it, result.start + size, result.size - size);
free_blocks.erase(it);
return block(result.start, size);
}
}
//TODO: compact memory here
}
virtual void free(block&& b)
{
free_size += b.size;
free_blocks.insert(std::forward<block>(b));
//TODO: coalesce
}
static bool compare_increasing_size(const block& a, const block& b)
{
return a.size < b.size;
}
static bool compare_memory_location(const block& a, const block& b)
{
return a.start < b.start;
}
};<commit_msg>corrected alloc logic, now works regardless of sorting function<commit_after>#pragma once
#include <set>
#include "memory_manager.hpp"
class firstfit_manager : public memory_manager
{
using compare_function = std::function<bool(const block&, const block&)>;
std::multiset<block, compare_function> free_blocks;
public:
firstfit_manager(unsigned int memory_size,
compare_function comp = compare_increasing_size)
: memory_manager(memory_size), free_blocks(comp)
{
free_blocks.emplace_hint(free_blocks.begin(), 0, memory_size);
};
virtual block alloc(unsigned int size)
{
if (size > free_size)
return block();
free_size -= size;
for (auto it = free_blocks.begin(); it != free_blocks.end(); ++it)
{
if (it->size > size)
{
block result(it->start, size);
free_blocks.emplace_hint(it, it->start + size, it->size - size);
free_blocks.erase(it);
return result;
}
}
//TODO: compact memory here
}
virtual void free(block&& b)
{
free_size += b.size;
free_blocks.insert(std::forward<block>(b));
//TODO: coalesce
}
static bool compare_increasing_size(const block& a, const block& b)
{
return a.size < b.size;
}
static bool compare_memory_location(const block& a, const block& b)
{
return a.start < b.start;
}
};<|endoftext|> |
<commit_before>/**
* Copyright 2018 The Android Open Source Project
*
* 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 <cassert>
#include <logging_macros.h>
#include "LiveEffectEngine.h"
LiveEffectEngine::LiveEffectEngine() {
assert(mOutputChannelCount == mInputChannelCount);
}
void LiveEffectEngine::setRecordingDeviceId(int32_t deviceId) {
mRecordingDeviceId = deviceId;
}
void LiveEffectEngine::setPlaybackDeviceId(int32_t deviceId) {
mPlaybackDeviceId = deviceId;
}
bool LiveEffectEngine::isAAudioRecommended() {
return oboe::AudioStreamBuilder::isAAudioRecommended();
}
bool LiveEffectEngine::setAudioApi(oboe::AudioApi api) {
if (mIsEffectOn) return false;
mAudioApi = api;
return true;
}
bool LiveEffectEngine::setEffectOn(bool isOn) {
bool success = true;
if (isOn != mIsEffectOn) {
if (isOn) {
success = openStreams() == oboe::Result::OK;
if (success) {
mFullDuplexPass.start();
mIsEffectOn = isOn;
}
} else {
mFullDuplexPass.stop();
closeStreams();
mIsEffectOn = isOn;
}
}
return success;
}
void LiveEffectEngine::closeStreams() {
/*
* Note: The order of events is important here.
* The playback stream must be closed before the recording stream. If the
* recording stream were to be closed first the playback stream's
* callback may attempt to read from the recording stream
* which would cause the app to crash since the recording stream would be
* null.
*/
closeStream(mPlayStream);
mFullDuplexPass.setOutputStream(nullptr);
closeStream(mRecordingStream);
mFullDuplexPass.setInputStream(nullptr);
}
oboe::Result LiveEffectEngine::openStreams() {
// Note: The order of stream creation is important. We create the playback
// stream first, then use properties from the playback stream
// (e.g. sample rate) to create the recording stream. By matching the
// properties we should get the lowest latency path
oboe::AudioStreamBuilder inBuilder, outBuilder;
setupPlaybackStreamParameters(&outBuilder);
oboe::Result result = outBuilder.openStream(mPlayStream);
if (result != oboe::Result::OK) {
mSampleRate = oboe::kUnspecified;
return result;
} else {
// The input stream needs to run at the same sample rate as the output.
mSampleRate = mPlayStream->getSampleRate();
}
warnIfNotLowLatency(mPlayStream);
setupRecordingStreamParameters(&inBuilder, mSampleRate);
result = inBuilder.openStream(mRecordingStream);
if (result != oboe::Result::OK) {
closeStream(mPlayStream);
return result;
}
warnIfNotLowLatency(mRecordingStream);
mFullDuplexPass.setInputStream(mRecordingStream);
mFullDuplexPass.setOutputStream(mPlayStream);
return result;
}
/**
* Sets the stream parameters which are specific to recording,
* including the sample rate which is determined from the
* playback stream.
*
* @param builder The recording stream builder
* @param sampleRate The desired sample rate of the recording stream
*/
oboe::AudioStreamBuilder *LiveEffectEngine::setupRecordingStreamParameters(
oboe::AudioStreamBuilder *builder, int32_t sampleRate) {
// This sample uses blocking read() because we don't specify a callback
builder->setDeviceId(mRecordingDeviceId)
->setDirection(oboe::Direction::Input)
->setSampleRate(sampleRate)
->setChannelCount(mInputChannelCount);
return setupCommonStreamParameters(builder);
}
/**
* Sets the stream parameters which are specific to playback, including device
* id and the dataCallback function, which must be set for low latency
* playback.
* @param builder The playback stream builder
*/
oboe::AudioStreamBuilder *LiveEffectEngine::setupPlaybackStreamParameters(
oboe::AudioStreamBuilder *builder) {
builder->setDataCallback(this)
->setErrorCallback(this)
->setDeviceId(mPlaybackDeviceId)
->setDirection(oboe::Direction::Output)
->setChannelCount(mOutputChannelCount);
return setupCommonStreamParameters(builder);
}
/**
* Set the stream parameters which are common to both recording and playback
* streams.
* @param builder The playback or recording stream builder
*/
oboe::AudioStreamBuilder *LiveEffectEngine::setupCommonStreamParameters(
oboe::AudioStreamBuilder *builder) {
// We request EXCLUSIVE mode since this will give us the lowest possible
// latency.
// If EXCLUSIVE mode isn't available the builder will fall back to SHARED
// mode.
builder->setAudioApi(mAudioApi)
->setFormat(mFormat)
->setSharingMode(oboe::SharingMode::Exclusive)
->setPerformanceMode(oboe::PerformanceMode::LowLatency);
return builder;
}
/**
* Close the stream. AudioStream::close() is a blocking call so
* the application does not need to add synchronization between
* onAudioReady() function and the thread calling close().
* [the closing thread is the UI thread in this sample].
* @param stream the stream to close
*/
void LiveEffectEngine::closeStream(std::shared_ptr<oboe::AudioStream> &stream) {
if (stream) {
oboe::Result result = stream->stop();
if (result != oboe::Result::OK) {
LOGW("Error stopping stream: %s", oboe::convertToText(result));
}
result = stream->close();
if (result != oboe::Result::OK) {
LOGE("Error closing stream: %s", oboe::convertToText(result));
} else {
LOGW("Successfully closed streams");
}
stream.reset();
}
}
/**
* Warn in logcat if non-low latency stream is created
* @param stream: newly created stream
*
*/
void LiveEffectEngine::warnIfNotLowLatency(std::shared_ptr<oboe::AudioStream> &stream) {
if (stream->getPerformanceMode() != oboe::PerformanceMode::LowLatency) {
LOGW(
"Stream is NOT low latency."
"Check your requested format, sample rate and channel count");
}
}
/**
* Handles playback stream's audio request. In this sample, we simply block-read
* from the record stream for the required samples.
*
* @param oboeStream: the playback stream that requesting additional samples
* @param audioData: the buffer to load audio samples for playback stream
* @param numFrames: number of frames to load to audioData buffer
* @return: DataCallbackResult::Continue.
*/
oboe::DataCallbackResult LiveEffectEngine::onAudioReady(
oboe::AudioStream *oboeStream, void *audioData, int32_t numFrames) {
return mFullDuplexPass.onAudioReady(oboeStream, audioData, numFrames);
}
/**
* Oboe notifies the application for "about to close the stream".
*
* @param oboeStream: the stream to close
* @param error: oboe's reason for closing the stream
*/
void LiveEffectEngine::onErrorBeforeClose(oboe::AudioStream *oboeStream,
oboe::Result error) {
LOGE("%s stream Error before close: %s",
oboe::convertToText(oboeStream->getDirection()),
oboe::convertToText(error));
}
/**
* Oboe notifies application that "the stream is closed"
*
* @param oboeStream
* @param error
*/
void LiveEffectEngine::onErrorAfterClose(oboe::AudioStream *oboeStream,
oboe::Result error) {
LOGE("%s stream Error after close: %s",
oboe::convertToText(oboeStream->getDirection()),
oboe::convertToText(error));
}
<commit_msg>Log reason why input or output stream fails to open<commit_after>/**
* Copyright 2018 The Android Open Source Project
*
* 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 <cassert>
#include <logging_macros.h>
#include "LiveEffectEngine.h"
LiveEffectEngine::LiveEffectEngine() {
assert(mOutputChannelCount == mInputChannelCount);
}
void LiveEffectEngine::setRecordingDeviceId(int32_t deviceId) {
mRecordingDeviceId = deviceId;
}
void LiveEffectEngine::setPlaybackDeviceId(int32_t deviceId) {
mPlaybackDeviceId = deviceId;
}
bool LiveEffectEngine::isAAudioRecommended() {
return oboe::AudioStreamBuilder::isAAudioRecommended();
}
bool LiveEffectEngine::setAudioApi(oboe::AudioApi api) {
if (mIsEffectOn) return false;
mAudioApi = api;
return true;
}
bool LiveEffectEngine::setEffectOn(bool isOn) {
bool success = true;
if (isOn != mIsEffectOn) {
if (isOn) {
success = openStreams() == oboe::Result::OK;
if (success) {
mFullDuplexPass.start();
mIsEffectOn = isOn;
}
} else {
mFullDuplexPass.stop();
closeStreams();
mIsEffectOn = isOn;
}
}
return success;
}
void LiveEffectEngine::closeStreams() {
/*
* Note: The order of events is important here.
* The playback stream must be closed before the recording stream. If the
* recording stream were to be closed first the playback stream's
* callback may attempt to read from the recording stream
* which would cause the app to crash since the recording stream would be
* null.
*/
closeStream(mPlayStream);
mFullDuplexPass.setOutputStream(nullptr);
closeStream(mRecordingStream);
mFullDuplexPass.setInputStream(nullptr);
}
oboe::Result LiveEffectEngine::openStreams() {
// Note: The order of stream creation is important. We create the playback
// stream first, then use properties from the playback stream
// (e.g. sample rate) to create the recording stream. By matching the
// properties we should get the lowest latency path
oboe::AudioStreamBuilder inBuilder, outBuilder;
setupPlaybackStreamParameters(&outBuilder);
oboe::Result result = outBuilder.openStream(mPlayStream);
if (result != oboe::Result::OK) {
LOGE("Failed to open output stream. Error %s", oboe::convertToText(result));
mSampleRate = oboe::kUnspecified;
return result;
} else {
// The input stream needs to run at the same sample rate as the output.
mSampleRate = mPlayStream->getSampleRate();
}
warnIfNotLowLatency(mPlayStream);
setupRecordingStreamParameters(&inBuilder, mSampleRate);
result = inBuilder.openStream(mRecordingStream);
if (result != oboe::Result::OK) {
LOGE("Failed to open input stream. Error %s", oboe::convertToText(result));
closeStream(mPlayStream);
return result;
}
warnIfNotLowLatency(mRecordingStream);
mFullDuplexPass.setInputStream(mRecordingStream);
mFullDuplexPass.setOutputStream(mPlayStream);
return result;
}
/**
* Sets the stream parameters which are specific to recording,
* including the sample rate which is determined from the
* playback stream.
*
* @param builder The recording stream builder
* @param sampleRate The desired sample rate of the recording stream
*/
oboe::AudioStreamBuilder *LiveEffectEngine::setupRecordingStreamParameters(
oboe::AudioStreamBuilder *builder, int32_t sampleRate) {
// This sample uses blocking read() because we don't specify a callback
builder->setDeviceId(mRecordingDeviceId)
->setDirection(oboe::Direction::Input)
->setSampleRate(sampleRate)
->setChannelCount(mInputChannelCount);
return setupCommonStreamParameters(builder);
}
/**
* Sets the stream parameters which are specific to playback, including device
* id and the dataCallback function, which must be set for low latency
* playback.
* @param builder The playback stream builder
*/
oboe::AudioStreamBuilder *LiveEffectEngine::setupPlaybackStreamParameters(
oboe::AudioStreamBuilder *builder) {
builder->setDataCallback(this)
->setErrorCallback(this)
->setDeviceId(mPlaybackDeviceId)
->setDirection(oboe::Direction::Output)
->setChannelCount(mOutputChannelCount);
return setupCommonStreamParameters(builder);
}
/**
* Set the stream parameters which are common to both recording and playback
* streams.
* @param builder The playback or recording stream builder
*/
oboe::AudioStreamBuilder *LiveEffectEngine::setupCommonStreamParameters(
oboe::AudioStreamBuilder *builder) {
// We request EXCLUSIVE mode since this will give us the lowest possible
// latency.
// If EXCLUSIVE mode isn't available the builder will fall back to SHARED
// mode.
builder->setAudioApi(mAudioApi)
->setFormat(mFormat)
->setSharingMode(oboe::SharingMode::Exclusive)
->setPerformanceMode(oboe::PerformanceMode::LowLatency);
return builder;
}
/**
* Close the stream. AudioStream::close() is a blocking call so
* the application does not need to add synchronization between
* onAudioReady() function and the thread calling close().
* [the closing thread is the UI thread in this sample].
* @param stream the stream to close
*/
void LiveEffectEngine::closeStream(std::shared_ptr<oboe::AudioStream> &stream) {
if (stream) {
oboe::Result result = stream->stop();
if (result != oboe::Result::OK) {
LOGW("Error stopping stream: %s", oboe::convertToText(result));
}
result = stream->close();
if (result != oboe::Result::OK) {
LOGE("Error closing stream: %s", oboe::convertToText(result));
} else {
LOGW("Successfully closed streams");
}
stream.reset();
}
}
/**
* Warn in logcat if non-low latency stream is created
* @param stream: newly created stream
*
*/
void LiveEffectEngine::warnIfNotLowLatency(std::shared_ptr<oboe::AudioStream> &stream) {
if (stream->getPerformanceMode() != oboe::PerformanceMode::LowLatency) {
LOGW(
"Stream is NOT low latency."
"Check your requested format, sample rate and channel count");
}
}
/**
* Handles playback stream's audio request. In this sample, we simply block-read
* from the record stream for the required samples.
*
* @param oboeStream: the playback stream that requesting additional samples
* @param audioData: the buffer to load audio samples for playback stream
* @param numFrames: number of frames to load to audioData buffer
* @return: DataCallbackResult::Continue.
*/
oboe::DataCallbackResult LiveEffectEngine::onAudioReady(
oboe::AudioStream *oboeStream, void *audioData, int32_t numFrames) {
return mFullDuplexPass.onAudioReady(oboeStream, audioData, numFrames);
}
/**
* Oboe notifies the application for "about to close the stream".
*
* @param oboeStream: the stream to close
* @param error: oboe's reason for closing the stream
*/
void LiveEffectEngine::onErrorBeforeClose(oboe::AudioStream *oboeStream,
oboe::Result error) {
LOGE("%s stream Error before close: %s",
oboe::convertToText(oboeStream->getDirection()),
oboe::convertToText(error));
}
/**
* Oboe notifies application that "the stream is closed"
*
* @param oboeStream
* @param error
*/
void LiveEffectEngine::onErrorAfterClose(oboe::AudioStream *oboeStream,
oboe::Result error) {
LOGE("%s stream Error after close: %s",
oboe::convertToText(oboeStream->getDirection()),
oboe::convertToText(error));
}
<|endoftext|> |
<commit_before>#include "CameraBase.h"
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
using namespace MathLib;
<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "CameraBase.h"
using namespace MathLib;
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
CCameraBase::CCameraBase(): CPlayer(PLAYER_SPECTATOR)
{
}
CCameraBase::~CCameraBase()
{
Leave();
}<|endoftext|> |
<commit_before>/* Copyright 2013-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <bm/bm_sim/pcap_file.h>
#include <bm/bm_sim/logger.h>
#include <cassert>
#include <chrono>
#include <thread>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstring>
namespace bm {
namespace {
// TODO(antonin): remove or good enough?
void pcap_fatal_error(const std::string &message) {
Logger::get()->critical(message);
exit(1);
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// This method should be in some separate C library
// Converts a timeval into a string.
// static
std::string
PcapPacket::timevalToString(const struct timeval *tv) {
std::stringstream result;
result << std::to_string(tv->tv_sec) << ":"
<< std::setfill('0') << std::setw(6) << std::to_string(tv->tv_usec);
return result.str();
}
////////////////////////////////////////////////////////////////////////////////
PcapFileBase::PcapFileBase(unsigned port, std::string filename)
: port(port),
filename(filename) {}
////////////////////////////////////////////////////////////////////////////////
// A stream-like abstraction of a PCAP (Packet capture) file.
PcapFileIn::PcapFileIn(unsigned port, std::string filename)
: PcapFileBase(port, filename),
pcap(nullptr),
current_header(nullptr),
current_data(nullptr) {
reset();
}
void
PcapFileIn::deallocate() {
if (pcap != nullptr)
pcap_close(pcap);
pcap = nullptr;
current_header = nullptr;
current_data = nullptr;
}
PcapFileIn::~PcapFileIn() {
deallocate();
}
void
PcapFileIn::open() {
char errbuf[PCAP_ERRBUF_SIZE];
pcap = pcap_open_offline(filename.c_str(), errbuf);
if (pcap == nullptr)
pcap_fatal_error(errbuf);
state = State::Opened;
}
void
PcapFileIn::reset() {
deallocate();
state = State::Uninitialized;
open();
}
bool
PcapFileIn::moveNext() {
switch (state) {
case State::AtEnd:
return false;
case State::Opened:
case State::Reading:
return advance();
case State::Uninitialized:
default:
pcap_fatal_error("Unexpected state");
return false; // unreachable
}
}
bool
PcapFileIn::advance() {
int pcap_status = pcap_next_ex(pcap, ¤t_header, ¤t_data);
if (pcap_status == 1) { // packet read without problems
if (current_header->caplen != current_header->len) {
pcap_fatal_error(
std::string("Incompletely captured packet in ") + filename);
}
state = State::Reading;
return true;
} else if (pcap_status == -2) { // end of file
state = State::AtEnd;
return false;
} else if (pcap_status == -1) {
pcap_fatal_error(
std::string("Error while reading packet from ") + filename);
} else {
// other status impossible, even 0 (which is only for live capture)
assert(0 && "Invalid pcap status");
}
// unreachable
return false;
}
std::unique_ptr<PcapPacket>
PcapFileIn::current() const {
switch (state) {
case State::Reading:
{
PcapPacket *packet = new PcapPacket(port, current_data, current_header);
return std::unique_ptr<PcapPacket>(packet);
}
case State::Opened:
pcap_fatal_error("Must call moveNext() before calling current()");
case State::AtEnd:
pcap_fatal_error("Cannot read past end-of-file");
case State::Uninitialized:
default:
pcap_fatal_error("Unexpected state");
}
return nullptr; // unreachable
}
bool PcapFileIn::atEOF() const {
return state == State::AtEnd;
}
////////////////////////////////////////////////////////////////////////////////
PcapFilesReader::PcapFilesReader(bool respectTiming,
unsigned wait_time_in_seconds)
: nonEmptyFiles(0),
wait_time_in_seconds(wait_time_in_seconds),
respectTiming(respectTiming),
started(false) {
timerclear(&zero);
}
void
PcapFilesReader::addFile(unsigned index, std::string file) {
auto f = std::unique_ptr<PcapFileIn>(new PcapFileIn(index, file));
files.push_back(std::move(f));
}
void
PcapFilesReader::scan() {
if (nonEmptyFiles == 0) {
BMLOG_DEBUG("Pcap reader: end of all input files");
// notifyAllEnd();
return;
}
int earliest_index = -1;
const struct timeval *earliest_time;
for (unsigned i=0; i < files.size(); i++) {
auto file = files.at(i).get();
if (file->atEOF()) continue;
std::unique_ptr<PcapPacket> p = file->current();
if (earliest_index == -1) {
earliest_index = i;
earliest_time = p->getTime();
} else {
const struct timeval *time = p->getTime();
if (timercmp(time, earliest_time, <)) {
earliest_index = i;
earliest_time = time;
}
}
}
assert(earliest_index >= 0);
struct timeval delay;
BMLOG_DEBUG("Pcap reader: first packet to send {}",
PcapPacket::timevalToString(earliest_time));
if (respectTiming) {
struct timeval delta;
timersub(earliest_time, &firstPacketTime, &delta);
struct timeval now;
gettimeofday(&now, nullptr);
struct timeval elapsed;
timersub(&now, &startTime, &elapsed);
timersub(&delta, &elapsed, &delay);
BMLOG_DEBUG("Pcap reader: delta {}, elapsed {}, delay {}",
PcapPacket::timevalToString(&delta),
PcapPacket::timevalToString(&elapsed),
PcapPacket::timevalToString(&delay));
} else {
timerclear(&delay);
}
schedulePacket((unsigned)earliest_index, &delay);
}
void PcapFilesReader::timerFired() {
auto file = files.at(scheduledIndex).get();
std::unique_ptr<PcapPacket> packet = file->current();
if (handler != nullptr)
handler(packet->getPort(), packet->getData(), packet->getLength(), cookie);
else
pcap_fatal_error("No packet handler set when sending packet");
bool success = file->moveNext();
if (!success)
nonEmptyFiles--;
scan();
}
void PcapFilesReader::schedulePacket(unsigned index, const struct timeval *at) {
scheduledIndex = index;
int compare = timercmp(at, &zero, <=);
if (compare) {
// packet should already have been sent
timerFired();
} else {
auto duration = std::chrono::seconds(at->tv_sec) +
std::chrono::microseconds(at->tv_usec);
BMLOG_DEBUG("Pcap reader: sleep for {}", duration.count());
std::this_thread::sleep_for(duration);
timerFired();
}
}
void PcapFilesReader::start() {
BMLOG_DEBUG("Pcap reader: starting PcapFilesReader {}",
std::to_string(files.size()));
// Give the switch some time to initialize
if (wait_time_in_seconds > 0) {
BMLOG_DEBUG("Pcap reader: waiting for {} seconds",
std::to_string(wait_time_in_seconds));
auto duration = std::chrono::seconds(wait_time_in_seconds);
std::this_thread::sleep_for(duration);
}
// Find out time of first packet
const struct timeval *firstTime = nullptr;
// Linear scan; we could use a priority queue, but probably this
// is more efficient for a small number of files.
for (auto &file : files) {
bool success = file->moveNext();
if (success) {
nonEmptyFiles++;
std::unique_ptr<PcapPacket> p = file->current();
const struct timeval *ptime = p->getTime();
if (firstTime == nullptr)
firstTime = ptime;
else if (timercmp(ptime, firstTime, <))
firstTime = ptime;
}
}
if (nonEmptyFiles > 0) {
assert(firstTime != nullptr);
firstPacketTime = *firstTime;
BMLOG_DEBUG("Pcap reader: first packet time {}",
PcapPacket::timevalToString(firstTime));
}
if (started)
pcap_fatal_error("Reader already started");
started = true;
gettimeofday(&startTime, nullptr);
scan();
}
PacketDispatcherIface::ReturnCode
PcapFilesReader::set_packet_handler(const PacketHandler &hnd, void *ck) {
assert(hnd);
assert(ck);
handler = hnd;
cookie = ck;
return ReturnCode::SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
PcapFileOut::PcapFileOut(unsigned port, std::string filename)
: PcapFileBase(port, filename) {
pcap = pcap_open_dead(0, 0);
if (pcap == nullptr)
pcap_fatal_error(
std::string("Could not open file ") + filename + " for writing");
dumper = pcap_dump_open(pcap, filename.c_str());
if (dumper == nullptr)
pcap_fatal_error(
std::string("Could not open file ") + filename + " for writing");
}
void
PcapFileOut::writePacket(const char *data, unsigned length) {
struct pcap_pkthdr pkt_header;
memset(&pkt_header, 0, sizeof(pkt_header));
gettimeofday(&pkt_header.ts, NULL);
pkt_header.caplen = length;
pkt_header.len = length;
pcap_dump(reinterpret_cast<unsigned char *>(dumper), &pkt_header,
reinterpret_cast<const unsigned char *>(data));
pcap_dump_flush(dumper);
}
PcapFileOut::~PcapFileOut() {
pcap_dump_close(dumper);
pcap_close(pcap);
}
////////////////////////////////////////////////////////////////////////////////
PcapFilesWriter::PcapFilesWriter() {}
void
PcapFilesWriter::addFile(unsigned port, std::string file) {
auto f = std::unique_ptr<PcapFileOut>(new PcapFileOut(port, file));
files.emplace(port, std::move(f));
}
void
PcapFilesWriter::send_packet(int port_num, const char *buffer, int len) {
unsigned idx = port_num;
if (files.find(port_num) == files.end())
// The behavior of the bmi_* library seems to be to ignore
// packets sent to inexistent interfaces, so we replicate it here.
return;
auto file = files.at(idx).get();
file->writePacket(buffer, len);
}
} // namespace bm
<commit_msg>fixed infinite recursion in scan() implementation in pcap_file.cpp (#133)<commit_after>/* Copyright 2013-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <bm/bm_sim/pcap_file.h>
#include <bm/bm_sim/logger.h>
#include <cassert>
#include <chrono>
#include <thread>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstring>
namespace bm {
namespace {
// TODO(antonin): remove or good enough?
void pcap_fatal_error(const std::string &message) {
Logger::get()->critical(message);
exit(1);
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// This method should be in some separate C library
// Converts a timeval into a string.
// static
std::string
PcapPacket::timevalToString(const struct timeval *tv) {
std::stringstream result;
result << std::to_string(tv->tv_sec) << ":"
<< std::setfill('0') << std::setw(6) << std::to_string(tv->tv_usec);
return result.str();
}
////////////////////////////////////////////////////////////////////////////////
PcapFileBase::PcapFileBase(unsigned port, std::string filename)
: port(port),
filename(filename) {}
////////////////////////////////////////////////////////////////////////////////
// A stream-like abstraction of a PCAP (Packet capture) file.
PcapFileIn::PcapFileIn(unsigned port, std::string filename)
: PcapFileBase(port, filename),
pcap(nullptr),
current_header(nullptr),
current_data(nullptr) {
reset();
}
void
PcapFileIn::deallocate() {
if (pcap != nullptr)
pcap_close(pcap);
pcap = nullptr;
current_header = nullptr;
current_data = nullptr;
}
PcapFileIn::~PcapFileIn() {
deallocate();
}
void
PcapFileIn::open() {
char errbuf[PCAP_ERRBUF_SIZE];
pcap = pcap_open_offline(filename.c_str(), errbuf);
if (pcap == nullptr)
pcap_fatal_error(errbuf);
state = State::Opened;
}
void
PcapFileIn::reset() {
deallocate();
state = State::Uninitialized;
open();
}
bool
PcapFileIn::moveNext() {
switch (state) {
case State::AtEnd:
return false;
case State::Opened:
case State::Reading:
return advance();
case State::Uninitialized:
default:
pcap_fatal_error("Unexpected state");
return false; // unreachable
}
}
bool
PcapFileIn::advance() {
int pcap_status = pcap_next_ex(pcap, ¤t_header, ¤t_data);
if (pcap_status == 1) { // packet read without problems
if (current_header->caplen != current_header->len) {
pcap_fatal_error(
std::string("Incompletely captured packet in ") + filename);
}
state = State::Reading;
return true;
} else if (pcap_status == -2) { // end of file
state = State::AtEnd;
return false;
} else if (pcap_status == -1) {
pcap_fatal_error(
std::string("Error while reading packet from ") + filename);
} else {
// other status impossible, even 0 (which is only for live capture)
assert(0 && "Invalid pcap status");
}
// unreachable
return false;
}
std::unique_ptr<PcapPacket>
PcapFileIn::current() const {
switch (state) {
case State::Reading:
{
PcapPacket *packet = new PcapPacket(port, current_data, current_header);
return std::unique_ptr<PcapPacket>(packet);
}
case State::Opened:
pcap_fatal_error("Must call moveNext() before calling current()");
case State::AtEnd:
pcap_fatal_error("Cannot read past end-of-file");
case State::Uninitialized:
default:
pcap_fatal_error("Unexpected state");
}
return nullptr; // unreachable
}
bool PcapFileIn::atEOF() const {
return state == State::AtEnd;
}
////////////////////////////////////////////////////////////////////////////////
PcapFilesReader::PcapFilesReader(bool respectTiming,
unsigned wait_time_in_seconds)
: nonEmptyFiles(0),
wait_time_in_seconds(wait_time_in_seconds),
respectTiming(respectTiming),
started(false) {
timerclear(&zero);
}
void
PcapFilesReader::addFile(unsigned index, std::string file) {
auto f = std::unique_ptr<PcapFileIn>(new PcapFileIn(index, file));
files.push_back(std::move(f));
}
void
PcapFilesReader::scan() {
while (true) {
if (nonEmptyFiles == 0) {
BMLOG_DEBUG("Pcap reader: end of all input files");
// notifyAllEnd();
return;
}
int earliest_index = -1;
const struct timeval *earliest_time;
for (unsigned i=0; i < files.size(); i++) {
auto file = files.at(i).get();
if (file->atEOF()) continue;
std::unique_ptr<PcapPacket> p = file->current();
if (earliest_index == -1) {
earliest_index = i;
earliest_time = p->getTime();
} else {
const struct timeval *time = p->getTime();
if (timercmp(time, earliest_time, <)) {
earliest_index = i;
earliest_time = time;
}
}
}
assert(earliest_index >= 0);
struct timeval delay;
BMLOG_DEBUG("Pcap reader: first packet to send {}",
PcapPacket::timevalToString(earliest_time));
if (respectTiming) {
struct timeval delta;
timersub(earliest_time, &firstPacketTime, &delta);
struct timeval now;
gettimeofday(&now, nullptr);
struct timeval elapsed;
timersub(&now, &startTime, &elapsed);
timersub(&delta, &elapsed, &delay);
BMLOG_DEBUG("Pcap reader: delta {}, elapsed {}, delay {}",
PcapPacket::timevalToString(&delta),
PcapPacket::timevalToString(&elapsed),
PcapPacket::timevalToString(&delay));
} else {
timerclear(&delay);
}
schedulePacket((unsigned)earliest_index, &delay);
}
}
void PcapFilesReader::timerFired() {
auto file = files.at(scheduledIndex).get();
std::unique_ptr<PcapPacket> packet = file->current();
if (handler != nullptr)
handler(packet->getPort(), packet->getData(), packet->getLength(), cookie);
else
pcap_fatal_error("No packet handler set when sending packet");
bool success = file->moveNext();
if (!success)
nonEmptyFiles--;
}
void PcapFilesReader::schedulePacket(unsigned index, const struct timeval *at) {
scheduledIndex = index;
int compare = timercmp(at, &zero, <=);
if (compare) {
// packet should already have been sent
timerFired();
} else {
auto duration = std::chrono::seconds(at->tv_sec) +
std::chrono::microseconds(at->tv_usec);
BMLOG_DEBUG("Pcap reader: sleep for {}", duration.count());
std::this_thread::sleep_for(duration);
timerFired();
}
}
void PcapFilesReader::start() {
BMLOG_DEBUG("Pcap reader: starting PcapFilesReader {}",
std::to_string(files.size()));
// Give the switch some time to initialize
if (wait_time_in_seconds > 0) {
BMLOG_DEBUG("Pcap reader: waiting for {} seconds",
std::to_string(wait_time_in_seconds));
auto duration = std::chrono::seconds(wait_time_in_seconds);
std::this_thread::sleep_for(duration);
}
// Find out time of first packet
const struct timeval *firstTime = nullptr;
// Linear scan; we could use a priority queue, but probably this
// is more efficient for a small number of files.
for (auto &file : files) {
bool success = file->moveNext();
if (success) {
nonEmptyFiles++;
std::unique_ptr<PcapPacket> p = file->current();
const struct timeval *ptime = p->getTime();
if (firstTime == nullptr)
firstTime = ptime;
else if (timercmp(ptime, firstTime, <))
firstTime = ptime;
}
}
if (nonEmptyFiles > 0) {
assert(firstTime != nullptr);
firstPacketTime = *firstTime;
BMLOG_DEBUG("Pcap reader: first packet time {}",
PcapPacket::timevalToString(firstTime));
}
if (started)
pcap_fatal_error("Reader already started");
started = true;
gettimeofday(&startTime, nullptr);
scan();
}
PacketDispatcherIface::ReturnCode
PcapFilesReader::set_packet_handler(const PacketHandler &hnd, void *ck) {
assert(hnd);
assert(ck);
handler = hnd;
cookie = ck;
return ReturnCode::SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
PcapFileOut::PcapFileOut(unsigned port, std::string filename)
: PcapFileBase(port, filename) {
pcap = pcap_open_dead(0, 0);
if (pcap == nullptr)
pcap_fatal_error(
std::string("Could not open file ") + filename + " for writing");
dumper = pcap_dump_open(pcap, filename.c_str());
if (dumper == nullptr)
pcap_fatal_error(
std::string("Could not open file ") + filename + " for writing");
}
void
PcapFileOut::writePacket(const char *data, unsigned length) {
struct pcap_pkthdr pkt_header;
memset(&pkt_header, 0, sizeof(pkt_header));
gettimeofday(&pkt_header.ts, NULL);
pkt_header.caplen = length;
pkt_header.len = length;
pcap_dump(reinterpret_cast<unsigned char *>(dumper), &pkt_header,
reinterpret_cast<const unsigned char *>(data));
pcap_dump_flush(dumper);
}
PcapFileOut::~PcapFileOut() {
pcap_dump_close(dumper);
pcap_close(pcap);
}
////////////////////////////////////////////////////////////////////////////////
PcapFilesWriter::PcapFilesWriter() {}
void
PcapFilesWriter::addFile(unsigned port, std::string file) {
auto f = std::unique_ptr<PcapFileOut>(new PcapFileOut(port, file));
files.emplace(port, std::move(f));
}
void
PcapFilesWriter::send_packet(int port_num, const char *buffer, int len) {
unsigned idx = port_num;
if (files.find(port_num) == files.end())
// The behavior of the bmi_* library seems to be to ignore
// packets sent to inexistent interfaces, so we replicate it here.
return;
auto file = files.at(idx).get();
file->writePacket(buffer, len);
}
} // namespace bm
<|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 <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "net/base/escape.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptSource.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_test.h"
using WebKit::WebFrame;
using WebKit::WebScriptSource;
using WebKit::WebString;
#if defined(OS_WIN)
#define TEST_PLUGIN_NAME "npapi_test_plugin.dll"
#elif defined(OS_MACOSX)
#define TEST_PLUGIN_NAME "npapi_test_plugin.plugin"
#elif defined(OS_POSIX)
#define TEST_PLUGIN_NAME "libnpapi_test_plugin.so"
#endif
#if defined(OS_MACOSX)
#define TEST_PLUGIN_DIRECTORY "PlugIns"
#else
#define TEST_PLUGIN_DIRECTORY "plugins"
#endif
// Ignore these until 64-bit plugin build is fixed. http://crbug.com/18337
#if !defined(ARCH_CPU_64_BITS)
// Provides functionality for creating plugin tests.
class PluginTest : public TestShellTest {
public:
PluginTest() {
FilePath executable_directory;
PathService::Get(base::DIR_EXE, &executable_directory);
plugin_src_ = executable_directory.AppendASCII(TEST_PLUGIN_NAME);
CHECK(file_util::PathExists(plugin_src_));
plugin_file_path_ = executable_directory.AppendASCII(TEST_PLUGIN_DIRECTORY);
file_util::CreateDirectory(plugin_file_path_);
plugin_file_path_ = plugin_file_path_.AppendASCII(TEST_PLUGIN_NAME);
}
void CopyTestPlugin() {
// On Linux, we need to delete before copying because if the plugin is a
// hard link, the copy will fail.
DeleteTestPlugin();
ASSERT_TRUE(file_util::CopyDirectory(plugin_src_, plugin_file_path_, true));
}
void DeleteTestPlugin() {
file_util::Delete(plugin_file_path_, true);
}
virtual void SetUp() {
CopyTestPlugin();
TestShellTest::SetUp();
}
virtual void TearDown() {
DeleteTestPlugin();
TestShellTest::TearDown();
}
FilePath plugin_src_;
FilePath plugin_file_path_;
};
#if !defined(OS_LINUX)
// TODO(tony): http://code.google.com/p/chromium/issues/detail?id=51402
// Tests navigator.plugins.refresh() works.
TEST_F(PluginTest, Refresh) {
std::string html = "\
<div id='result'>Test running....</div>\
<script>\
function check() {\
var l = navigator.plugins.length;\
var result = document.getElementById('result');\
for(var i = 0; i < l; i++) {\
if (navigator.plugins[i].filename == '" TEST_PLUGIN_NAME "') {\
result.innerHTML = 'DONE';\
break;\
}\
}\
\
if (result.innerHTML != 'DONE')\
result.innerHTML = 'FAIL';\
}\
</script>\
";
WebScriptSource call_check(
WebString::fromUTF8("check();"));
WebScriptSource refresh(
WebString::fromUTF8("navigator.plugins.refresh(false)"));
// Remove any leftover from previous tests if they exist. We must also
// refresh WebKit's plugin cache since it might have had an entry for the
// test plugin from a previous test.
DeleteTestPlugin();
ASSERT_FALSE(file_util::PathExists(plugin_file_path_));
test_shell_->webView()->mainFrame()->executeScript(refresh);
test_shell_->webView()->mainFrame()->loadHTMLString(
html, GURL("about:blank"));
test_shell_->WaitTestFinished();
std::string text;
test_shell_->webView()->mainFrame()->executeScript(call_check);
text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8();
ASSERT_EQ(text, "FAIL");
CopyTestPlugin();
test_shell_->webView()->mainFrame()->executeScript(refresh);
test_shell_->webView()->mainFrame()->executeScript(call_check);
text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8();
ASSERT_EQ(text, "DONE");
}
#endif
// Tests that if a frame is deleted as a result of calling NPP_HandleEvent, we
// don't crash.
TEST_F(PluginTest, DeleteFrameDuringEvent) {
FilePath test_html = data_dir_;
test_html = test_html.AppendASCII("plugins");
test_html = test_html.AppendASCII("delete_frame.html");
test_shell_->LoadFile(test_html);
test_shell_->WaitTestFinished();
WebKit::WebMouseEvent input;
input.button = WebKit::WebMouseEvent::ButtonLeft;
input.x = 50;
input.y = 50;
input.type = WebKit::WebInputEvent::MouseUp;
test_shell_->webView()->handleInputEvent(input);
// No crash means we passed.
}
#if defined(OS_WIN)
BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lparam) {
HWND* plugin_hwnd = reinterpret_cast<HWND*>(lparam);
if (*plugin_hwnd) {
// More than one child window found, unexpected.
plugin_hwnd = NULL;
return FALSE;
}
*plugin_hwnd = hwnd;
return TRUE;
}
// Tests that hiding/showing the parent frame hides/shows the plugin.
TEST_F(PluginTest, PluginVisibilty) {
FilePath test_html = data_dir_;
test_html = test_html.AppendASCII("plugins");
test_html = test_html.AppendASCII("plugin_visibility.html");
test_shell_->LoadFile(test_html);
test_shell_->WaitTestFinished();
WebFrame* main_frame = test_shell_->webView()->mainFrame();
HWND frame_hwnd = test_shell_->webViewWnd();
HWND plugin_hwnd = NULL;
EnumChildWindows(frame_hwnd, EnumChildProc,
reinterpret_cast<LPARAM>(&plugin_hwnd));
ASSERT_TRUE(plugin_hwnd != NULL);
ASSERT_FALSE(IsWindowVisible(plugin_hwnd));
main_frame->executeScript(WebString::fromUTF8("showPlugin(true)"));
ASSERT_TRUE(IsWindowVisible(plugin_hwnd));
main_frame->executeScript(WebString::fromUTF8("showFrame(false)"));
ASSERT_FALSE(IsWindowVisible(plugin_hwnd));
main_frame->executeScript(WebString::fromUTF8("showFrame(true)"));
ASSERT_TRUE(IsWindowVisible(plugin_hwnd));
}
#endif
#endif //!ARCH_CPU_64_BITS
<commit_msg>Revert "Disable failing test on Linux."<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 <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "net/base/escape.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptSource.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_test.h"
using WebKit::WebFrame;
using WebKit::WebScriptSource;
using WebKit::WebString;
#if defined(OS_WIN)
#define TEST_PLUGIN_NAME "npapi_test_plugin.dll"
#elif defined(OS_MACOSX)
#define TEST_PLUGIN_NAME "npapi_test_plugin.plugin"
#elif defined(OS_POSIX)
#define TEST_PLUGIN_NAME "libnpapi_test_plugin.so"
#endif
#if defined(OS_MACOSX)
#define TEST_PLUGIN_DIRECTORY "PlugIns"
#else
#define TEST_PLUGIN_DIRECTORY "plugins"
#endif
// Ignore these until 64-bit plugin build is fixed. http://crbug.com/18337
#if !defined(ARCH_CPU_64_BITS)
// Provides functionality for creating plugin tests.
class PluginTest : public TestShellTest {
public:
PluginTest() {
FilePath executable_directory;
PathService::Get(base::DIR_EXE, &executable_directory);
plugin_src_ = executable_directory.AppendASCII(TEST_PLUGIN_NAME);
CHECK(file_util::PathExists(plugin_src_));
plugin_file_path_ = executable_directory.AppendASCII(TEST_PLUGIN_DIRECTORY);
file_util::CreateDirectory(plugin_file_path_);
plugin_file_path_ = plugin_file_path_.AppendASCII(TEST_PLUGIN_NAME);
}
void CopyTestPlugin() {
// On Linux, we need to delete before copying because if the plugin is a
// hard link, the copy will fail.
DeleteTestPlugin();
ASSERT_TRUE(file_util::CopyDirectory(plugin_src_, plugin_file_path_, true));
}
void DeleteTestPlugin() {
file_util::Delete(plugin_file_path_, true);
}
virtual void SetUp() {
CopyTestPlugin();
TestShellTest::SetUp();
}
virtual void TearDown() {
DeleteTestPlugin();
TestShellTest::TearDown();
}
FilePath plugin_src_;
FilePath plugin_file_path_;
};
// Tests navigator.plugins.refresh() works.
TEST_F(PluginTest, Refresh) {
std::string html = "\
<div id='result'>Test running....</div>\
<script>\
function check() {\
var l = navigator.plugins.length;\
var result = document.getElementById('result');\
for(var i = 0; i < l; i++) {\
if (navigator.plugins[i].filename == '" TEST_PLUGIN_NAME "') {\
result.innerHTML = 'DONE';\
break;\
}\
}\
\
if (result.innerHTML != 'DONE')\
result.innerHTML = 'FAIL';\
}\
</script>\
";
WebScriptSource call_check(
WebString::fromUTF8("check();"));
WebScriptSource refresh(
WebString::fromUTF8("navigator.plugins.refresh(false)"));
// Remove any leftover from previous tests if they exist. We must also
// refresh WebKit's plugin cache since it might have had an entry for the
// test plugin from a previous test.
DeleteTestPlugin();
ASSERT_FALSE(file_util::PathExists(plugin_file_path_));
test_shell_->webView()->mainFrame()->executeScript(refresh);
test_shell_->webView()->mainFrame()->loadHTMLString(
html, GURL("about:blank"));
test_shell_->WaitTestFinished();
std::string text;
test_shell_->webView()->mainFrame()->executeScript(call_check);
text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8();
ASSERT_EQ(text, "FAIL");
CopyTestPlugin();
test_shell_->webView()->mainFrame()->executeScript(refresh);
test_shell_->webView()->mainFrame()->executeScript(call_check);
text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8();
ASSERT_EQ(text, "DONE");
}
// Tests that if a frame is deleted as a result of calling NPP_HandleEvent, we
// don't crash.
TEST_F(PluginTest, DeleteFrameDuringEvent) {
FilePath test_html = data_dir_;
test_html = test_html.AppendASCII("plugins");
test_html = test_html.AppendASCII("delete_frame.html");
test_shell_->LoadFile(test_html);
test_shell_->WaitTestFinished();
WebKit::WebMouseEvent input;
input.button = WebKit::WebMouseEvent::ButtonLeft;
input.x = 50;
input.y = 50;
input.type = WebKit::WebInputEvent::MouseUp;
test_shell_->webView()->handleInputEvent(input);
// No crash means we passed.
}
#if defined(OS_WIN)
BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lparam) {
HWND* plugin_hwnd = reinterpret_cast<HWND*>(lparam);
if (*plugin_hwnd) {
// More than one child window found, unexpected.
plugin_hwnd = NULL;
return FALSE;
}
*plugin_hwnd = hwnd;
return TRUE;
}
// Tests that hiding/showing the parent frame hides/shows the plugin.
TEST_F(PluginTest, PluginVisibilty) {
FilePath test_html = data_dir_;
test_html = test_html.AppendASCII("plugins");
test_html = test_html.AppendASCII("plugin_visibility.html");
test_shell_->LoadFile(test_html);
test_shell_->WaitTestFinished();
WebFrame* main_frame = test_shell_->webView()->mainFrame();
HWND frame_hwnd = test_shell_->webViewWnd();
HWND plugin_hwnd = NULL;
EnumChildWindows(frame_hwnd, EnumChildProc,
reinterpret_cast<LPARAM>(&plugin_hwnd));
ASSERT_TRUE(plugin_hwnd != NULL);
ASSERT_FALSE(IsWindowVisible(plugin_hwnd));
main_frame->executeScript(WebString::fromUTF8("showPlugin(true)"));
ASSERT_TRUE(IsWindowVisible(plugin_hwnd));
main_frame->executeScript(WebString::fromUTF8("showFrame(false)"));
ASSERT_FALSE(IsWindowVisible(plugin_hwnd));
main_frame->executeScript(WebString::fromUTF8("showFrame(true)"));
ASSERT_TRUE(IsWindowVisible(plugin_hwnd));
}
#endif
#endif //!ARCH_CPU_64_BITS
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2017 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <votca/xtp/gwbse.h>
#include <boost/format.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <votca/tools/constants.h>
//#include "mathimf.h"
using boost::format;
using namespace boost::filesystem;
namespace votca {
namespace xtp {
namespace ub = boost::numeric::ublas;
// +++++++++++++++++++++++++++++ //
// MBPT MEMBER FUNCTIONS //
// +++++++++++++++++++++++++++++ //
void GWBSE::FullQPHamiltonian(){
// constructing full QP Hamiltonian, storage in vxc
_vxc = -_vxc + _sigma_x + _sigma_c;
// diagonal elements are given by _qp_energies
for (unsigned _m = 0; _m < _vxc.size1(); _m++ ){
_vxc( _m,_m ) = _qp_energies( _m + _qpmin );
}
// sigma matrices can be freed
_sigma_x.resize(0);
_sigma_c.resize(0);
if ( _do_qp_diag ){
_qp_diag_energies.resize(_vxc.size1());
_qp_diag_coefficients.resize(_vxc.size1(), _vxc.size1());
linalg_eigenvalues(_vxc, _qp_diag_energies, _qp_diag_coefficients);
}
return;
}
void GWBSE::sigma_c_setup(const TCMatrix& _Mmn) {
// iterative refinement of qp energies
int _max_iter = 15;
unsigned _levelsum = _Mmn[0].size2(); // total number of bands
unsigned _gwsize = _Mmn[0].size1(); // size of the GW basis
const double pi = boost::math::constants::pi<double>();
ub::vector<double>& dftenergies=_orbitals->MOEnergies();
// initial _qp_energies are dft energies
ub::vector<double>_qp_old_rpa=_qp_energies;
ub::vector<double>_qp_old=_qp_energies;
bool energies_converged=false;
_sigma_c.resize(_qptotal);
// only diagonal elements except for in final iteration
for (int _i_iter = 0; _i_iter < _max_iter - 1; _i_iter++) {
// loop over all GW levels
#pragma omp parallel for
for (unsigned _gw_level = 0; _gw_level < _qptotal; _gw_level++) {
_sigma_c(_gw_level, _gw_level) = 0;
double qpmin = _qp_energies(_gw_level + _qpmin);
const ub::matrix<real_gwbse>& Mmn = _Mmn[ _gw_level + _qpmin ];
// loop over all functions in GW basis
for (unsigned _i_gw = 0; _i_gw < _gwsize; _i_gw++) {
double ppm_freq = _ppm_freq(_i_gw);
double fac = _ppm_weight(_i_gw) * ppm_freq;
// loop over all bands
for (unsigned _i = 0; _i < _levelsum; _i++) {
double occ = 1.0;
if (_i > _homo) occ = -1.0; // sign for empty levels
// energy denominator
double _denom = qpmin - _qp_energies(_i) + occ*ppm_freq;
double _stab = 1.0;
if (std::abs(_denom) < 0.25) {
_stab = 0.25 * (1.0 - std::cos(4.0 * pi * std::abs(_denom)));
}
double _factor =0.5* fac * _stab / _denom; //Hartree
// sigma_c diagonal elements
_sigma_c(_gw_level, _gw_level) += _factor * Mmn(_i_gw, _i) * Mmn(_i_gw, _i);
}// bands
}// GW functions
// update _qp_energies
_qp_energies(_gw_level + _qpmin) = dftenergies(_gw_level + _qpmin) + _sigma_x(_gw_level, _gw_level) + _sigma_c(_gw_level, _gw_level) - _vxc(_gw_level, _gw_level);
}// all bands
//cout << " end of qp refinement step (diagonal) " << _i_iter << "\n" << endl;
_qp_old = _qp_old - _qp_energies;
energies_converged = true;
for (unsigned l = 0; l < _qp_old.size(); l++) {
if (std::abs(_qp_old(l)) > _qp_limit) {
energies_converged = false;
break;
}
}
if (energies_converged) {
CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << " Converged after " << _i_iter+1 << " qp_energy iterations." << flush;
break;
} else {
_qp_old = _qp_energies;
}
} // iterations
_qp_converged = true;
_qp_old_rpa= _qp_old_rpa - _qp_energies;
for (unsigned l = 0; l < _qp_old_rpa.size(); l++) {
if (std::abs(_qp_old_rpa(l)) > _shift_limit) {
_qp_converged = false;
break;
}
}
double _DFTgap =dftenergies(_homo + 1) - dftenergies(_homo);
double _QPgap = _qp_energies( _homo +1 ) - _qp_energies( _homo );
_shift = _QPgap - _DFTgap;
// qp energies outside the update range are simply shifted.
for(unsigned i=_qpmax+1;i<dftenergies.size();++i){
_qp_energies(i)=dftenergies(i)+_shift;
}
if ( ! _iterate_qp ) _qp_converged = true;
// only if _shift is converged
if (_qp_converged) {
// in final step, also calc offdiagonal elements
// initialize sigma_c to zero at the beginning
//this is not the fastest algorithm but faster ones throw igwbse off, so this is good enough.
#pragma omp parallel for
for (unsigned _gw_level = 0; _gw_level < _qptotal; _gw_level++) {
double qpmin_e=_qp_energies(_gw_level + _qpmin);
const ub::matrix<real_gwbse>& Mmn = _Mmn[ _gw_level + _qpmin ];
for (unsigned _m = 0; _m < _gw_level; _m++) {
_sigma_c(_gw_level, _m) = 0;
const ub::matrix<real_gwbse>& Mmn2 = _Mmn[_m + _qpmin];
// loop over all functions in GW basis
for (unsigned _i_gw = 0; _i_gw < _gwsize; _i_gw++) {
double ppm_freq = _ppm_freq(_i_gw);
double fac = _ppm_weight(_i_gw) * ppm_freq;
// loop over all screening levels
for (unsigned _i = 0; _i < _levelsum; _i++) {
double occ = 1.0;
if (_i > _homo) occ = -1.0; // sign for empty levels
// energy denominator
double _denom = qpmin_e - _qp_energies(_i) + occ * ppm_freq;
double _stab = 1.0;
if (std::abs(_denom) < 0.25) {
_stab = 0.25 * (1.0 - std::cos(4.0 * pi * std::abs(_denom)));
}
double _factor = 0.5*fac * Mmn(_i_gw, _i) * _stab / _denom; //Hartree
_sigma_c(_gw_level, _m) += _factor * Mmn2(_i_gw, _i);
}// screening levels
}// GW functions
}// GW row
_qp_energies(_gw_level + _qpmin) = dftenergies(_gw_level + _qpmin) + _sigma_x(_gw_level, _gw_level) + _sigma_c(_gw_level, _gw_level) - _vxc(_gw_level, _gw_level);
} // GW col
}
return;
} // sigma_c_setup
void GWBSE::sigma_x_setup(const TCMatrix& _Mmn){
// initialize sigma_x
_sigma_x.resize(_qptotal);
int _size = _Mmn[0].size1();
// band 1 loop over all GW levels
#pragma omp parallel for
for ( unsigned _m1 = 0 ; _m1 < _qptotal ; _m1++ ){
const ub::matrix<real_gwbse>& M1mn = _Mmn[ _m1 + _qpmin ];
// band 2 loop over all GW levels
//for ( int _m2 = _qpmin ; _m2 <= _qpmax ; _m2++ ){
for ( unsigned _m2 = 0 ; _m2 <= _m1 ; _m2++ ){
_sigma_x( _m1, _m2 )=0;
const ub::matrix<real_gwbse>& M2mn = _Mmn[ _m2 + _qpmin ];
// loop over all basis functions
for ( int _i_gw = 0 ; _i_gw < _size ; _i_gw++ ){
// loop over all occupied bands used in screening
for ( unsigned _i_occ = 0 ; _i_occ <= _homo ; _i_occ++ ){
_sigma_x( _m1, _m2 ) -= M1mn( _i_gw , _i_occ ) * M2mn( _i_gw , _i_occ );
} // occupied bands
} // gwbasis functions
} // level 2
} // level 1
// factor for hybrid DFT
_sigma_x = ( 1.0 - _ScaHFX ) * _sigma_x;
return;
}
void GWBSE::sigma_prepare_threecenters(TCMatrix& _Mmn){
#if (GWBSE_DOUBLE)
const ub::matrix<double>& ppm_phi=_ppm_phi;
#else
const ub::matrix<float> ppm_phi=_ppm_phi;
#endif
#pragma omp parallel for
for ( int _m_level = 0 ; _m_level < _Mmn.get_mtot(); _m_level++ ){
// get Mmn for this _m_level
// and multiply with _ppm_phi = eigenvectors of epsilon
_Mmn[ _m_level ] = ub::prod( ppm_phi , _Mmn[_m_level] );
}
return;
}
}
};
<commit_msg>small beauty stuff<commit_after>/*
* Copyright 2009-2017 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <votca/xtp/gwbse.h>
#include <boost/format.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <votca/tools/constants.h>
//#include "mathimf.h"
using boost::format;
using namespace boost::filesystem;
namespace votca {
namespace xtp {
namespace ub = boost::numeric::ublas;
// +++++++++++++++++++++++++++++ //
// MBPT MEMBER FUNCTIONS //
// +++++++++++++++++++++++++++++ //
void GWBSE::FullQPHamiltonian(){
// constructing full QP Hamiltonian, storage in vxc
_vxc = -_vxc + _sigma_x + _sigma_c;
// diagonal elements are given by _qp_energies
for (unsigned _m = 0; _m < _vxc.size1(); _m++ ){
_vxc( _m,_m ) = _qp_energies( _m + _qpmin );
}
// sigma matrices can be freed
_sigma_x.resize(0);
_sigma_c.resize(0);
if ( _do_qp_diag ){
_qp_diag_energies.resize(_vxc.size1());
_qp_diag_coefficients.resize(_vxc.size1(), _vxc.size1());
linalg_eigenvalues(_vxc, _qp_diag_energies, _qp_diag_coefficients);
}
return;
}
void GWBSE::sigma_c_setup(const TCMatrix& _Mmn) {
// iterative refinement of qp energies
int _max_iter = 15;
unsigned _levelsum = _Mmn[0].size2(); // total number of bands
unsigned _gwsize = _Mmn[0].size1(); // size of the GW basis
const double pi = boost::math::constants::pi<double>();
ub::vector<double>& dftenergies=_orbitals->MOEnergies();
// initial _qp_energies are dft energies
ub::vector<double>_qp_old_rpa=_qp_energies;
ub::vector<double>_qp_old=_qp_energies;
bool energies_converged=false;
_sigma_c.resize(_qptotal);
// only diagonal elements except for in final iteration
for (int _i_iter = 0; _i_iter < _max_iter - 1; _i_iter++) {
// loop over all GW levels
#pragma omp parallel for
for (unsigned _gw_level = 0; _gw_level < _qptotal; _gw_level++) {
_sigma_c(_gw_level, _gw_level) = 0;
double qpmin = _qp_energies(_gw_level + _qpmin);
const ub::matrix<real_gwbse>& Mmn = _Mmn[ _gw_level + _qpmin ];
// loop over all functions in GW basis
for (unsigned _i_gw = 0; _i_gw < _gwsize; _i_gw++) {
double ppm_freq = _ppm_freq(_i_gw);
double fac = _ppm_weight(_i_gw) * ppm_freq;
// loop over all bands
for (unsigned _i = 0; _i < _levelsum; _i++) {
double occ = 1.0;
if (_i > _homo) occ = -1.0; // sign for empty levels
// energy denominator
double _denom = qpmin - _qp_energies(_i) + occ*ppm_freq;
double _stab = 1.0;
if (std::abs(_denom) < 0.25) {
_stab = 0.25 * (1.0 - std::cos(4.0 * pi * std::abs(_denom)));
}
double _factor =0.5* fac * _stab / _denom; //Hartree
// sigma_c diagonal elements
_sigma_c(_gw_level, _gw_level) += _factor * Mmn(_i_gw, _i) * Mmn(_i_gw, _i);
}// bands
}// GW functions
// update _qp_energies
_qp_energies(_gw_level + _qpmin) = dftenergies(_gw_level + _qpmin) + _sigma_x(_gw_level, _gw_level) + _sigma_c(_gw_level, _gw_level) - _vxc(_gw_level, _gw_level);
}// all bands
_qp_old = _qp_old - _qp_energies;
energies_converged = true;
for (unsigned l = 0; l < _qp_old.size(); l++) {
if (std::abs(_qp_old(l)) > _qp_limit) {
energies_converged = false;
break;
}
}
if (energies_converged) {
CTP_LOG(ctp::logDEBUG, *_pLog) << ctp::TimeStamp() << " Converged after " << _i_iter+1 << " qp_energy iterations." << flush;
break;
} else {
_qp_old = _qp_energies;
}
} // iterations
_qp_converged = true;
_qp_old_rpa= _qp_old_rpa - _qp_energies;
for (unsigned l = 0; l < _qp_old_rpa.size(); l++) {
if (std::abs(_qp_old_rpa(l)) > _shift_limit) {
_qp_converged = false;
break;
}
}
double _DFTgap =dftenergies(_homo + 1) - dftenergies(_homo);
double _QPgap = _qp_energies( _homo +1 ) - _qp_energies( _homo );
_shift = _QPgap - _DFTgap;
if(_iterate_qp){
// qp energies outside the update range are simply shifted.
for(unsigned i=_qpmax+1;i<dftenergies.size();++i){
_qp_energies(i)=dftenergies(i)+_shift;
}
}else{
_qp_converged = true;
}
// only if _shift is converged
if (_qp_converged) {
// in final step, also calc offdiagonal elements
// initialize sigma_c to zero at the beginning
//this is not the fastest algorithm but faster ones throw igwbse off, so this is good enough.
#pragma omp parallel for
for (unsigned _gw_level = 0; _gw_level < _qptotal; _gw_level++) {
double qpmin_e=_qp_energies(_gw_level + _qpmin);
const ub::matrix<real_gwbse>& Mmn = _Mmn[ _gw_level + _qpmin ];
for (unsigned _m = 0; _m < _gw_level; _m++) {
_sigma_c(_gw_level, _m) = 0;
const ub::matrix<real_gwbse>& Mmn2 = _Mmn[_m + _qpmin];
// loop over all functions in GW basis
for (unsigned _i_gw = 0; _i_gw < _gwsize; _i_gw++) {
double ppm_freq = _ppm_freq(_i_gw);
double fac = _ppm_weight(_i_gw) * ppm_freq;
// loop over all screening levels
for (unsigned _i = 0; _i < _levelsum; _i++) {
double occ = 1.0;
if (_i > _homo) occ = -1.0; // sign for empty levels
// energy denominator
double _denom = qpmin_e - _qp_energies(_i) + occ * ppm_freq;
double _stab = 1.0;
if (std::abs(_denom) < 0.25) {
_stab = 0.25 * (1.0 - std::cos(4.0 * pi * std::abs(_denom)));
}
double _factor = 0.5*fac * Mmn(_i_gw, _i) * _stab / _denom; //Hartree
_sigma_c(_gw_level, _m) += _factor * Mmn2(_i_gw, _i);
}// screening levels
}// GW functions
}// GW row
_qp_energies(_gw_level + _qpmin) = dftenergies(_gw_level + _qpmin) + _sigma_x(_gw_level, _gw_level) + _sigma_c(_gw_level, _gw_level) - _vxc(_gw_level, _gw_level);
} // GW col
}
return;
} // sigma_c_setup
void GWBSE::sigma_x_setup(const TCMatrix& _Mmn){
// initialize sigma_x
_sigma_x.resize(_qptotal);
int _size = _Mmn[0].size1();
// band 1 loop over all GW levels
#pragma omp parallel for
for ( unsigned _m1 = 0 ; _m1 < _qptotal ; _m1++ ){
const ub::matrix<real_gwbse>& M1mn = _Mmn[ _m1 + _qpmin ];
// band 2 loop over all GW levels
//for ( int _m2 = _qpmin ; _m2 <= _qpmax ; _m2++ ){
for ( unsigned _m2 = 0 ; _m2 <= _m1 ; _m2++ ){
_sigma_x( _m1, _m2 )=0;
const ub::matrix<real_gwbse>& M2mn = _Mmn[ _m2 + _qpmin ];
// loop over all basis functions
for ( int _i_gw = 0 ; _i_gw < _size ; _i_gw++ ){
// loop over all occupied bands used in screening
for ( unsigned _i_occ = 0 ; _i_occ <= _homo ; _i_occ++ ){
_sigma_x( _m1, _m2 ) -= M1mn( _i_gw , _i_occ ) * M2mn( _i_gw , _i_occ );
} // occupied bands
} // gwbasis functions
} // level 2
} // level 1
// factor for hybrid DFT
_sigma_x = ( 1.0 - _ScaHFX ) * _sigma_x;
return;
}
void GWBSE::sigma_prepare_threecenters(TCMatrix& _Mmn){
#if (GWBSE_DOUBLE)
const ub::matrix<double>& ppm_phi=_ppm_phi;
#else
const ub::matrix<float> ppm_phi=_ppm_phi;
#endif
#pragma omp parallel for
for ( int _m_level = 0 ; _m_level < _Mmn.get_mtot(); _m_level++ ){
// get Mmn for this _m_level
// and multiply with _ppm_phi = eigenvectors of epsilon
_Mmn[ _m_level ] = ub::prod( ppm_phi , _Mmn[_m_level] );
}
return;
}
}
};
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rtl_old_testint64.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:46:55 $
*
* 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
*
************************************************************************/
// LLA:
// this file is converted to use with testshl2
// original was placed in sal/test/textenc.cxx
// fndef _OSL_DIAGNOSE_H_
// nclude <osl/diagnose.h>
// #endif
#include <sal/types.h>
#define TEST_ENSURE(c, m) CPPUNIT_ASSERT_MESSAGE((m), (c))
// #if OSL_DEBUG_LEVEL > 0
// #define TEST_ENSURE(c, m) OSL_ENSURE(c, m)
// #else
// #define TEST_ENSURE(c, m) OSL_VERIFY(c)
// #endif
#include <cppunit/simpleheader.hxx>
// -----------------------------------------------------------------------------
namespace rtl_math
{
class int64 : public CppUnit::TestFixture
{
public:
void test_int64();
CPPUNIT_TEST_SUITE( int64 );
CPPUNIT_TEST( test_int64 );
CPPUNIT_TEST_SUITE_END( );
};
void int64::test_int64()
{
#ifndef SAL_INT64_IS_STRUCT
#ifdef UNX
sal_Int64 i1 = -3223372036854775807LL;
sal_uInt64 u1 = 5223372036854775807ULL;
#else
sal_Int64 i1 = -3223372036854775807;
sal_uInt64 u1 = 5223372036854775807;
#endif
sal_Int64 i2 = 0;
sal_uInt64 u2 = 0;
#else
sal_Int64 i1;
sal_setInt64(&i1, 3965190145L, -750499787L);
sal_Int64 i2 = { 0, 0 };
sal_uInt64 u1;
sal_setUInt64(&u1, 1651507199UL, 1216161073UL);
sal_uInt64 u2 = {0, 0 };
#endif
sal_uInt32 low = 0;
sal_Int32 high = 0;
sal_getInt64(i1, &low, &high);
sal_setInt64(&i2, low, high);
sal_uInt32 ulow = 0;
sal_uInt32 uhigh = 0;
sal_getUInt64(u1, &ulow, &uhigh);
sal_setUInt64(&u2, ulow, uhigh);
#ifndef SAL_INT64_IS_STRUCT
TEST_ENSURE( i1 == i2, "test_int64 error 1");
TEST_ENSURE( u1 == u2, "test_int64 error 2");
#else
TEST_ENSURE( (i1.Part1 == i2.Part1) && (i1.Part2 == i2.Part2),
"test_int64 error 1");
TEST_ENSURE( (u1.Part1 == u2.Part1) && (u1.Part2 == u2.Part2),
"test_int64 error 2");
#endif
return;
}
} // namespace rtl_math
// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_math::int64, "rtl_math" );
// -----------------------------------------------------------------------------
NOADDITIONAL;
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.140); FILE MERGED 2006/09/01 17:34:11 kaib 1.3.140.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rtl_old_testint64.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:57:00 $
*
* 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_sal.hxx"
// LLA:
// this file is converted to use with testshl2
// original was placed in sal/test/textenc.cxx
// fndef _OSL_DIAGNOSE_H_
// nclude <osl/diagnose.h>
// #endif
#include <sal/types.h>
#define TEST_ENSURE(c, m) CPPUNIT_ASSERT_MESSAGE((m), (c))
// #if OSL_DEBUG_LEVEL > 0
// #define TEST_ENSURE(c, m) OSL_ENSURE(c, m)
// #else
// #define TEST_ENSURE(c, m) OSL_VERIFY(c)
// #endif
#include <cppunit/simpleheader.hxx>
// -----------------------------------------------------------------------------
namespace rtl_math
{
class int64 : public CppUnit::TestFixture
{
public:
void test_int64();
CPPUNIT_TEST_SUITE( int64 );
CPPUNIT_TEST( test_int64 );
CPPUNIT_TEST_SUITE_END( );
};
void int64::test_int64()
{
#ifndef SAL_INT64_IS_STRUCT
#ifdef UNX
sal_Int64 i1 = -3223372036854775807LL;
sal_uInt64 u1 = 5223372036854775807ULL;
#else
sal_Int64 i1 = -3223372036854775807;
sal_uInt64 u1 = 5223372036854775807;
#endif
sal_Int64 i2 = 0;
sal_uInt64 u2 = 0;
#else
sal_Int64 i1;
sal_setInt64(&i1, 3965190145L, -750499787L);
sal_Int64 i2 = { 0, 0 };
sal_uInt64 u1;
sal_setUInt64(&u1, 1651507199UL, 1216161073UL);
sal_uInt64 u2 = {0, 0 };
#endif
sal_uInt32 low = 0;
sal_Int32 high = 0;
sal_getInt64(i1, &low, &high);
sal_setInt64(&i2, low, high);
sal_uInt32 ulow = 0;
sal_uInt32 uhigh = 0;
sal_getUInt64(u1, &ulow, &uhigh);
sal_setUInt64(&u2, ulow, uhigh);
#ifndef SAL_INT64_IS_STRUCT
TEST_ENSURE( i1 == i2, "test_int64 error 1");
TEST_ENSURE( u1 == u2, "test_int64 error 2");
#else
TEST_ENSURE( (i1.Part1 == i2.Part1) && (i1.Part2 == i2.Part2),
"test_int64 error 1");
TEST_ENSURE( (u1.Part1 == u2.Part1) && (u1.Part2 == u2.Part2),
"test_int64 error 2");
#endif
return;
}
} // namespace rtl_math
// -----------------------------------------------------------------------------
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_math::int64, "rtl_math" );
// -----------------------------------------------------------------------------
NOADDITIONAL;
<|endoftext|> |
<commit_before>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include <memory>
#include "iree/compiler/Conversion/HLOToHLO/Passes.h"
#include "iree/compiler/Conversion/HLOToLinalg/HLOToLinalgOnTensorPasses.h"
#include "iree/compiler/Conversion/LinalgToLinalg/Passes.h"
#include "iree/compiler/Dialect/Shape/Conversion/Passes.h"
#include "iree/compiler/Dialect/Shape/Transforms/Passes.h"
#include "mlir-hlo/Dialect/mhlo/transforms/passes.h"
#include "mlir/Conversion/SCFToStandard/SCFToStandard.h"
#include "mlir/Conversion/TosaToLinalg/TosaToLinalg.h"
#include "mlir/Conversion/TosaToSCF/TosaToSCF.h"
#include "mlir/Conversion/TosaToStandard/TosaToStandard.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/Shape/Transforms/Passes.h"
#include "mlir/Pass/PassOptions.h"
#include "mlir/Pass/PassRegistry.h"
#include "mlir/Transforms/Passes.h"
static llvm::cl::opt<bool> clEnableLinalgOnTensorsDispatch(
"iree-flow-dispatch-linalg-on-tensors",
llvm::cl::desc(
"Enable use of Linalg on tensors for dispatch region creation."),
llvm::cl::init(false));
// TODO(benvanik): change to a pipeline option.
static llvm::cl::opt<bool> clExportBenchmarkFuncs(
"iree-flow-export-benchmark-funcs",
llvm::cl::desc(
"Exports one function per original module entry point and "
"unique flow.executable that dispatches with dummy arguments."),
llvm::cl::init(false));
// TODO(benvanik): change to a pipeline option.
static llvm::cl::opt<bool> clTraceDispatchTensors(
"iree-flow-trace-dispatch-tensors2",
llvm::cl::desc(
"Trace runtime input/output tensors for each dispatch function."),
llvm::cl::init(false));
static llvm::cl::opt<bool> clEnable1x1ConvToMatmul(
"iree-flow-enable-1x1-conv-to-matmul",
llvm::cl::desc("Enable converting 1x1 linalg convolution ops to linalg "
"matmul ops pass."),
llvm::cl::init(true));
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {
// Prepare HLO for use as an input to the Flow dialect.
//
// HACK: this needs to be moved into the various tensorflow-specific import
// tools so that none of this code pulls in HLO. Today we still have
// dependencies on HLO for the legacy non-linalg-on-tensors path so it's fine
// here, but soon we'll be shifting away from that and only accepting upstream
// dialects like linalg.
static void buildHLOInputTransformPassPipeline(OpPassManager &passManager) {
passManager.addNestedPass<FuncOp>(
IREE::Flow::createHLOToHLOPreprocessingPass());
if (clEnableLinalgOnTensorsDispatch) {
// TODO(ataei): This should run as part of createHLOToHLOPreprocessingPass
// which will break VMLA backend.
passManager.addNestedPass<FuncOp>(createDecomposeHLOClampPass());
}
// Run passes to remove shape constraints. HLO lowering inserts them, but they
// are not desired here.
passManager.addNestedPass<FuncOp>(mlir::createRemoveShapeConstraintsPass());
}
// Prepare TOSA for use as an input to the Flow dialect.
static void buildTOSAInputTransformPassPipeline(OpPassManager &passManager) {
passManager.addNestedPass<FuncOp>(tosa::createTosaToSCF());
passManager.addNestedPass<FuncOp>(tosa::createTosaToStandard());
passManager.addNestedPass<FuncOp>(tosa::createTosaToLinalgOnTensors());
}
void buildInputTransformPassPipeline(OpPassManager &passManager) {
buildHLOInputTransformPassPipeline(passManager);
buildTOSAInputTransformPassPipeline(passManager);
passManager.addPass(createCanonicalizerPass());
}
void registerInputTransformPassPipeline() {
PassPipelineRegistration<> transformPassPipeline(
"iree-input-transformation-pipeline",
"Runs the full IREE flow dialect transformation pipeline",
[](OpPassManager &passManager) {
buildInputTransformPassPipeline(passManager);
});
}
void buildFlowTransformPassPipeline(OpPassManager &passManager,
bool dispatchLinalgOnTensors) {
//----------------------------------------------------------------------------
// Entry dialect cleanup
//----------------------------------------------------------------------------
// Currently we don't handle SCF ops well and have to convert them all to CFG.
// In the future it would be nice if we could have all of flow be both scf
// and cfg compatible.
passManager.addNestedPass<FuncOp>(mlir::createLowerToCFGPass());
// We also don't handle calls well on the old codepath; until we remove the
// use of the CFG we can continue inlining.
passManager.addPass(mlir::createInlinerPass());
// Convert `shape` dialect to `shapex` dialect.
passManager.addPass(Shape::createConvertShapeToShapexPass());
// Perform initial cleanup.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(mlir::createCSEPass());
// Legalize input types. We do this after flattening tuples so that we don't
// have to deal with them.
// TODO(nicolasvasilache): createLegalizeInputTypesPass is old and does not
// handle region conversion properly (parent cloned before children). Revisit
// when using ops with regions such as scf.for and linalg.generic.
passManager.addPass(IREE::Flow::createLegalizeInputTypesPass());
//----------------------------------------------------------------------------
// Shape materialization for buffer assignment and stream formation.
//
// Phase ordering constraints:
// - All tensor-level transformations which alter shapes must be complete
// prior to this phase.
//
// Pre-conditions:
// - Type conversion and sanitization of public function signatures.
// - "Root" dynamic tensors all pass through a single shapex.tie_shape
// use which associates them to their shape.
// - Loose, non-associated shapex.get_ranked_shape ops can exist anywhere
// and will be resolved.
// Post-conditions:
// - All dynamic tensors bridge through a shapex.tie_shape op with the
// appropriate shape.
// - No shapex.get_ranked_shape ops exist (they have been converted to
// concrete IR which materializes the shapes, either statically or
// dynamically).
// - Shape folding and canonicalization has been done.
//----------------------------------------------------------------------------
// Replaces variables with !shapex.ranked_shape types with individual
// variables for each dimension. This allows for constant dimensions to be
// DCE'd in following passes.
passManager.addPass(IREE::Flow::createExpandVariableDynamicDimsPass());
// Materialize dynamic shapes in the IR, also expanding function signatures
// such that:
// - Dynamic ranked tensors: (tensor<?x?xf32>) expands to
// (tensor<?x?xf32>, ranked_shape<[?,?]>), and ultimately expands to
// (tensor<?x?xf32>, i32, i32)
// - Unranked tensors: **unsupported**
// The generated ABI wrappers assume such an expansion and will generate code
// to produce it from the original reflection metadata captured in the
// previous pass.
passManager.addNestedPass<FuncOp>(
Shape::createExpandFunctionDynamicDimsPass());
SmallVector<std::string> doNotRecurseOpNames = {"flow.dispatch.workgroups"};
passManager.addNestedPass<FuncOp>(
Shape::createTieDynamicShapesPass(doNotRecurseOpNames));
passManager.addNestedPass<FuncOp>(
Shape::createMaterializeShapeCalculationsPass());
passManager.addNestedPass<FuncOp>(Shape::createHoistShapeCalculationsPass());
//----------------------------------------------------------------------------
// Partitioning and dispatch region formation
//
// Phase ordering constraints:
// - Must precede dependencies on fully formed flow.dispatch and
// flow.dispatch_region ops
// Pre-conditions:
// - Conversion to CFG
// - Materialization of shape metadata ops
// Post-conditions:
// - Dispatch functions have been outlined such that only their dynamic
// root tensors are tied via shapex.tie_shape
// - Non-dispatchable ops have either been converted to flow ops or deemed
// legal.
// - shapex.tie_shape ops exist at any dispatch operands/results that are
// dynamic, preserving the shape association.
//----------------------------------------------------------------------------
// Convert into our expected input and (hopefully) some flow ops.
passManager.addNestedPass<FuncOp>(
IREE::Flow::createPrePartitioningConversionPass());
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
if (dispatchLinalgOnTensors) {
// TODO(benvanik): move up to input; requires pre-partitioning conversion
// to be reworked first.
passManager.addNestedPass<FuncOp>(
mlir::iree_compiler::createHLOToLinalgOnTensorsPass(true));
if (clEnable1x1ConvToMatmul) {
passManager.addNestedPass<FuncOp>(
mlir::iree_compiler::createConvert1x1ConvToMatmulPass());
}
passManager.addNestedPass<FuncOp>(
mlir::createConvertElementwiseToLinalgPass());
passManager.addNestedPass<FuncOp>(
mlir::createLinalgFoldUnitExtentDimsPass());
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(
mlir::iree_compiler::createFusionOfTensorOpsPass());
passManager.addNestedPass<FuncOp>(
IREE::Flow::createConvertToFlowTensorOpsPass());
passManager.addNestedPass<FuncOp>(mlir::createCSEPass());
passManager.addNestedPass<FuncOp>(
IREE::Flow::createDispatchLinalgOnTensorsPass());
// NOTE: required because the current dispatch-linalg-on-tensors pass
// creates a lot of dead IR that needs to be cleaned up.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
// Outline the dispatch regions into their own functions wrapped in
// executables.
passManager.addPass(IREE::Flow::createOutlineDispatchRegions2Pass());
} else {
// DEPRECATED: legacy HLO-based path.
passManager.addPass(IREE::Flow::createDispatchabilityAnalysisPass());
passManager.addNestedPass<FuncOp>(
IREE::Flow::createIdentifyDispatchRegions2Pass());
passManager.addNestedPass<FuncOp>(createCSEPass());
passManager.addNestedPass<FuncOp>(
IREE::Flow::createFoldCompatibleDispatchRegionsPass());
passManager.addPass(IREE::Flow::createOutlineDispatchRegionsPass());
}
// Cleanup identity ops that clutter up the IR and canonicalize.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
// Deduplicate executables created from dispatch regions.
// Note: this only deduplicates equivalent executables. We could in addition
// generalize executables to prune further (e.g. by promoting a dimension to
// an argument if two executables differ only in that one dimension).
passManager.addPass(IREE::Flow::createDeduplicateExecutablesPass());
// Create one function per remaining flow.executable that can be used with
// iree-benchmark-module to benchmark each dispatch individually, as well as
// exporting all original model entry points.
if (clExportBenchmarkFuncs) {
passManager.addPass(IREE::Flow::createExportBenchmarkFuncsPass());
}
// Inject tracing that logs both input and output tensors from all dispatches.
// We do this after deduping so that the executable names match later stages.
if (clTraceDispatchTensors) {
passManager.addNestedPass<FuncOp>(
IREE::Flow::createInjectDispatchTracingPass());
}
//----------------------------------------------------------------------------
// Stream formation.
// Pre-conditions:
// - Full formation of dispatch regions
//----------------------------------------------------------------------------
// Form streams.
// Cleanup the IR before we try to form streams.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(mlir::createCSEPass());
// Reorder blocks to increase the grouping of streamable ops.
passManager.addNestedPass<FuncOp>(
IREE::Flow::createHoistUnstreamableOpsPass());
// The hoisting pass does some reordering. Canonicalize to avoid unnecessary
// arbitrary ordering.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(IREE::Flow::createFormStreamsPass());
// Prior to leaving the pipeline we need to clean things up for following
// layers. These transforms may be undone by subsequent CSE/folding passes.
passManager.addPass(IREE::Flow::createOutlineLargeConstantsPass());
// Forming streams involves a fair amount of subgraph stitching, which can
// cause duplication. Run CSE to collapse.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(mlir::createCSEPass());
// Symbol DCE any remaining variables/functions that are now no longer
// required.
passManager.addPass(mlir::createSymbolDCEPass());
}
void registerFlowTransformPassPipeline() {
PassPipelineRegistration<> transformPassPipeline(
"iree-flow-transformation-pipeline",
"Runs the full IREE flow dialect transformation pipeline",
[](OpPassManager &passManager) {
buildFlowTransformPassPipeline(passManager, false);
});
}
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Delete clEnableLinalgOnTensorsDispatch option.<commit_after>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include <memory>
#include "iree/compiler/Conversion/HLOToHLO/Passes.h"
#include "iree/compiler/Conversion/HLOToLinalg/HLOToLinalgOnTensorPasses.h"
#include "iree/compiler/Conversion/LinalgToLinalg/Passes.h"
#include "iree/compiler/Dialect/Shape/Conversion/Passes.h"
#include "iree/compiler/Dialect/Shape/Transforms/Passes.h"
#include "mlir-hlo/Dialect/mhlo/transforms/passes.h"
#include "mlir/Conversion/SCFToStandard/SCFToStandard.h"
#include "mlir/Conversion/TosaToLinalg/TosaToLinalg.h"
#include "mlir/Conversion/TosaToSCF/TosaToSCF.h"
#include "mlir/Conversion/TosaToStandard/TosaToStandard.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/Shape/Transforms/Passes.h"
#include "mlir/Pass/PassOptions.h"
#include "mlir/Pass/PassRegistry.h"
#include "mlir/Transforms/Passes.h"
// TODO(benvanik): change to a pipeline option.
static llvm::cl::opt<bool> clExportBenchmarkFuncs(
"iree-flow-export-benchmark-funcs",
llvm::cl::desc(
"Exports one function per original module entry point and "
"unique flow.executable that dispatches with dummy arguments."),
llvm::cl::init(false));
// TODO(benvanik): change to a pipeline option.
static llvm::cl::opt<bool> clTraceDispatchTensors(
"iree-flow-trace-dispatch-tensors2",
llvm::cl::desc(
"Trace runtime input/output tensors for each dispatch function."),
llvm::cl::init(false));
static llvm::cl::opt<bool> clEnable1x1ConvToMatmul(
"iree-flow-enable-1x1-conv-to-matmul",
llvm::cl::desc("Enable converting 1x1 linalg convolution ops to linalg "
"matmul ops pass."),
llvm::cl::init(true));
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {
// Prepare HLO for use as an input to the Flow dialect.
//
// HACK: this needs to be moved into the various tensorflow-specific import
// tools so that none of this code pulls in HLO. Today we still have
// dependencies on HLO for the legacy non-linalg-on-tensors path so it's fine
// here, but soon we'll be shifting away from that and only accepting upstream
// dialects like linalg.
static void buildHLOInputTransformPassPipeline(OpPassManager &passManager) {
passManager.addNestedPass<FuncOp>(
IREE::Flow::createHLOToHLOPreprocessingPass());
// TODO(ataei): This should run as part of createHLOToHLOPreprocessingPass
// which will break VMLA backend.
passManager.addNestedPass<FuncOp>(createDecomposeHLOClampPass());
// Run passes to remove shape constraints. HLO lowering inserts them, but they
// are not desired here.
passManager.addNestedPass<FuncOp>(mlir::createRemoveShapeConstraintsPass());
}
// Prepare TOSA for use as an input to the Flow dialect.
static void buildTOSAInputTransformPassPipeline(OpPassManager &passManager) {
passManager.addNestedPass<FuncOp>(tosa::createTosaToSCF());
passManager.addNestedPass<FuncOp>(tosa::createTosaToStandard());
passManager.addNestedPass<FuncOp>(tosa::createTosaToLinalgOnTensors());
}
void buildInputTransformPassPipeline(OpPassManager &passManager) {
buildHLOInputTransformPassPipeline(passManager);
buildTOSAInputTransformPassPipeline(passManager);
passManager.addPass(createCanonicalizerPass());
}
void registerInputTransformPassPipeline() {
PassPipelineRegistration<> transformPassPipeline(
"iree-input-transformation-pipeline",
"Runs the full IREE flow dialect transformation pipeline",
[](OpPassManager &passManager) {
buildInputTransformPassPipeline(passManager);
});
}
void buildFlowTransformPassPipeline(OpPassManager &passManager,
bool dispatchLinalgOnTensors) {
//----------------------------------------------------------------------------
// Entry dialect cleanup
//----------------------------------------------------------------------------
// Currently we don't handle SCF ops well and have to convert them all to CFG.
// In the future it would be nice if we could have all of flow be both scf
// and cfg compatible.
passManager.addNestedPass<FuncOp>(mlir::createLowerToCFGPass());
// We also don't handle calls well on the old codepath; until we remove the
// use of the CFG we can continue inlining.
passManager.addPass(mlir::createInlinerPass());
// Convert `shape` dialect to `shapex` dialect.
passManager.addPass(Shape::createConvertShapeToShapexPass());
// Perform initial cleanup.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(mlir::createCSEPass());
// Legalize input types. We do this after flattening tuples so that we don't
// have to deal with them.
// TODO(nicolasvasilache): createLegalizeInputTypesPass is old and does not
// handle region conversion properly (parent cloned before children). Revisit
// when using ops with regions such as scf.for and linalg.generic.
passManager.addPass(IREE::Flow::createLegalizeInputTypesPass());
//----------------------------------------------------------------------------
// Shape materialization for buffer assignment and stream formation.
//
// Phase ordering constraints:
// - All tensor-level transformations which alter shapes must be complete
// prior to this phase.
//
// Pre-conditions:
// - Type conversion and sanitization of public function signatures.
// - "Root" dynamic tensors all pass through a single shapex.tie_shape
// use which associates them to their shape.
// - Loose, non-associated shapex.get_ranked_shape ops can exist anywhere
// and will be resolved.
// Post-conditions:
// - All dynamic tensors bridge through a shapex.tie_shape op with the
// appropriate shape.
// - No shapex.get_ranked_shape ops exist (they have been converted to
// concrete IR which materializes the shapes, either statically or
// dynamically).
// - Shape folding and canonicalization has been done.
//----------------------------------------------------------------------------
// Replaces variables with !shapex.ranked_shape types with individual
// variables for each dimension. This allows for constant dimensions to be
// DCE'd in following passes.
passManager.addPass(IREE::Flow::createExpandVariableDynamicDimsPass());
// Materialize dynamic shapes in the IR, also expanding function signatures
// such that:
// - Dynamic ranked tensors: (tensor<?x?xf32>) expands to
// (tensor<?x?xf32>, ranked_shape<[?,?]>), and ultimately expands to
// (tensor<?x?xf32>, i32, i32)
// - Unranked tensors: **unsupported**
// The generated ABI wrappers assume such an expansion and will generate code
// to produce it from the original reflection metadata captured in the
// previous pass.
passManager.addNestedPass<FuncOp>(
Shape::createExpandFunctionDynamicDimsPass());
SmallVector<std::string> doNotRecurseOpNames = {"flow.dispatch.workgroups"};
passManager.addNestedPass<FuncOp>(
Shape::createTieDynamicShapesPass(doNotRecurseOpNames));
passManager.addNestedPass<FuncOp>(
Shape::createMaterializeShapeCalculationsPass());
passManager.addNestedPass<FuncOp>(Shape::createHoistShapeCalculationsPass());
//----------------------------------------------------------------------------
// Partitioning and dispatch region formation
//
// Phase ordering constraints:
// - Must precede dependencies on fully formed flow.dispatch and
// flow.dispatch_region ops
// Pre-conditions:
// - Conversion to CFG
// - Materialization of shape metadata ops
// Post-conditions:
// - Dispatch functions have been outlined such that only their dynamic
// root tensors are tied via shapex.tie_shape
// - Non-dispatchable ops have either been converted to flow ops or deemed
// legal.
// - shapex.tie_shape ops exist at any dispatch operands/results that are
// dynamic, preserving the shape association.
//----------------------------------------------------------------------------
// Convert into our expected input and (hopefully) some flow ops.
passManager.addNestedPass<FuncOp>(
IREE::Flow::createPrePartitioningConversionPass());
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
if (dispatchLinalgOnTensors) {
// TODO(benvanik): move up to input; requires pre-partitioning conversion
// to be reworked first.
passManager.addNestedPass<FuncOp>(
mlir::iree_compiler::createHLOToLinalgOnTensorsPass(true));
if (clEnable1x1ConvToMatmul) {
passManager.addNestedPass<FuncOp>(
mlir::iree_compiler::createConvert1x1ConvToMatmulPass());
}
passManager.addNestedPass<FuncOp>(
mlir::createConvertElementwiseToLinalgPass());
passManager.addNestedPass<FuncOp>(
mlir::createLinalgFoldUnitExtentDimsPass());
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(
mlir::iree_compiler::createFusionOfTensorOpsPass());
passManager.addNestedPass<FuncOp>(
IREE::Flow::createConvertToFlowTensorOpsPass());
passManager.addNestedPass<FuncOp>(mlir::createCSEPass());
passManager.addNestedPass<FuncOp>(
IREE::Flow::createDispatchLinalgOnTensorsPass());
// NOTE: required because the current dispatch-linalg-on-tensors pass
// creates a lot of dead IR that needs to be cleaned up.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
// Outline the dispatch regions into their own functions wrapped in
// executables.
passManager.addPass(IREE::Flow::createOutlineDispatchRegions2Pass());
} else {
// DEPRECATED: legacy HLO-based path.
passManager.addPass(IREE::Flow::createDispatchabilityAnalysisPass());
passManager.addNestedPass<FuncOp>(
IREE::Flow::createIdentifyDispatchRegions2Pass());
passManager.addNestedPass<FuncOp>(createCSEPass());
passManager.addNestedPass<FuncOp>(
IREE::Flow::createFoldCompatibleDispatchRegionsPass());
passManager.addPass(IREE::Flow::createOutlineDispatchRegionsPass());
}
// Cleanup identity ops that clutter up the IR and canonicalize.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
// Deduplicate executables created from dispatch regions.
// Note: this only deduplicates equivalent executables. We could in addition
// generalize executables to prune further (e.g. by promoting a dimension to
// an argument if two executables differ only in that one dimension).
passManager.addPass(IREE::Flow::createDeduplicateExecutablesPass());
// Create one function per remaining flow.executable that can be used with
// iree-benchmark-module to benchmark each dispatch individually, as well as
// exporting all original model entry points.
if (clExportBenchmarkFuncs) {
passManager.addPass(IREE::Flow::createExportBenchmarkFuncsPass());
}
// Inject tracing that logs both input and output tensors from all dispatches.
// We do this after deduping so that the executable names match later stages.
if (clTraceDispatchTensors) {
passManager.addNestedPass<FuncOp>(
IREE::Flow::createInjectDispatchTracingPass());
}
//----------------------------------------------------------------------------
// Stream formation.
// Pre-conditions:
// - Full formation of dispatch regions
//----------------------------------------------------------------------------
// Form streams.
// Cleanup the IR before we try to form streams.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(mlir::createCSEPass());
// Reorder blocks to increase the grouping of streamable ops.
passManager.addNestedPass<FuncOp>(
IREE::Flow::createHoistUnstreamableOpsPass());
// The hoisting pass does some reordering. Canonicalize to avoid unnecessary
// arbitrary ordering.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(IREE::Flow::createFormStreamsPass());
// Prior to leaving the pipeline we need to clean things up for following
// layers. These transforms may be undone by subsequent CSE/folding passes.
passManager.addPass(IREE::Flow::createOutlineLargeConstantsPass());
// Forming streams involves a fair amount of subgraph stitching, which can
// cause duplication. Run CSE to collapse.
passManager.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
passManager.addNestedPass<FuncOp>(mlir::createCSEPass());
// Symbol DCE any remaining variables/functions that are now no longer
// required.
passManager.addPass(mlir::createSymbolDCEPass());
}
void registerFlowTransformPassPipeline() {
PassPipelineRegistration<> transformPassPipeline(
"iree-flow-transformation-pipeline",
"Runs the full IREE flow dialect transformation pipeline",
[](OpPassManager &passManager) {
buildFlowTransformPassPipeline(passManager, false);
});
}
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
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 author 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 <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/bind.hpp>
#include "libtorrent/socket.hpp"
#include "libtorrent/enum_net.hpp"
#include "libtorrent/broadcast_socket.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent
{
bool is_local(address const& a)
{
if (a.is_v6()) return a.to_v6().is_link_local();
address_v4 a4 = a.to_v4();
unsigned long ip = a4.to_ulong();
return ((ip & 0xff000000) == 0x0a000000
|| (ip & 0xfff00000) == 0xac100000
|| (ip & 0xffff0000) == 0xc0a80000);
}
bool is_loopback(address const& addr)
{
if (addr.is_v4())
return addr.to_v4() == address_v4::loopback();
else
return addr.to_v6() == address_v6::loopback();
}
bool is_multicast(address const& addr)
{
if (addr.is_v4())
return addr.to_v4().is_multicast();
else
return addr.to_v6().is_multicast();
}
bool is_any(address const& addr)
{
if (addr.is_v4())
return addr.to_v4() == address_v4::any();
else
return addr.to_v6() == address_v6::any();
}
address guess_local_address(asio::io_service& ios)
{
// make a best guess of the interface we're using and its IP
asio::error_code ec;
std::vector<address> const& interfaces = enum_net_interfaces(ios, ec);
address ret = address_v4::any();
for (std::vector<address>::const_iterator i = interfaces.begin()
, end(interfaces.end()); i != end; ++i)
{
address const& a = *i;
if (is_loopback(a)
|| is_multicast(a)
|| is_any(a)) continue;
// prefer a v4 address, but return a v6 if
// there are no v4
if (a.is_v4()) return a;
if (ret != address_v4::any())
ret = a;
}
return ret;
}
broadcast_socket::broadcast_socket(asio::io_service& ios
, udp::endpoint const& multicast_endpoint
, receive_handler_t const& handler
, bool loopback)
: m_multicast_endpoint(multicast_endpoint)
, m_on_receive(handler)
{
TORRENT_ASSERT(is_multicast(m_multicast_endpoint.address()));
using namespace asio::ip::multicast;
asio::error_code ec;
std::vector<address> interfaces = enum_net_interfaces(ios, ec);
for (std::vector<address>::const_iterator i = interfaces.begin()
, end(interfaces.end()); i != end; ++i)
{
// only broadcast to IPv4 addresses that are not local
if (!is_local(*i)) continue;
// only multicast on compatible networks
if (i->is_v4() != multicast_endpoint.address().is_v4()) continue;
// ignore any loopback interface
if (is_loopback(*i)) continue;
boost::shared_ptr<datagram_socket> s(new datagram_socket(ios));
if (i->is_v4())
{
s->open(udp::v4(), ec);
if (ec) continue;
s->set_option(datagram_socket::reuse_address(true), ec);
if (ec) continue;
s->bind(udp::endpoint(address_v4::any(), multicast_endpoint.port()), ec);
if (ec) continue;
s->set_option(join_group(multicast_endpoint.address()), ec);
if (ec) continue;
s->set_option(outbound_interface(i->to_v4()), ec);
if (ec) continue;
}
else
{
s->open(udp::v6(), ec);
if (ec) continue;
s->set_option(datagram_socket::reuse_address(true), ec);
if (ec) continue;
s->bind(udp::endpoint(address_v6::any(), multicast_endpoint.port()), ec);
if (ec) continue;
s->set_option(join_group(multicast_endpoint.address()), ec);
if (ec) continue;
// s->set_option(outbound_interface(i->to_v6()), ec);
// if (ec) continue;
}
s->set_option(hops(255), ec);
if (ec) continue;
s->set_option(enable_loopback(loopback), ec);
if (ec) continue;
m_sockets.push_back(socket_entry(s));
socket_entry& se = m_sockets.back();
s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))
, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));
#ifndef NDEBUG
// std::cerr << "broadcast socket [ if: " << i->to_v4().to_string()
// << " group: " << multicast_endpoint.address() << " ]" << std::endl;
#endif
}
open_unicast_socket(ios, address_v4::any());
open_unicast_socket(ios, address_v6::any());
}
void broadcast_socket::open_unicast_socket(io_service& ios, address const& addr)
{
asio::error_code ec;
boost::shared_ptr<datagram_socket> s(new datagram_socket(ios));
s->open(addr.is_v4() ? udp::v4() : udp::v6(), ec);
if (ec) return;
s->bind(udp::endpoint(addr, 0), ec);
if (ec) return;
m_unicast_sockets.push_back(socket_entry(s));
socket_entry& se = m_unicast_sockets.back();
s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))
, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));
}
void broadcast_socket::send(char const* buffer, int size, asio::error_code& ec)
{
for (std::list<socket_entry>::iterator i = m_unicast_sockets.begin()
, end(m_unicast_sockets.end()); i != end; ++i)
{
if (!i->socket) continue;
asio::error_code e;
i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);
#ifndef NDEBUG
// std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << std::endl;
#endif
if (e)
{
i->socket->close(e);
i->socket.reset();
}
}
}
void broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec
, std::size_t bytes_transferred)
{
if (ec || bytes_transferred == 0 || !m_on_receive) return;
m_on_receive(s->remote, s->buffer, bytes_transferred);
if (!s->socket) return;
s->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer))
, s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2));
}
void broadcast_socket::close()
{
m_on_receive.clear();
std::for_each(m_sockets.begin(), m_sockets.end(), bind(&socket_entry::close, _1));
std::for_each(m_unicast_sockets.begin(), m_unicast_sockets.end(), bind(&socket_entry::close, _1));
}
}
<commit_msg>broadcast socket fix<commit_after>/*
Copyright (c) 2007, Arvid Norberg
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 author 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 <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/bind.hpp>
#include "libtorrent/socket.hpp"
#include "libtorrent/enum_net.hpp"
#include "libtorrent/broadcast_socket.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent
{
bool is_local(address const& a)
{
if (a.is_v6()) return a.to_v6().is_link_local();
address_v4 a4 = a.to_v4();
unsigned long ip = a4.to_ulong();
return ((ip & 0xff000000) == 0x0a000000
|| (ip & 0xfff00000) == 0xac100000
|| (ip & 0xffff0000) == 0xc0a80000);
}
bool is_loopback(address const& addr)
{
if (addr.is_v4())
return addr.to_v4() == address_v4::loopback();
else
return addr.to_v6() == address_v6::loopback();
}
bool is_multicast(address const& addr)
{
if (addr.is_v4())
return addr.to_v4().is_multicast();
else
return addr.to_v6().is_multicast();
}
bool is_any(address const& addr)
{
if (addr.is_v4())
return addr.to_v4() == address_v4::any();
else
return addr.to_v6() == address_v6::any();
}
address guess_local_address(asio::io_service& ios)
{
// make a best guess of the interface we're using and its IP
asio::error_code ec;
std::vector<address> const& interfaces = enum_net_interfaces(ios, ec);
address ret = address_v4::any();
for (std::vector<address>::const_iterator i = interfaces.begin()
, end(interfaces.end()); i != end; ++i)
{
address const& a = *i;
if (is_loopback(a)
|| is_multicast(a)
|| is_any(a)) continue;
// prefer a v4 address, but return a v6 if
// there are no v4
if (a.is_v4()) return a;
if (ret != address_v4::any())
ret = a;
}
return ret;
}
broadcast_socket::broadcast_socket(asio::io_service& ios
, udp::endpoint const& multicast_endpoint
, receive_handler_t const& handler
, bool loopback)
: m_multicast_endpoint(multicast_endpoint)
, m_on_receive(handler)
{
TORRENT_ASSERT(is_multicast(m_multicast_endpoint.address()));
using namespace asio::ip::multicast;
asio::error_code ec;
std::vector<address> interfaces = enum_net_interfaces(ios, ec);
for (std::vector<address>::const_iterator i = interfaces.begin()
, end(interfaces.end()); i != end; ++i)
{
// only broadcast to IPv4 addresses that are not local
if (!is_local(*i)) continue;
// only multicast on compatible networks
if (i->is_v4() != multicast_endpoint.address().is_v4()) continue;
// ignore any loopback interface
if (is_loopback(*i)) continue;
boost::shared_ptr<datagram_socket> s(new datagram_socket(ios));
if (i->is_v4())
{
s->open(udp::v4(), ec);
if (ec) continue;
s->set_option(datagram_socket::reuse_address(true), ec);
if (ec) continue;
s->bind(udp::endpoint(address_v4::any(), multicast_endpoint.port()), ec);
if (ec) continue;
s->set_option(join_group(multicast_endpoint.address()), ec);
if (ec) continue;
s->set_option(outbound_interface(i->to_v4()), ec);
if (ec) continue;
}
else
{
s->open(udp::v6(), ec);
if (ec) continue;
s->set_option(datagram_socket::reuse_address(true), ec);
if (ec) continue;
s->bind(udp::endpoint(address_v6::any(), multicast_endpoint.port()), ec);
if (ec) continue;
s->set_option(join_group(multicast_endpoint.address()), ec);
if (ec) continue;
// s->set_option(outbound_interface(i->to_v6()), ec);
// if (ec) continue;
}
s->set_option(hops(255), ec);
if (ec) continue;
s->set_option(enable_loopback(loopback), ec);
if (ec) continue;
m_sockets.push_back(socket_entry(s));
socket_entry& se = m_sockets.back();
s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))
, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));
#ifndef NDEBUG
// std::cerr << "broadcast socket [ if: " << i->to_v4().to_string()
// << " group: " << multicast_endpoint.address() << " ]" << std::endl;
#endif
}
open_unicast_socket(ios, address_v4::any());
open_unicast_socket(ios, address_v6::any());
}
void broadcast_socket::open_unicast_socket(io_service& ios, address const& addr)
{
asio::error_code ec;
boost::shared_ptr<datagram_socket> s(new datagram_socket(ios));
s->open(addr.is_v4() ? udp::v4() : udp::v6(), ec);
if (ec) return;
s->bind(udp::endpoint(addr, 0), ec);
if (ec) return;
m_unicast_sockets.push_back(socket_entry(s));
socket_entry& se = m_unicast_sockets.back();
s->async_receive_from(asio::buffer(se.buffer, sizeof(se.buffer))
, se.remote, bind(&broadcast_socket::on_receive, this, &se, _1, _2));
}
void broadcast_socket::send(char const* buffer, int size, asio::error_code& ec)
{
for (std::list<socket_entry>::iterator i = m_unicast_sockets.begin()
, end(m_unicast_sockets.end()); i != end; ++i)
{
if (!i->socket) continue;
asio::error_code e;
i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);
#ifndef NDEBUG
// std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << " to: " << m_multicast_endpoint << std::endl;
#endif
if (e)
{
i->socket->close(e);
i->socket.reset();
}
}
for (std::list<socket_entry>::iterator i = m_sockets.begin()
, end(m_sockets.end()); i != end; ++i)
{
if (!i->socket) continue;
asio::error_code e;
i->socket->send_to(asio::buffer(buffer, size), m_multicast_endpoint, 0, e);
#ifndef NDEBUG
// std::cerr << " sending on " << i->socket->local_endpoint().address().to_string() << " to: " << m_multicast_endpoint << std::endl;
#endif
if (e)
{
i->socket->close(e);
i->socket.reset();
}
}
}
void broadcast_socket::on_receive(socket_entry* s, asio::error_code const& ec
, std::size_t bytes_transferred)
{
if (ec || bytes_transferred == 0 || !m_on_receive) return;
m_on_receive(s->remote, s->buffer, bytes_transferred);
if (!s->socket) return;
s->socket->async_receive_from(asio::buffer(s->buffer, sizeof(s->buffer))
, s->remote, bind(&broadcast_socket::on_receive, this, s, _1, _2));
}
void broadcast_socket::close()
{
std::for_each(m_sockets.begin(), m_sockets.end(), bind(&socket_entry::close, _1));
std::for_each(m_unicast_sockets.begin(), m_unicast_sockets.end(), bind(&socket_entry::close, _1));
m_on_receive.clear();
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessiblePreviewCell.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: kz $ $Date: 2006-07-21 13:06:49 $
*
* 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_sc.hxx"
#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SC_ACCESSIBLETEXT_HXX
#include "AccessibleText.hxx"
#endif
#ifndef SC_EDITSRC_HXX
#include "editsrc.hxx"
#endif
#include "AccessiblePreviewCell.hxx"
#ifndef SC_ACCESSIBILITYHINTS_HXX
#include "AccessibilityHints.hxx"
#endif
#include "prevwsh.hxx"
#include "unoguard.hxx"
#include "prevloc.hxx"
#include "document.hxx"
#ifndef _SVX_ACCESSILE_TEXT_HELPER_HXX_
#include <svx/AccessibleTextHelper.hxx>
#endif
#include <unotools/accessiblestatesethelper.hxx>
#include <svx/brshitem.hxx>
#include <vcl/window.hxx>
#ifndef _TOOLKIT_HELPER_CONVERT_HXX_
#include <toolkit/helper/convert.hxx>
#endif
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
//===== internal ============================================================
ScAccessiblePreviewCell::ScAccessiblePreviewCell( const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent,
ScPreviewShell* pViewShell, /* const */ ScAddress& rCellAddress,
sal_Int32 nIndex ) :
ScAccessibleCellBase( rxParent, ( pViewShell ? pViewShell->GetDocument() : NULL ), rCellAddress, nIndex ),
mpViewShell( pViewShell ),
mpTextHelper(NULL)
{
if (mpViewShell)
mpViewShell->AddAccessibilityObject(*this);
}
ScAccessiblePreviewCell::~ScAccessiblePreviewCell()
{
if (!ScAccessibleContextBase::IsDefunc() && !rBHelper.bInDispose)
{
// increment refcount to prevent double call off dtor
osl_incrementInterlockedCount( &m_refCount );
// call dispose to inform object wich have a weak reference to this object
dispose();
}
}
void SAL_CALL ScAccessiblePreviewCell::disposing()
{
ScUnoGuard aGuard;
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
mpViewShell = NULL;
}
if (mpTextHelper)
DELETEZ(mpTextHelper);
ScAccessibleCellBase::disposing();
}
void ScAccessiblePreviewCell::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if (rHint.ISA( SfxSimpleHint ))
{
const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
ULONG nId = rRef.GetId();
if (rRef.GetId() == SC_HINT_ACC_VISAREACHANGED)
{
if (mpTextHelper)
mpTextHelper->UpdateChildren();
}
}
ScAccessibleContextBase::Notify(rBC, rHint);
}
//===== XAccessibleComponent ============================================
uno::Reference< XAccessible > SAL_CALL ScAccessiblePreviewCell::getAccessibleAtPoint( const awt::Point& rPoint )
throw (uno::RuntimeException)
{
uno::Reference<XAccessible> xRet;
if (containsPoint(rPoint))
{
ScUnoGuard aGuard;
IsObjectValid();
if(!mpTextHelper)
CreateTextHelper();
xRet = mpTextHelper->GetAt(rPoint);
}
return xRet;
}
void SAL_CALL ScAccessiblePreviewCell::grabFocus() throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleComponent> xAccessibleComponent(getAccessibleParent()->getAccessibleContext(), uno::UNO_QUERY);
if (xAccessibleComponent.is())
xAccessibleComponent->grabFocus();
}
}
//===== XAccessibleContext ==============================================
sal_Int32 SAL_CALL ScAccessiblePreviewCell::getAccessibleChildCount() throw(uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (!mpTextHelper)
CreateTextHelper();
return mpTextHelper->GetChildCount();
}
uno::Reference< XAccessible > SAL_CALL ScAccessiblePreviewCell::getAccessibleChild(sal_Int32 nIndex)
throw (uno::RuntimeException, lang::IndexOutOfBoundsException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (!mpTextHelper)
CreateTextHelper();
return mpTextHelper->GetChild(nIndex);
}
uno::Reference<XAccessibleStateSet> SAL_CALL ScAccessiblePreviewCell::getAccessibleStateSet()
throw(uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessibleStateSet> xParentStates;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
xParentStates = xParentContext->getAccessibleStateSet();
}
utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
if (IsDefunc(xParentStates))
pStateSet->AddState(AccessibleStateType::DEFUNC);
else
{
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::MULTI_LINE);
if (IsOpaque(xParentStates))
pStateSet->AddState(AccessibleStateType::OPAQUE);
if (isShowing())
pStateSet->AddState(AccessibleStateType::SHOWING);
pStateSet->AddState(AccessibleStateType::TRANSIENT);
if (isVisible())
pStateSet->AddState(AccessibleStateType::VISIBLE);
// #111635# MANAGES_DESCENDANTS (for paragraphs)
pStateSet->AddState(AccessibleStateType::MANAGES_DESCENDANTS);
}
return pStateSet;
}
//===== XServiceInfo ====================================================
rtl::OUString SAL_CALL ScAccessiblePreviewCell::getImplementationName() throw(uno::RuntimeException)
{
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ScAccessiblePreviewCell"));
}
uno::Sequence<rtl::OUString> SAL_CALL ScAccessiblePreviewCell::getSupportedServiceNames()
throw(uno::RuntimeException)
{
uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
sal_Int32 nOldSize(aSequence.getLength());
aSequence.realloc(nOldSize + 1);
::rtl::OUString* pNames = aSequence.getArray();
pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.table.AccessibleCellView"));
return aSequence;
}
//===== XTypeProvider =======================================================
uno::Sequence<sal_Int8> SAL_CALL
ScAccessiblePreviewCell::getImplementationId(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
static uno::Sequence<sal_Int8> aId;
if (aId.getLength() == 0)
{
aId.realloc (16);
rtl_createUuid (reinterpret_cast<sal_uInt8 *>(aId.getArray()), 0, sal_True);
}
return aId;
}
//==== internal =========================================================
Rectangle ScAccessiblePreviewCell::GetBoundingBoxOnScreen() const throw (uno::RuntimeException)
{
Rectangle aCellRect;
if (mpViewShell)
{
mpViewShell->GetLocationData().GetCellPosition( maCellAddress, aCellRect );
Window* pWindow = mpViewShell->GetWindow();
if (pWindow)
{
Rectangle aRect = pWindow->GetWindowExtentsRelative(NULL);
aCellRect.setX(aCellRect.getX() + aRect.getX());
aCellRect.setY(aCellRect.getY() + aRect.getY());
}
}
return aCellRect;
}
Rectangle ScAccessiblePreviewCell::GetBoundingBox() const throw (uno::RuntimeException)
{
Rectangle aCellRect;
if (mpViewShell)
{
mpViewShell->GetLocationData().GetCellPosition( maCellAddress, aCellRect );
uno::Reference<XAccessible> xAccParent = const_cast<ScAccessiblePreviewCell*>(this)->getAccessibleParent();
if (xAccParent.is())
{
uno::Reference<XAccessibleContext> xAccParentContext = xAccParent->getAccessibleContext();
uno::Reference<XAccessibleComponent> xAccParentComp (xAccParentContext, uno::UNO_QUERY);
if (xAccParentComp.is())
{
Rectangle aParentRect (VCLRectangle(xAccParentComp->getBounds()));
aCellRect.setX(aCellRect.getX() - aParentRect.getX());
aCellRect.setY(aCellRect.getY() - aParentRect.getY());
}
}
}
return aCellRect;
}
sal_Bool ScAccessiblePreviewCell::IsDefunc(
const uno::Reference<XAccessibleStateSet>& rxParentStates)
{
return ScAccessibleContextBase::IsDefunc() || (mpDoc == NULL) || (mpViewShell == NULL) || !getAccessibleParent().is() ||
(rxParentStates.is() && rxParentStates->contains(AccessibleStateType::DEFUNC));
}
sal_Bool ScAccessiblePreviewCell::IsEditable(
const uno::Reference<XAccessibleStateSet>& rxParentStates)
{
return sal_False;
}
sal_Bool ScAccessiblePreviewCell::IsOpaque(
const uno::Reference<XAccessibleStateSet>& rxParentStates)
{
// test whether there is a background color
//! could be moved to ScAccessibleCellBase
sal_Bool bOpaque(sal_True);
if (mpDoc)
{
const SvxBrushItem* pItem = (const SvxBrushItem*)mpDoc->GetAttr(
maCellAddress.Col(), maCellAddress.Row(), maCellAddress.Tab(), ATTR_BACKGROUND);
if (pItem)
bOpaque = pItem->GetColor() != COL_TRANSPARENT;
}
return bOpaque;
}
sal_Bool ScAccessiblePreviewCell::IsSelected(const uno::Reference<XAccessibleStateSet>& rxParentStates)
{
return sal_False;
}
void ScAccessiblePreviewCell::CreateTextHelper()
{
if (!mpTextHelper)
{
::std::auto_ptr < ScAccessibleTextData > pAccessiblePreviewCellTextData
(new ScAccessiblePreviewCellTextData(mpViewShell, maCellAddress));
::std::auto_ptr< SvxEditSource > pEditSource (new ScAccessibilityEditSource(pAccessiblePreviewCellTextData));
mpTextHelper = new ::accessibility::AccessibleTextHelper( pEditSource );
mpTextHelper->SetEventSource( this );
// #111635# paragraphs in preview are transient
::accessibility::AccessibleTextHelper::VectorOfStates aChildStates;
aChildStates.push_back( AccessibleStateType::TRANSIENT );
mpTextHelper->SetAdditionalChildStates( aChildStates );
}
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.18.110); FILE MERGED 2006/12/01 08:53:20 nn 1.18.110.1: #i69284# warning-free: ui, wntmsci10<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessiblePreviewCell.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:55:58 $
*
* 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_sc.hxx"
#ifndef SC_ITEMS_HXX
#include "scitems.hxx"
#endif
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SC_ACCESSIBLETEXT_HXX
#include "AccessibleText.hxx"
#endif
#ifndef SC_EDITSRC_HXX
#include "editsrc.hxx"
#endif
#include "AccessiblePreviewCell.hxx"
#ifndef SC_ACCESSIBILITYHINTS_HXX
#include "AccessibilityHints.hxx"
#endif
#include "prevwsh.hxx"
#include "unoguard.hxx"
#include "prevloc.hxx"
#include "document.hxx"
#ifndef _SVX_ACCESSILE_TEXT_HELPER_HXX_
#include <svx/AccessibleTextHelper.hxx>
#endif
#include <unotools/accessiblestatesethelper.hxx>
#include <svx/brshitem.hxx>
#include <vcl/window.hxx>
#ifndef _TOOLKIT_HELPER_CONVERT_HXX_
#include <toolkit/helper/convert.hxx>
#endif
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
using namespace ::com::sun::star;
using namespace ::com::sun::star::accessibility;
//===== internal ============================================================
ScAccessiblePreviewCell::ScAccessiblePreviewCell( const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent,
ScPreviewShell* pViewShell, /* const */ ScAddress& rCellAddress,
sal_Int32 nIndex ) :
ScAccessibleCellBase( rxParent, ( pViewShell ? pViewShell->GetDocument() : NULL ), rCellAddress, nIndex ),
mpViewShell( pViewShell ),
mpTextHelper(NULL)
{
if (mpViewShell)
mpViewShell->AddAccessibilityObject(*this);
}
ScAccessiblePreviewCell::~ScAccessiblePreviewCell()
{
if (!ScAccessibleContextBase::IsDefunc() && !rBHelper.bInDispose)
{
// increment refcount to prevent double call off dtor
osl_incrementInterlockedCount( &m_refCount );
// call dispose to inform object wich have a weak reference to this object
dispose();
}
}
void SAL_CALL ScAccessiblePreviewCell::disposing()
{
ScUnoGuard aGuard;
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
mpViewShell = NULL;
}
if (mpTextHelper)
DELETEZ(mpTextHelper);
ScAccessibleCellBase::disposing();
}
void ScAccessiblePreviewCell::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if (rHint.ISA( SfxSimpleHint ))
{
const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
if (rRef.GetId() == SC_HINT_ACC_VISAREACHANGED)
{
if (mpTextHelper)
mpTextHelper->UpdateChildren();
}
}
ScAccessibleContextBase::Notify(rBC, rHint);
}
//===== XAccessibleComponent ============================================
uno::Reference< XAccessible > SAL_CALL ScAccessiblePreviewCell::getAccessibleAtPoint( const awt::Point& rPoint )
throw (uno::RuntimeException)
{
uno::Reference<XAccessible> xRet;
if (containsPoint(rPoint))
{
ScUnoGuard aGuard;
IsObjectValid();
if(!mpTextHelper)
CreateTextHelper();
xRet = mpTextHelper->GetAt(rPoint);
}
return xRet;
}
void SAL_CALL ScAccessiblePreviewCell::grabFocus() throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleComponent> xAccessibleComponent(getAccessibleParent()->getAccessibleContext(), uno::UNO_QUERY);
if (xAccessibleComponent.is())
xAccessibleComponent->grabFocus();
}
}
//===== XAccessibleContext ==============================================
sal_Int32 SAL_CALL ScAccessiblePreviewCell::getAccessibleChildCount() throw(uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (!mpTextHelper)
CreateTextHelper();
return mpTextHelper->GetChildCount();
}
uno::Reference< XAccessible > SAL_CALL ScAccessiblePreviewCell::getAccessibleChild(sal_Int32 nIndex)
throw (uno::RuntimeException, lang::IndexOutOfBoundsException)
{
ScUnoGuard aGuard;
IsObjectValid();
if (!mpTextHelper)
CreateTextHelper();
return mpTextHelper->GetChild(nIndex);
}
uno::Reference<XAccessibleStateSet> SAL_CALL ScAccessiblePreviewCell::getAccessibleStateSet()
throw(uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessibleStateSet> xParentStates;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
xParentStates = xParentContext->getAccessibleStateSet();
}
utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
if (IsDefunc(xParentStates))
pStateSet->AddState(AccessibleStateType::DEFUNC);
else
{
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::MULTI_LINE);
if (IsOpaque(xParentStates))
pStateSet->AddState(AccessibleStateType::OPAQUE);
if (isShowing())
pStateSet->AddState(AccessibleStateType::SHOWING);
pStateSet->AddState(AccessibleStateType::TRANSIENT);
if (isVisible())
pStateSet->AddState(AccessibleStateType::VISIBLE);
// #111635# MANAGES_DESCENDANTS (for paragraphs)
pStateSet->AddState(AccessibleStateType::MANAGES_DESCENDANTS);
}
return pStateSet;
}
//===== XServiceInfo ====================================================
rtl::OUString SAL_CALL ScAccessiblePreviewCell::getImplementationName() throw(uno::RuntimeException)
{
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ScAccessiblePreviewCell"));
}
uno::Sequence<rtl::OUString> SAL_CALL ScAccessiblePreviewCell::getSupportedServiceNames()
throw(uno::RuntimeException)
{
uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
sal_Int32 nOldSize(aSequence.getLength());
aSequence.realloc(nOldSize + 1);
::rtl::OUString* pNames = aSequence.getArray();
pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.table.AccessibleCellView"));
return aSequence;
}
//===== XTypeProvider =======================================================
uno::Sequence<sal_Int8> SAL_CALL
ScAccessiblePreviewCell::getImplementationId(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
IsObjectValid();
static uno::Sequence<sal_Int8> aId;
if (aId.getLength() == 0)
{
aId.realloc (16);
rtl_createUuid (reinterpret_cast<sal_uInt8 *>(aId.getArray()), 0, sal_True);
}
return aId;
}
//==== internal =========================================================
Rectangle ScAccessiblePreviewCell::GetBoundingBoxOnScreen() const throw (uno::RuntimeException)
{
Rectangle aCellRect;
if (mpViewShell)
{
mpViewShell->GetLocationData().GetCellPosition( maCellAddress, aCellRect );
Window* pWindow = mpViewShell->GetWindow();
if (pWindow)
{
Rectangle aRect = pWindow->GetWindowExtentsRelative(NULL);
aCellRect.setX(aCellRect.getX() + aRect.getX());
aCellRect.setY(aCellRect.getY() + aRect.getY());
}
}
return aCellRect;
}
Rectangle ScAccessiblePreviewCell::GetBoundingBox() const throw (uno::RuntimeException)
{
Rectangle aCellRect;
if (mpViewShell)
{
mpViewShell->GetLocationData().GetCellPosition( maCellAddress, aCellRect );
uno::Reference<XAccessible> xAccParent = const_cast<ScAccessiblePreviewCell*>(this)->getAccessibleParent();
if (xAccParent.is())
{
uno::Reference<XAccessibleContext> xAccParentContext = xAccParent->getAccessibleContext();
uno::Reference<XAccessibleComponent> xAccParentComp (xAccParentContext, uno::UNO_QUERY);
if (xAccParentComp.is())
{
Rectangle aParentRect (VCLRectangle(xAccParentComp->getBounds()));
aCellRect.setX(aCellRect.getX() - aParentRect.getX());
aCellRect.setY(aCellRect.getY() - aParentRect.getY());
}
}
}
return aCellRect;
}
sal_Bool ScAccessiblePreviewCell::IsDefunc(
const uno::Reference<XAccessibleStateSet>& rxParentStates)
{
return ScAccessibleContextBase::IsDefunc() || (mpDoc == NULL) || (mpViewShell == NULL) || !getAccessibleParent().is() ||
(rxParentStates.is() && rxParentStates->contains(AccessibleStateType::DEFUNC));
}
sal_Bool ScAccessiblePreviewCell::IsEditable(
const uno::Reference<XAccessibleStateSet>& /* rxParentStates */)
{
return sal_False;
}
sal_Bool ScAccessiblePreviewCell::IsOpaque(
const uno::Reference<XAccessibleStateSet>& /* rxParentStates */)
{
// test whether there is a background color
//! could be moved to ScAccessibleCellBase
sal_Bool bOpaque(sal_True);
if (mpDoc)
{
const SvxBrushItem* pItem = (const SvxBrushItem*)mpDoc->GetAttr(
maCellAddress.Col(), maCellAddress.Row(), maCellAddress.Tab(), ATTR_BACKGROUND);
if (pItem)
bOpaque = pItem->GetColor() != COL_TRANSPARENT;
}
return bOpaque;
}
sal_Bool ScAccessiblePreviewCell::IsSelected(const uno::Reference<XAccessibleStateSet>& /* rxParentStates */)
{
return sal_False;
}
void ScAccessiblePreviewCell::CreateTextHelper()
{
if (!mpTextHelper)
{
::std::auto_ptr < ScAccessibleTextData > pAccessiblePreviewCellTextData
(new ScAccessiblePreviewCellTextData(mpViewShell, maCellAddress));
::std::auto_ptr< SvxEditSource > pEditSource (new ScAccessibilityEditSource(pAccessiblePreviewCellTextData));
mpTextHelper = new ::accessibility::AccessibleTextHelper( pEditSource );
mpTextHelper->SetEventSource( this );
// #111635# paragraphs in preview are transient
::accessibility::AccessibleTextHelper::VectorOfStates aChildStates;
aChildStates.push_back( AccessibleStateType::TRANSIENT );
mpTextHelper->SetAdditionalChildStates( aChildStates );
}
}
<|endoftext|> |
<commit_before>//===- CheckerRegistry.cpp - Maintains all available checkers -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/LLVM.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace clang;
using namespace ento;
using llvm::sys::DynamicLibrary;
using RegisterCheckersFn = void (*)(CheckerRegistry &);
static bool isCompatibleAPIVersion(const char *VersionString) {
// If the version string is null, its not an analyzer plugin.
if (!VersionString)
return false;
// For now, none of the static analyzer API is considered stable.
// Versions must match exactly.
return strcmp(VersionString, CLANG_ANALYZER_API_VERSION_STRING) == 0;
}
namespace {
template <class T> struct FullNameLT {
bool operator()(const T &Lhs, const T &Rhs) {
return Lhs.FullName < Rhs.FullName;
}
};
using CheckerNameLT = FullNameLT<CheckerRegistry::CheckerInfo>;
} // end of anonymous namespace
template <class CheckerOrPackageInfoList>
static
typename std::conditional<std::is_const<CheckerOrPackageInfoList>::value,
typename CheckerOrPackageInfoList::const_iterator,
typename CheckerOrPackageInfoList::iterator>::type
binaryFind(CheckerOrPackageInfoList &Collection, StringRef FullName) {
using CheckerOrPackage = typename CheckerOrPackageInfoList::value_type;
using CheckerOrPackageFullNameLT = FullNameLT<CheckerOrPackage>;
assert(std::is_sorted(Collection.begin(), Collection.end(),
CheckerOrPackageFullNameLT{}) &&
"In order to efficiently gather checkers/packages, this function "
"expects them to be already sorted!");
typename CheckerOrPackageInfoList::value_type Info(FullName);
return llvm::lower_bound(
Collection, Info,
FullNameLT<typename CheckerOrPackageInfoList::value_type>{});
}
static constexpr char PackageSeparator = '.';
static bool isInPackage(const CheckerRegistry::CheckerInfo &Checker,
StringRef PackageName) {
// Does the checker's full name have the package as a prefix?
if (!Checker.FullName.startswith(PackageName))
return false;
// Is the package actually just the name of a specific checker?
if (Checker.FullName.size() == PackageName.size())
return true;
// Is the checker in the package (or a subpackage)?
if (Checker.FullName[PackageName.size()] == PackageSeparator)
return true;
return false;
}
CheckerRegistry::CheckerInfoListRange
CheckerRegistry::getMutableCheckersForCmdLineArg(StringRef CmdLineArg) {
auto It = binaryFind(Checkers, CmdLineArg);
if (!isInPackage(*It, CmdLineArg))
return {Checkers.end(), Checkers.end()};
// See how large the package is.
// If the package doesn't exist, assume the option refers to a single
// checker.
size_t Size = 1;
llvm::StringMap<size_t>::const_iterator PackageSize =
PackageSizes.find(CmdLineArg);
if (PackageSize != PackageSizes.end())
Size = PackageSize->getValue();
return {It, It + Size};
}
CheckerRegistry::CheckerRegistry(
ArrayRef<std::string> Plugins, DiagnosticsEngine &Diags,
AnalyzerOptions &AnOpts, const LangOptions &LangOpts,
ArrayRef<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns)
: Diags(Diags), AnOpts(AnOpts), LangOpts(LangOpts) {
// Register builtin checkers.
#define GET_CHECKERS
#define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI) \
addChecker(register##CLASS, shouldRegister##CLASS, FULLNAME, HELPTEXT, \
DOC_URI);
#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
#undef CHECKER
#undef GET_CHECKERS
#undef PACKAGE
#undef GET_PACKAGES
// Register checkers from plugins.
for (const std::string &Plugin : Plugins) {
// Get access to the plugin.
std::string ErrorMsg;
DynamicLibrary Lib =
DynamicLibrary::getPermanentLibrary(Plugin.c_str(), &ErrorMsg);
if (!Lib.isValid()) {
Diags.Report(diag::err_fe_unable_to_load_plugin) << Plugin << ErrorMsg;
continue;
}
// See if its compatible with this build of clang.
const char *PluginAPIVersion = static_cast<const char *>(
Lib.getAddressOfSymbol("clang_analyzerAPIVersionString"));
if (!isCompatibleAPIVersion(PluginAPIVersion)) {
Diags.Report(diag::warn_incompatible_analyzer_plugin_api)
<< llvm::sys::path::filename(Plugin);
Diags.Report(diag::note_incompatible_analyzer_plugin_api)
<< CLANG_ANALYZER_API_VERSION_STRING << PluginAPIVersion;
continue;
}
// Register its checkers.
RegisterCheckersFn RegisterPluginCheckers =
reinterpret_cast<RegisterCheckersFn>(
Lib.getAddressOfSymbol("clang_registerCheckers"));
if (RegisterPluginCheckers)
RegisterPluginCheckers(*this);
}
// Register statically linked checkers, that aren't generated from the tblgen
// file, but rather passed their registry function as a parameter in
// checkerRegistrationFns.
for (const auto &Fn : CheckerRegistrationFns)
Fn(*this);
// Sort checkers for efficient collection.
// FIXME: Alphabetical sort puts 'experimental' in the middle.
// Would it be better to name it '~experimental' or something else
// that's ASCIIbetically last?
llvm::sort(Checkers, CheckerNameLT{});
#define GET_CHECKER_DEPENDENCIES
#define CHECKER_DEPENDENCY(FULLNAME, DEPENDENCY) \
addDependency(FULLNAME, DEPENDENCY);
#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
#undef CHECKER_DEPENDENCY
#undef GET_CHECKER_DEPENDENCIES
// Parse '-analyzer-checker' and '-analyzer-disable-checker' options from the
// command line.
for (const std::pair<std::string, bool> &Opt : AnOpts.CheckersControlList) {
CheckerInfoListRange CheckerForCmdLineArg =
getMutableCheckersForCmdLineArg(Opt.first);
if (CheckerForCmdLineArg.begin() == CheckerForCmdLineArg.end()) {
Diags.Report(diag::err_unknown_analyzer_checker) << Opt.first;
Diags.Report(diag::note_suggest_disabling_all_checkers);
}
for (CheckerInfo &checker : CheckerForCmdLineArg) {
checker.State = Opt.second ? StateFromCmdLine::State_Enabled
: StateFromCmdLine::State_Disabled;
}
}
}
/// Collects dependencies in \p ret, returns false on failure.
static bool
collectDependenciesImpl(const CheckerRegistry::ConstCheckerInfoList &Deps,
const LangOptions &LO,
CheckerRegistry::CheckerInfoSet &Ret);
/// Collects dependenies in \p enabledCheckers. Return None on failure.
LLVM_NODISCARD
static llvm::Optional<CheckerRegistry::CheckerInfoSet>
collectDependencies(const CheckerRegistry::CheckerInfo &checker,
const LangOptions &LO) {
CheckerRegistry::CheckerInfoSet Ret;
// Add dependencies to the enabled checkers only if all of them can be
// enabled.
if (!collectDependenciesImpl(checker.Dependencies, LO, Ret))
return None;
return Ret;
}
static bool
collectDependenciesImpl(const CheckerRegistry::ConstCheckerInfoList &Deps,
const LangOptions &LO,
CheckerRegistry::CheckerInfoSet &Ret) {
for (const CheckerRegistry::CheckerInfo *Dependency : Deps) {
if (Dependency->isDisabled(LO))
return false;
// Collect dependencies recursively.
if (!collectDependenciesImpl(Dependency->Dependencies, LO, Ret))
return false;
Ret.insert(Dependency);
}
return true;
}
CheckerRegistry::CheckerInfoSet CheckerRegistry::getEnabledCheckers() const {
CheckerInfoSet EnabledCheckers;
for (const CheckerInfo &Checker : Checkers) {
if (!Checker.isEnabled(LangOpts))
continue;
// Recursively enable its dependencies.
llvm::Optional<CheckerInfoSet> Deps =
collectDependencies(Checker, LangOpts);
if (!Deps) {
// If we failed to enable any of the dependencies, don't enable this
// checker.
continue;
}
// Note that set_union also preserves the order of insertion.
EnabledCheckers.set_union(*Deps);
// Enable the checker.
EnabledCheckers.insert(&Checker);
}
return EnabledCheckers;
}
void CheckerRegistry::addChecker(InitializationFunction Rfn,
ShouldRegisterFunction Sfn, StringRef Name,
StringRef Desc, StringRef DocsUri) {
Checkers.emplace_back(Rfn, Sfn, Name, Desc, DocsUri);
// Record the presence of the checker in its packages.
StringRef PackageName, LeafName;
std::tie(PackageName, LeafName) = Name.rsplit(PackageSeparator);
while (!LeafName.empty()) {
PackageSizes[PackageName] += 1;
std::tie(PackageName, LeafName) = PackageName.rsplit(PackageSeparator);
}
}
void CheckerRegistry::addDependency(StringRef FullName, StringRef Dependency) {
auto CheckerIt = binaryFind(Checkers, FullName);
assert(CheckerIt != Checkers.end() && CheckerIt->FullName == FullName &&
"Failed to find the checker while attempting to set up its "
"dependencies!");
auto DependencyIt = binaryFind(Checkers, Dependency);
assert(DependencyIt != Checkers.end() &&
DependencyIt->FullName == Dependency &&
"Failed to find the dependency of a checker!");
CheckerIt->Dependencies.emplace_back(&*DependencyIt);
}
void CheckerRegistry::initializeManager(CheckerManager &CheckerMgr) const {
// Collect checkers enabled by the options.
CheckerInfoSet enabledCheckers = getEnabledCheckers();
// Initialize the CheckerManager with all enabled checkers.
for (const auto *Checker : enabledCheckers) {
CheckerMgr.setCurrentCheckName(CheckName(Checker->FullName));
Checker->Initialize(CheckerMgr);
}
}
void CheckerRegistry::validateCheckerOptions() const {
for (const auto &Config : AnOpts.Config) {
size_t Pos = Config.getKey().find(':');
if (Pos == StringRef::npos)
continue;
bool HasChecker = false;
StringRef CheckerName = Config.getKey().substr(0, Pos);
for (const auto &Checker : Checkers) {
if (Checker.FullName.startswith(CheckerName) &&
(Checker.FullName.size() == Pos || Checker.FullName[Pos] == '.')) {
HasChecker = true;
break;
}
}
if (!HasChecker)
Diags.Report(diag::err_unknown_analyzer_checker) << CheckerName;
}
}
void CheckerRegistry::printCheckerWithDescList(raw_ostream &Out,
size_t MaxNameChars) const {
// FIXME: Print available packages.
Out << "CHECKERS:\n";
// Find the maximum option length.
size_t OptionFieldWidth = 0;
for (const auto &Checker : Checkers) {
// Limit the amount of padding we are willing to give up for alignment.
// Package.Name Description [Hidden]
size_t NameLength = Checker.FullName.size();
if (NameLength <= MaxNameChars)
OptionFieldWidth = std::max(OptionFieldWidth, NameLength);
}
const size_t InitialPad = 2;
for (const auto &Checker : Checkers) {
Out.indent(InitialPad) << Checker.FullName;
int Pad = OptionFieldWidth - Checker.FullName.size();
// Break on long option names.
if (Pad < 0) {
Out << '\n';
Pad = OptionFieldWidth + InitialPad;
}
Out.indent(Pad + 2) << Checker.Desc;
Out << '\n';
}
}
void CheckerRegistry::printEnabledCheckerList(raw_ostream &Out) const {
// Collect checkers enabled by the options.
CheckerInfoSet EnabledCheckers = getEnabledCheckers();
for (const auto *i : EnabledCheckers)
Out << i->FullName << '\n';
}
<commit_msg>[analyzer] Fix -Wunused-local-typedef after rC358695<commit_after>//===- CheckerRegistry.cpp - Maintains all available checkers -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/LLVM.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace clang;
using namespace ento;
using llvm::sys::DynamicLibrary;
using RegisterCheckersFn = void (*)(CheckerRegistry &);
static bool isCompatibleAPIVersion(const char *VersionString) {
// If the version string is null, its not an analyzer plugin.
if (!VersionString)
return false;
// For now, none of the static analyzer API is considered stable.
// Versions must match exactly.
return strcmp(VersionString, CLANG_ANALYZER_API_VERSION_STRING) == 0;
}
namespace {
template <class T> struct FullNameLT {
bool operator()(const T &Lhs, const T &Rhs) {
return Lhs.FullName < Rhs.FullName;
}
};
using CheckerNameLT = FullNameLT<CheckerRegistry::CheckerInfo>;
} // end of anonymous namespace
template <class CheckerOrPackageInfoList>
static
typename std::conditional<std::is_const<CheckerOrPackageInfoList>::value,
typename CheckerOrPackageInfoList::const_iterator,
typename CheckerOrPackageInfoList::iterator>::type
binaryFind(CheckerOrPackageInfoList &Collection, StringRef FullName) {
using CheckerOrPackage = typename CheckerOrPackageInfoList::value_type;
using CheckerOrPackageFullNameLT = FullNameLT<CheckerOrPackage>;
assert(std::is_sorted(Collection.begin(), Collection.end(),
CheckerOrPackageFullNameLT{}) &&
"In order to efficiently gather checkers/packages, this function "
"expects them to be already sorted!");
return llvm::lower_bound(Collection, CheckerOrPackage(FullName),
CheckerOrPackageFullNameLT{});
}
static constexpr char PackageSeparator = '.';
static bool isInPackage(const CheckerRegistry::CheckerInfo &Checker,
StringRef PackageName) {
// Does the checker's full name have the package as a prefix?
if (!Checker.FullName.startswith(PackageName))
return false;
// Is the package actually just the name of a specific checker?
if (Checker.FullName.size() == PackageName.size())
return true;
// Is the checker in the package (or a subpackage)?
if (Checker.FullName[PackageName.size()] == PackageSeparator)
return true;
return false;
}
CheckerRegistry::CheckerInfoListRange
CheckerRegistry::getMutableCheckersForCmdLineArg(StringRef CmdLineArg) {
auto It = binaryFind(Checkers, CmdLineArg);
if (!isInPackage(*It, CmdLineArg))
return {Checkers.end(), Checkers.end()};
// See how large the package is.
// If the package doesn't exist, assume the option refers to a single
// checker.
size_t Size = 1;
llvm::StringMap<size_t>::const_iterator PackageSize =
PackageSizes.find(CmdLineArg);
if (PackageSize != PackageSizes.end())
Size = PackageSize->getValue();
return {It, It + Size};
}
CheckerRegistry::CheckerRegistry(
ArrayRef<std::string> Plugins, DiagnosticsEngine &Diags,
AnalyzerOptions &AnOpts, const LangOptions &LangOpts,
ArrayRef<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns)
: Diags(Diags), AnOpts(AnOpts), LangOpts(LangOpts) {
// Register builtin checkers.
#define GET_CHECKERS
#define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI) \
addChecker(register##CLASS, shouldRegister##CLASS, FULLNAME, HELPTEXT, \
DOC_URI);
#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
#undef CHECKER
#undef GET_CHECKERS
#undef PACKAGE
#undef GET_PACKAGES
// Register checkers from plugins.
for (const std::string &Plugin : Plugins) {
// Get access to the plugin.
std::string ErrorMsg;
DynamicLibrary Lib =
DynamicLibrary::getPermanentLibrary(Plugin.c_str(), &ErrorMsg);
if (!Lib.isValid()) {
Diags.Report(diag::err_fe_unable_to_load_plugin) << Plugin << ErrorMsg;
continue;
}
// See if its compatible with this build of clang.
const char *PluginAPIVersion = static_cast<const char *>(
Lib.getAddressOfSymbol("clang_analyzerAPIVersionString"));
if (!isCompatibleAPIVersion(PluginAPIVersion)) {
Diags.Report(diag::warn_incompatible_analyzer_plugin_api)
<< llvm::sys::path::filename(Plugin);
Diags.Report(diag::note_incompatible_analyzer_plugin_api)
<< CLANG_ANALYZER_API_VERSION_STRING << PluginAPIVersion;
continue;
}
// Register its checkers.
RegisterCheckersFn RegisterPluginCheckers =
reinterpret_cast<RegisterCheckersFn>(
Lib.getAddressOfSymbol("clang_registerCheckers"));
if (RegisterPluginCheckers)
RegisterPluginCheckers(*this);
}
// Register statically linked checkers, that aren't generated from the tblgen
// file, but rather passed their registry function as a parameter in
// checkerRegistrationFns.
for (const auto &Fn : CheckerRegistrationFns)
Fn(*this);
// Sort checkers for efficient collection.
// FIXME: Alphabetical sort puts 'experimental' in the middle.
// Would it be better to name it '~experimental' or something else
// that's ASCIIbetically last?
llvm::sort(Checkers, CheckerNameLT{});
#define GET_CHECKER_DEPENDENCIES
#define CHECKER_DEPENDENCY(FULLNAME, DEPENDENCY) \
addDependency(FULLNAME, DEPENDENCY);
#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
#undef CHECKER_DEPENDENCY
#undef GET_CHECKER_DEPENDENCIES
// Parse '-analyzer-checker' and '-analyzer-disable-checker' options from the
// command line.
for (const std::pair<std::string, bool> &Opt : AnOpts.CheckersControlList) {
CheckerInfoListRange CheckerForCmdLineArg =
getMutableCheckersForCmdLineArg(Opt.first);
if (CheckerForCmdLineArg.begin() == CheckerForCmdLineArg.end()) {
Diags.Report(diag::err_unknown_analyzer_checker) << Opt.first;
Diags.Report(diag::note_suggest_disabling_all_checkers);
}
for (CheckerInfo &checker : CheckerForCmdLineArg) {
checker.State = Opt.second ? StateFromCmdLine::State_Enabled
: StateFromCmdLine::State_Disabled;
}
}
}
/// Collects dependencies in \p ret, returns false on failure.
static bool
collectDependenciesImpl(const CheckerRegistry::ConstCheckerInfoList &Deps,
const LangOptions &LO,
CheckerRegistry::CheckerInfoSet &Ret);
/// Collects dependenies in \p enabledCheckers. Return None on failure.
LLVM_NODISCARD
static llvm::Optional<CheckerRegistry::CheckerInfoSet>
collectDependencies(const CheckerRegistry::CheckerInfo &checker,
const LangOptions &LO) {
CheckerRegistry::CheckerInfoSet Ret;
// Add dependencies to the enabled checkers only if all of them can be
// enabled.
if (!collectDependenciesImpl(checker.Dependencies, LO, Ret))
return None;
return Ret;
}
static bool
collectDependenciesImpl(const CheckerRegistry::ConstCheckerInfoList &Deps,
const LangOptions &LO,
CheckerRegistry::CheckerInfoSet &Ret) {
for (const CheckerRegistry::CheckerInfo *Dependency : Deps) {
if (Dependency->isDisabled(LO))
return false;
// Collect dependencies recursively.
if (!collectDependenciesImpl(Dependency->Dependencies, LO, Ret))
return false;
Ret.insert(Dependency);
}
return true;
}
CheckerRegistry::CheckerInfoSet CheckerRegistry::getEnabledCheckers() const {
CheckerInfoSet EnabledCheckers;
for (const CheckerInfo &Checker : Checkers) {
if (!Checker.isEnabled(LangOpts))
continue;
// Recursively enable its dependencies.
llvm::Optional<CheckerInfoSet> Deps =
collectDependencies(Checker, LangOpts);
if (!Deps) {
// If we failed to enable any of the dependencies, don't enable this
// checker.
continue;
}
// Note that set_union also preserves the order of insertion.
EnabledCheckers.set_union(*Deps);
// Enable the checker.
EnabledCheckers.insert(&Checker);
}
return EnabledCheckers;
}
void CheckerRegistry::addChecker(InitializationFunction Rfn,
ShouldRegisterFunction Sfn, StringRef Name,
StringRef Desc, StringRef DocsUri) {
Checkers.emplace_back(Rfn, Sfn, Name, Desc, DocsUri);
// Record the presence of the checker in its packages.
StringRef PackageName, LeafName;
std::tie(PackageName, LeafName) = Name.rsplit(PackageSeparator);
while (!LeafName.empty()) {
PackageSizes[PackageName] += 1;
std::tie(PackageName, LeafName) = PackageName.rsplit(PackageSeparator);
}
}
void CheckerRegistry::addDependency(StringRef FullName, StringRef Dependency) {
auto CheckerIt = binaryFind(Checkers, FullName);
assert(CheckerIt != Checkers.end() && CheckerIt->FullName == FullName &&
"Failed to find the checker while attempting to set up its "
"dependencies!");
auto DependencyIt = binaryFind(Checkers, Dependency);
assert(DependencyIt != Checkers.end() &&
DependencyIt->FullName == Dependency &&
"Failed to find the dependency of a checker!");
CheckerIt->Dependencies.emplace_back(&*DependencyIt);
}
void CheckerRegistry::initializeManager(CheckerManager &CheckerMgr) const {
// Collect checkers enabled by the options.
CheckerInfoSet enabledCheckers = getEnabledCheckers();
// Initialize the CheckerManager with all enabled checkers.
for (const auto *Checker : enabledCheckers) {
CheckerMgr.setCurrentCheckName(CheckName(Checker->FullName));
Checker->Initialize(CheckerMgr);
}
}
void CheckerRegistry::validateCheckerOptions() const {
for (const auto &Config : AnOpts.Config) {
size_t Pos = Config.getKey().find(':');
if (Pos == StringRef::npos)
continue;
bool HasChecker = false;
StringRef CheckerName = Config.getKey().substr(0, Pos);
for (const auto &Checker : Checkers) {
if (Checker.FullName.startswith(CheckerName) &&
(Checker.FullName.size() == Pos || Checker.FullName[Pos] == '.')) {
HasChecker = true;
break;
}
}
if (!HasChecker)
Diags.Report(diag::err_unknown_analyzer_checker) << CheckerName;
}
}
void CheckerRegistry::printCheckerWithDescList(raw_ostream &Out,
size_t MaxNameChars) const {
// FIXME: Print available packages.
Out << "CHECKERS:\n";
// Find the maximum option length.
size_t OptionFieldWidth = 0;
for (const auto &Checker : Checkers) {
// Limit the amount of padding we are willing to give up for alignment.
// Package.Name Description [Hidden]
size_t NameLength = Checker.FullName.size();
if (NameLength <= MaxNameChars)
OptionFieldWidth = std::max(OptionFieldWidth, NameLength);
}
const size_t InitialPad = 2;
for (const auto &Checker : Checkers) {
Out.indent(InitialPad) << Checker.FullName;
int Pad = OptionFieldWidth - Checker.FullName.size();
// Break on long option names.
if (Pad < 0) {
Out << '\n';
Pad = OptionFieldWidth + InitialPad;
}
Out.indent(Pad + 2) << Checker.Desc;
Out << '\n';
}
}
void CheckerRegistry::printEnabledCheckerList(raw_ostream &Out) const {
// Collect checkers enabled by the options.
CheckerInfoSet EnabledCheckers = getEnabledCheckers();
for (const auto *i : EnabledCheckers)
Out << i->FullName << '\n';
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "Downloads.h"
/* system headers */
#include <map>
#include <vector>
/* common implementation headers */
#include "network.h"
#include "AccessList.h"
#include "CacheManager.h"
#include "BzMaterial.h"
#include "AnsiCodes.h"
#include "TextureManager.h"
#include "cURLManager.h"
/* local implementation headers */
#include "playing.h"
#include "HUDDialogStack.h"
// stupid globals for stupid file tracker
int totalTex = 0;
int currentTex = 0;
int runs = 0;
// FIXME - someone write a better explanation
static const char DownloadContent[] =
"#\n"
"# This file controls the access to servers for downloads.\n"
"# Patterns are attempted in order against both the hostname\n"
"# and ip. The first matching pattern sets the state. If no\n"
"# patterns are matched, then the server is authorized. There\n"
"# are four types of matches:\n"
"#\n"
"# simple globbing (* and ?)\n"
"# allow\n"
"# deny\n"
"#\n"
"# regular expressions\n"
"# allow_regex\n"
"# deny_regex\n"
"#\n"
"\n"
"#\n"
"# To authorize all servers, remove the last 3 lines.\n"
"#\n"
"\n"
"allow *.bzflag.bz\n"
"allow *.bzflag.org\n"
"deny *\n";
static AccessList DownloadAccessList("DownloadAccess.txt", DownloadContent);
static bool textureDownloading = false;
// Function Prototypes
static void printAuthNotice();
static bool checkAuthorizations(BzMaterialManager::TextureSet& set);
class CachedTexture : cURLManager {
public:
CachedTexture(const std::string &texUrl);
virtual void finalization(char *data, unsigned int length, bool good);
static void setParams(bool check, long timeout);
static int activeTransfer();
private:
virtual void collectData(char* ptr, int len);
std::string url;
static bool checkForCache;
static long httpTimeout;
static int textureCounter;
static int byteTransferred;
bool timeRequest;
};
bool CachedTexture::checkForCache = false;
long CachedTexture::httpTimeout = 0;
int CachedTexture::textureCounter = 0;
int CachedTexture::byteTransferred = 0;
CachedTexture::CachedTexture(const std::string &texUrl) : cURLManager()
{
CacheManager::CacheRecord oldrec;
setURL(texUrl);
url = texUrl;
// use the cache?
bool cached = CACHEMGR.findURL(texUrl, oldrec);
if (cached && !checkForCache) {
// use the cached file
MATERIALMGR.setTextureLocal(texUrl, oldrec.name);
} else {
textureCounter++;
if (httpTimeout > 0.0)
setTimeout(httpTimeout);
setRequestFileTime(true);
timeRequest = cached;
std::string msg = ColorStrings[GreyColor];
msg += "downloading: " + url;
addMessage(NULL, msg);
if (cached) {
// use the cached file -- just in case
MATERIALMGR.setTextureLocal(url, oldrec.name);
setTimeCondition(ModifiedSince, oldrec.date);
}
addHandle();
}
}
void CachedTexture::setParams(bool check, long timeout)
{
checkForCache = check;
httpTimeout = timeout;
textureCounter = 0;
byteTransferred = 0;
}
void CachedTexture::finalization(char *data, unsigned int length, bool good)
{
time_t filetime;
textureCounter--;
if (good) {
if (length) {
getFileTime(filetime);
// CACHEMGR generates name, usedDate, and key
CacheManager::CacheRecord rec;
rec.url = url;
rec.size = length;
rec.date = filetime;
CACHEMGR.addFile(rec, data);
const std::string localname = CACHEMGR.getLocalName(url);
TextureManager& TEXMGR = TextureManager::instance();
if (TEXMGR.isLoaded(localname)) {
TEXMGR.reloadTextureImage(localname); // reload with the new image
}
MATERIALMGR.setTextureLocal(url, localname);
}
} else {
MATERIALMGR.setTextureLocal(url, "");
}
}
int CachedTexture::activeTransfer()
{
return textureCounter;
}
void CachedTexture::collectData(char* ptr, int len)
{
char buffer[128];
if(runs == 0)
totalTex = textureCounter;
cURLManager::collectData(ptr, len);
byteTransferred += len;
//Make it so it counts textures in reverse order (0 to max instead of max to 0)
currentTex = totalTex - textureCounter + 1;
//Turn bytes into kilobytes
sprintf (buffer, "Downloading texture (%d of %d): %d KB", currentTex, totalTex, byteTransferred/1024);
runs++;
HUDDialogStack::get()->setFailedMessage(buffer);
}
std::vector<CachedTexture*> cachedTexVector;
void Downloads::startDownloads(bool doDownloads, bool updateDownloads,
bool referencing)
{
totalTex = 0;
currentTex = 0;
runs = 0;
CACHEMGR.loadIndex();
CACHEMGR.limitCacheSize();
DownloadAccessList.reload();
BzMaterialManager::TextureSet set;
BzMaterialManager::TextureSet::iterator set_it;
MATERIALMGR.makeTextureList(set, referencing);
float timeout = 15;
if (BZDB.isSet("httpTimeout")) {
timeout = BZDB.eval("httpTimeout");
}
CachedTexture::setParams(updateDownloads, (long)timeout);
// check hosts' access permissions
bool authNotice = checkAuthorizations(set);
if (!referencing) {
// Clear old cached texture
// This is the first time is called after joining
int texNo = cachedTexVector.size();
for (int i = 0; i < texNo; i++)
delete cachedTexVector[i];
cachedTexVector.clear();
}
if (doDownloads)
for (set_it = set.begin(); set_it != set.end(); set_it++) {
const std::string& texUrl = set_it->c_str();
if (CACHEMGR.isCacheFileType(texUrl)) {
if (!referencing)
MATERIALMGR.setTextureLocal(texUrl, "");
cachedTexVector.push_back(new CachedTexture(texUrl));
}
}
else
for (set_it = set.begin(); set_it != set.end(); set_it++) {
const std::string& texUrl = set_it->c_str();
if (CACHEMGR.isCacheFileType(texUrl)) {
// use the cache?
CacheManager::CacheRecord oldrec;
if (CACHEMGR.findURL(texUrl, oldrec)) {
// use the cached file
MATERIALMGR.setTextureLocal(texUrl, oldrec.name);
} else {
// bail here if we can't download
MATERIALMGR.setTextureLocal(texUrl, "");
std::string msg = ColorStrings[GreyColor];
msg += "not downloading: " + texUrl;
addMessage(NULL, msg);
}
}
}
if (authNotice) {
printAuthNotice();
}
textureDownloading = true;
}
void Downloads::finalizeDownloads()
{
textureDownloading = false;
int texNo = cachedTexVector.size();
for (int i = 0; i < texNo; i++)
delete cachedTexVector[i];
cachedTexVector.clear();
CACHEMGR.saveIndex();
}
bool Downloads::requestFinalized()
{
return textureDownloading && (CachedTexture::activeTransfer() == 0);
}
void Downloads::removeTextures()
{
BzMaterialManager::TextureSet set;
BzMaterialManager::TextureSet::iterator set_it;
MATERIALMGR.makeTextureList(set, false /* ignore referencing */);
TextureManager& TEXMGR = TextureManager::instance();
for (set_it = set.begin(); set_it != set.end(); set_it++) {
const std::string& texUrl = set_it->c_str();
if (CACHEMGR.isCacheFileType(texUrl)) {
const std::string& localname = CACHEMGR.getLocalName(texUrl);
if (TEXMGR.isLoaded(localname)) {
TEXMGR.removeTexture(localname);
}
}
}
return;
}
static void printAuthNotice()
{
std::string msg = ColorStrings[WhiteColor];
msg += "NOTE: ";
msg += ColorStrings[GreyColor];
msg += "download access is controlled by ";
msg += ColorStrings[YellowColor];
msg += DownloadAccessList.getFileName();
addMessage(NULL, msg);
return;
}
bool authorizedServer(const std::string& hostname)
{
// Don't do here a DNS lookup, it can block the client
// DNS is temporary removed until someone code it unblocking
// make the list of strings to check
std::vector<std::string> nameAndIp;
if (hostname.size() > 0) {
nameAndIp.push_back(hostname);
}
return DownloadAccessList.authorized(nameAndIp);
}
bool parseHostname(const std::string& url, std::string& hostname)
{
std::string protocol, path, ip;
int port;
if (BzfNetwork::parseURL(url, protocol, hostname, port, path)) {
if ((protocol == "http") || (protocol == "ftp")) {
return true;
}
}
return false;
}
static bool checkAuthorizations(BzMaterialManager::TextureSet& set)
{
// avoid the DNS lookup
if (DownloadAccessList.alwaysAuthorized()) {
return false;
}
bool hostFailed = false;
BzMaterialManager::TextureSet::iterator set_it;
std::map<std::string, bool> hostAccess;
std::map<std::string, bool>::iterator host_it;
// get the list of hosts to check
for (set_it = set.begin(); set_it != set.end(); set_it++) {
const std::string& url = *set_it;
std::string hostname;
if (parseHostname(url, hostname)) {
hostAccess[hostname] = true;
}
}
// check the hosts
for (host_it = hostAccess.begin(); host_it != hostAccess.end(); host_it++) {
const std::string& host = host_it->first;
host_it->second = authorizedServer(host);
}
// clear any unauthorized urls
set_it = set.begin();
while (set_it != set.end()) {
BzMaterialManager::TextureSet::iterator next_it = set_it;
next_it++;
const std::string& url = *set_it;
std::string hostname;
if (parseHostname(url, hostname) && !hostAccess[hostname]) {
hostFailed = true;
// send a message
std::string msg = ColorStrings[RedColor];
msg += "local denial: ";
msg += ColorStrings[GreyColor];
msg += url;
addMessage(NULL, msg);
// remove the url
MATERIALMGR.setTextureLocal(url, "");
set.erase(set_it);
}
set_it = next_it;
}
return hostFailed;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>do not use global vars if they don't need to be exported<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "Downloads.h"
/* system headers */
#include <map>
#include <vector>
/* common implementation headers */
#include "network.h"
#include "AccessList.h"
#include "CacheManager.h"
#include "BzMaterial.h"
#include "AnsiCodes.h"
#include "TextureManager.h"
#include "cURLManager.h"
/* local implementation headers */
#include "playing.h"
#include "HUDDialogStack.h"
// local variables for file tracker
static int totalTex = 0;
static int currentTex = 0;
static int runs = 0;
// FIXME - someone write a better explanation
static const char DownloadContent[] =
"#\n"
"# This file controls the access to servers for downloads.\n"
"# Patterns are attempted in order against both the hostname\n"
"# and ip. The first matching pattern sets the state. If no\n"
"# patterns are matched, then the server is authorized. There\n"
"# are four types of matches:\n"
"#\n"
"# simple globbing (* and ?)\n"
"# allow\n"
"# deny\n"
"#\n"
"# regular expressions\n"
"# allow_regex\n"
"# deny_regex\n"
"#\n"
"\n"
"#\n"
"# To authorize all servers, remove the last 3 lines.\n"
"#\n"
"\n"
"allow *.bzflag.bz\n"
"allow *.bzflag.org\n"
"deny *\n";
static AccessList DownloadAccessList("DownloadAccess.txt", DownloadContent);
static bool textureDownloading = false;
// Function Prototypes
static void printAuthNotice();
static bool checkAuthorizations(BzMaterialManager::TextureSet& set);
class CachedTexture : cURLManager {
public:
CachedTexture(const std::string &texUrl);
virtual void finalization(char *data, unsigned int length, bool good);
static void setParams(bool check, long timeout);
static int activeTransfer();
private:
virtual void collectData(char* ptr, int len);
std::string url;
static bool checkForCache;
static long httpTimeout;
static int textureCounter;
static int byteTransferred;
bool timeRequest;
};
bool CachedTexture::checkForCache = false;
long CachedTexture::httpTimeout = 0;
int CachedTexture::textureCounter = 0;
int CachedTexture::byteTransferred = 0;
CachedTexture::CachedTexture(const std::string &texUrl) : cURLManager()
{
CacheManager::CacheRecord oldrec;
setURL(texUrl);
url = texUrl;
// use the cache?
bool cached = CACHEMGR.findURL(texUrl, oldrec);
if (cached && !checkForCache) {
// use the cached file
MATERIALMGR.setTextureLocal(texUrl, oldrec.name);
} else {
textureCounter++;
if (httpTimeout > 0.0)
setTimeout(httpTimeout);
setRequestFileTime(true);
timeRequest = cached;
std::string msg = ColorStrings[GreyColor];
msg += "downloading: " + url;
addMessage(NULL, msg);
if (cached) {
// use the cached file -- just in case
MATERIALMGR.setTextureLocal(url, oldrec.name);
setTimeCondition(ModifiedSince, oldrec.date);
}
addHandle();
}
}
void CachedTexture::setParams(bool check, long timeout)
{
checkForCache = check;
httpTimeout = timeout;
textureCounter = 0;
byteTransferred = 0;
}
void CachedTexture::finalization(char *data, unsigned int length, bool good)
{
time_t filetime;
textureCounter--;
if (good) {
if (length) {
getFileTime(filetime);
// CACHEMGR generates name, usedDate, and key
CacheManager::CacheRecord rec;
rec.url = url;
rec.size = length;
rec.date = filetime;
CACHEMGR.addFile(rec, data);
const std::string localname = CACHEMGR.getLocalName(url);
TextureManager& TEXMGR = TextureManager::instance();
if (TEXMGR.isLoaded(localname)) {
TEXMGR.reloadTextureImage(localname); // reload with the new image
}
MATERIALMGR.setTextureLocal(url, localname);
}
} else {
MATERIALMGR.setTextureLocal(url, "");
}
}
int CachedTexture::activeTransfer()
{
return textureCounter;
}
void CachedTexture::collectData(char* ptr, int len)
{
char buffer[128];
if(runs == 0)
totalTex = textureCounter;
cURLManager::collectData(ptr, len);
byteTransferred += len;
//Make it so it counts textures in reverse order (0 to max instead of max to 0)
currentTex = totalTex - textureCounter + 1;
//Turn bytes into kilobytes
sprintf (buffer, "Downloading texture (%d of %d): %d KB", currentTex, totalTex, byteTransferred/1024);
runs++;
HUDDialogStack::get()->setFailedMessage(buffer);
}
std::vector<CachedTexture*> cachedTexVector;
void Downloads::startDownloads(bool doDownloads, bool updateDownloads,
bool referencing)
{
totalTex = 0;
currentTex = 0;
runs = 0;
CACHEMGR.loadIndex();
CACHEMGR.limitCacheSize();
DownloadAccessList.reload();
BzMaterialManager::TextureSet set;
BzMaterialManager::TextureSet::iterator set_it;
MATERIALMGR.makeTextureList(set, referencing);
float timeout = 15;
if (BZDB.isSet("httpTimeout")) {
timeout = BZDB.eval("httpTimeout");
}
CachedTexture::setParams(updateDownloads, (long)timeout);
// check hosts' access permissions
bool authNotice = checkAuthorizations(set);
if (!referencing) {
// Clear old cached texture
// This is the first time is called after joining
int texNo = cachedTexVector.size();
for (int i = 0; i < texNo; i++)
delete cachedTexVector[i];
cachedTexVector.clear();
}
if (doDownloads)
for (set_it = set.begin(); set_it != set.end(); set_it++) {
const std::string& texUrl = set_it->c_str();
if (CACHEMGR.isCacheFileType(texUrl)) {
if (!referencing)
MATERIALMGR.setTextureLocal(texUrl, "");
cachedTexVector.push_back(new CachedTexture(texUrl));
}
}
else
for (set_it = set.begin(); set_it != set.end(); set_it++) {
const std::string& texUrl = set_it->c_str();
if (CACHEMGR.isCacheFileType(texUrl)) {
// use the cache?
CacheManager::CacheRecord oldrec;
if (CACHEMGR.findURL(texUrl, oldrec)) {
// use the cached file
MATERIALMGR.setTextureLocal(texUrl, oldrec.name);
} else {
// bail here if we can't download
MATERIALMGR.setTextureLocal(texUrl, "");
std::string msg = ColorStrings[GreyColor];
msg += "not downloading: " + texUrl;
addMessage(NULL, msg);
}
}
}
if (authNotice) {
printAuthNotice();
}
textureDownloading = true;
}
void Downloads::finalizeDownloads()
{
textureDownloading = false;
int texNo = cachedTexVector.size();
for (int i = 0; i < texNo; i++)
delete cachedTexVector[i];
cachedTexVector.clear();
CACHEMGR.saveIndex();
}
bool Downloads::requestFinalized()
{
return textureDownloading && (CachedTexture::activeTransfer() == 0);
}
void Downloads::removeTextures()
{
BzMaterialManager::TextureSet set;
BzMaterialManager::TextureSet::iterator set_it;
MATERIALMGR.makeTextureList(set, false /* ignore referencing */);
TextureManager& TEXMGR = TextureManager::instance();
for (set_it = set.begin(); set_it != set.end(); set_it++) {
const std::string& texUrl = set_it->c_str();
if (CACHEMGR.isCacheFileType(texUrl)) {
const std::string& localname = CACHEMGR.getLocalName(texUrl);
if (TEXMGR.isLoaded(localname)) {
TEXMGR.removeTexture(localname);
}
}
}
return;
}
static void printAuthNotice()
{
std::string msg = ColorStrings[WhiteColor];
msg += "NOTE: ";
msg += ColorStrings[GreyColor];
msg += "download access is controlled by ";
msg += ColorStrings[YellowColor];
msg += DownloadAccessList.getFileName();
addMessage(NULL, msg);
return;
}
bool authorizedServer(const std::string& hostname)
{
// Don't do here a DNS lookup, it can block the client
// DNS is temporary removed until someone code it unblocking
// make the list of strings to check
std::vector<std::string> nameAndIp;
if (hostname.size() > 0) {
nameAndIp.push_back(hostname);
}
return DownloadAccessList.authorized(nameAndIp);
}
bool parseHostname(const std::string& url, std::string& hostname)
{
std::string protocol, path, ip;
int port;
if (BzfNetwork::parseURL(url, protocol, hostname, port, path)) {
if ((protocol == "http") || (protocol == "ftp")) {
return true;
}
}
return false;
}
static bool checkAuthorizations(BzMaterialManager::TextureSet& set)
{
// avoid the DNS lookup
if (DownloadAccessList.alwaysAuthorized()) {
return false;
}
bool hostFailed = false;
BzMaterialManager::TextureSet::iterator set_it;
std::map<std::string, bool> hostAccess;
std::map<std::string, bool>::iterator host_it;
// get the list of hosts to check
for (set_it = set.begin(); set_it != set.end(); set_it++) {
const std::string& url = *set_it;
std::string hostname;
if (parseHostname(url, hostname)) {
hostAccess[hostname] = true;
}
}
// check the hosts
for (host_it = hostAccess.begin(); host_it != hostAccess.end(); host_it++) {
const std::string& host = host_it->first;
host_it->second = authorizedServer(host);
}
// clear any unauthorized urls
set_it = set.begin();
while (set_it != set.end()) {
BzMaterialManager::TextureSet::iterator next_it = set_it;
next_it++;
const std::string& url = *set_it;
std::string hostname;
if (parseHostname(url, hostname) && !hostAccess[hostname]) {
hostFailed = true;
// send a message
std::string msg = ColorStrings[RedColor];
msg += "local denial: ";
msg += ColorStrings[GreyColor];
msg += url;
addMessage(NULL, msg);
// remove the url
MATERIALMGR.setTextureLocal(url, "");
set.erase(set_it);
}
set_it = next_it;
}
return hostFailed;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2013 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.
//-----------------------------------------------------------------------------
#ifndef _ASSET_BASE_H_
#include "assetBase.h"
#endif
#ifndef _ASSET_MANAGER_H_
#include "assetManager.h"
#endif
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
// Script bindings.
#include "assetBase_ScriptBinding.h"
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT(AssetBase);
//-----------------------------------------------------------------------------
StringTableEntry assetNameField = StringTable->insert("AssetName");
StringTableEntry assetDescriptionField = StringTable->insert("AssetDescription");
StringTableEntry assetCategoryField = StringTable->insert("AssetCategory");
StringTableEntry assetAutoUnloadField = StringTable->insert("AssetAutoUnload");
StringTableEntry assetInternalField = StringTable->insert("AssetInternal");
StringTableEntry assetPrivateField = StringTable->insert("AssetPrivate");
//-----------------------------------------------------------------------------
const String AssetBase::mErrCodeStrings[] =
{
"Failed",
"Ok",
"NotLoaded",
"BadFileReference",
"InvalidFormat",
"DependencyNotFound",
"FileTooLarge",
"UsingFallback",
"UnKnown"
};
AssetBase::AssetBase() :
mpOwningAssetManager(NULL),
mAcquireReferenceCount(0),
mAssetInitialized(false)
{
// Generate an asset definition.
mpAssetDefinition = new AssetDefinition();
mInternalName = StringTable->EmptyString();
mClassName = StringTable->EmptyString();
mSuperClassName = StringTable->EmptyString();
}
//-----------------------------------------------------------------------------
AssetBase::~AssetBase()
{
// If the asset manager does not own the asset then we own the
// asset definition so delete it.
if (!getOwned())
SAFE_DELETE(mpAssetDefinition);
}
//-----------------------------------------------------------------------------
void AssetBase::initPersistFields()
{
// Call parent.
Parent::initPersistFields();
// Asset configuration.
addProtectedField(assetNameField, TypeString, 0, &setAssetName, &getAssetName, &writeAssetName, "The name of the asset. The is not a unique identification like an asset Id.");
addProtectedField(assetDescriptionField, TypeString, 0, &setAssetDescription, &getAssetDescription, &writeAssetDescription, "The simple description of the asset contents.");
addProtectedField(assetCategoryField, TypeString, 0, &setAssetCategory, &getAssetCategory, &writeAssetCategory, "An arbitrary category that can be used to categorized assets.");
addProtectedField(assetAutoUnloadField, TypeBool, 0, &setAssetAutoUnload, &getAssetAutoUnload, &writeAssetAutoUnload, "Whether the asset is automatically unloaded when an asset is released and has no other acquisitions or not.");
addProtectedField(assetInternalField, TypeBool, 0, &setAssetInternal, &getAssetInternal, &writeAssetInternal, "Whether the asset is used internally only or not.");
addProtectedField(assetPrivateField, TypeBool, 0, &defaultProtectedNotSetFn, &getAssetPrivate, &defaultProtectedNotWriteFn, "Whether the asset is private or not.");
}
//------------------------------------------------------------------------------
void AssetBase::copyTo(SimObject* object)
{
// Call to parent.
Parent::copyTo(object);
// Cast to asset.
AssetBase* pAsset = static_cast<AssetBase*>(object);
// Sanity!
AssertFatal(pAsset != NULL, "AssetBase::copyTo() - Object is not the correct type.");
// Copy state.
pAsset->setAssetName(getAssetName());
pAsset->setAssetDescription(getAssetDescription());
pAsset->setAssetCategory(getAssetCategory());
pAsset->setAssetAutoUnload(getAssetAutoUnload());
pAsset->setAssetInternal(getAssetInternal());
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetDescription(const char* pAssetDescription)
{
// Fetch asset description.
StringTableEntry assetDescription = StringTable->insert(pAssetDescription);
// Ignore no change.
if (mpAssetDefinition->mAssetDescription == assetDescription)
return;
// Update.
mpAssetDefinition->mAssetDescription = assetDescription;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetCategory(const char* pAssetCategory)
{
// Fetch asset category.
StringTableEntry assetCategory = StringTable->insert(pAssetCategory);
// Ignore no change.
if (mpAssetDefinition->mAssetCategory == assetCategory)
return;
// Update.
mpAssetDefinition->mAssetCategory = assetCategory;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetAutoUnload(const bool autoUnload)
{
// Ignore no change.
if (mpAssetDefinition->mAssetAutoUnload == autoUnload)
return;
// Update.
mpAssetDefinition->mAssetAutoUnload = autoUnload;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetInternal(const bool assetInternal)
{
// Ignore no change,
if (mpAssetDefinition->mAssetInternal == assetInternal)
return;
// Update.
mpAssetDefinition->mAssetInternal = assetInternal;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
StringTableEntry AssetBase::expandAssetFilePath(const char* pAssetFilePath) const
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_ExpandAssetFilePath);
// Sanity!
AssertFatal(pAssetFilePath != NULL, "Cannot expand a NULL asset path.");
// Fetch asset file-path length.
const U32 assetFilePathLength = dStrlen(pAssetFilePath);
// Are there any characters in the path?
if (assetFilePathLength == 0)
{
// No, so return empty.
return StringTable->EmptyString();
}
// Fetch the asset base-path hint.
StringTableEntry assetBasePathHint;
if (getOwned() && !getAssetPrivate())
{
assetBasePathHint = mpOwningAssetManager->getAssetPath(getAssetId());
}
else
{
assetBasePathHint = NULL;
}
// Expand the path with the asset base-path hint.
char assetFilePathBuffer[1024];
Con::expandPath(assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetFilePath, assetBasePathHint);
return StringTable->insert(assetFilePathBuffer);
}
//-----------------------------------------------------------------------------
StringTableEntry AssetBase::collapseAssetFilePath(const char* pAssetFilePath) const
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_CollapseAssetFilePath);
// Sanity!
AssertFatal(pAssetFilePath != NULL, "Cannot collapse a NULL asset path.");
// Fetch asset file-path length.
const U32 assetFilePathLength = dStrlen(pAssetFilePath);
// Are there any characters in the path?
if (assetFilePathLength == 0)
{
// No, so return empty.
return StringTable->EmptyString();
}
char assetFilePathBuffer[1024];
// Is the asset not owned or private?
if (!getOwned() || getAssetPrivate())
{
// Yes, so we can only collapse the path using the platform layer.
Con::collapsePath(assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetFilePath);
return StringTable->insert(assetFilePathBuffer);
}
// Fetch asset base-path.
StringTableEntry assetBasePath = mpOwningAssetManager->getAssetPath(getAssetId());
// Is the asset file-path location within the asset base-path?
if (Con::isBasePath(pAssetFilePath, assetBasePath))
{
// Yes, so fetch path relative to the asset base-path.
StringTableEntry relativePath = Platform::makeRelativePathName(pAssetFilePath, assetBasePath);
// Format the collapsed path.
dSprintf(assetFilePathBuffer, sizeof(assetFilePathBuffer), "%s", relativePath);
}
else
{
// No, so we can collapse the path using the platform layer.
Con::collapsePath(assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetFilePath);
}
return StringTable->insert(assetFilePathBuffer);
}
//-----------------------------------------------------------------------------
void AssetBase::refreshAsset(void)
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_RefreshAsset);
// Finish if asset is not owned or is not initialized.
if (mpOwningAssetManager == NULL || !mAssetInitialized)
return;
// Yes, so refresh the asset via the asset manager.
mpOwningAssetManager->refreshAsset(getAssetId());
}
//-----------------------------------------------------------------------------
S32 AssetBase::getAssetDependencyFieldCount(const char* pFieldName)
{
S32 matchedFieldCount = 0;
SimFieldDictionary* fieldDictionary = getFieldDictionary();
for (SimFieldDictionaryIterator itr(fieldDictionary); *itr; ++itr)
{
SimFieldDictionary::Entry* entry = *itr;
if (String(entry->slotName).startsWith(pFieldName))
{
matchedFieldCount++;
}
}
return matchedFieldCount;
}
//-----------------------------------------------------------------------------
StringTableEntry AssetBase::getAssetDependencyField(const char* pFieldName, S32 index)
{
SimFieldDictionary* fieldDictionary = getFieldDictionary();
for (SimFieldDictionaryIterator itr(fieldDictionary); *itr; ++itr)
{
SimFieldDictionary::Entry* entry = *itr;
String slotName = String(entry->slotName);
if (slotName.startsWith(pFieldName))
{
S32 trailingNum;
String::GetTrailingNumber(slotName.c_str(), trailingNum);
if (trailingNum == index)
{
return StringTable->insert(String(entry->value).replace(ASSET_ID_FIELD_PREFIX, "").c_str());
}
}
}
return StringTable->EmptyString();
}
//-----------------------------------------------------------------------------
void AssetBase::clearAssetDependencyFields(const char* pFieldName)
{
SimFieldDictionary* fieldDictionary = getFieldDictionary();
for (SimFieldDictionaryIterator itr(fieldDictionary); *itr; ++itr)
{
SimFieldDictionary::Entry* entry = *itr;
if (String(entry->slotName).startsWith(pFieldName))
{
setDataField(entry->slotName, NULL, "");
}
}
}
//-----------------------------------------------------------------------------
void AssetBase::addAssetDependencyField(const char* pFieldName, const char* pAssetId)
{
U32 existingFieldCount = getAssetDependencyFieldCount(pFieldName);
//we have a match!
char depSlotName[50];
dSprintf(depSlotName, sizeof(depSlotName), "%s%d", pFieldName, existingFieldCount);
char depValue[255];
dSprintf(depValue, sizeof(depValue), "%s=%s", ASSET_ID_SIGNATURE, pAssetId);
setDataField(StringTable->insert(depSlotName), NULL, StringTable->insert(depValue));
}
//-----------------------------------------------------------------------------
bool AssetBase::saveAsset()
{
// Set the format mode.
Taml taml;
// Yes, so set it.
taml.setFormatMode(Taml::getFormatModeEnum("xml"));
// Turn-off auto-formatting.
taml.setAutoFormat(false);
// Read object.
bool success = taml.write(this, AssetDatabase.getAssetFilePath(getAssetId()));
if (!success)
return false;
return true;
}
//-----------------------------------------------------------------------------
void AssetBase::acquireAssetReference(void)
{
// Acquired the acquired reference count.
if (mpOwningAssetManager != NULL)
mpOwningAssetManager->acquireAcquiredReferenceCount();
mAcquireReferenceCount++;
}
//-----------------------------------------------------------------------------
bool AssetBase::releaseAssetReference(void)
{
// Are there any acquisition references?
if (mAcquireReferenceCount == 0)
{
// Return "unload" unless auto unload is off.
return mpAssetDefinition->mAssetAutoUnload;
}
// Release the acquired reference count.
if (mpOwningAssetManager != NULL)
mpOwningAssetManager->releaseAcquiredReferenceCount();
// Release reference.
mAcquireReferenceCount--;
// Are there any acquisition references?
if (mAcquireReferenceCount == 0)
{
// No, so return "unload" unless auto unload is off.
return mpAssetDefinition->mAssetAutoUnload;
}
// Return "don't unload".
return false;
}
//-----------------------------------------------------------------------------
void AssetBase::setOwned(AssetManager* pAssetManager, AssetDefinition* pAssetDefinition)
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_setOwned);
// Sanity!
AssertFatal(pAssetManager != NULL, "Cannot set asset ownership with NULL asset manager.");
AssertFatal(mpOwningAssetManager == NULL, "Cannot set asset ownership if it is already owned.");
AssertFatal(pAssetDefinition != NULL, "Cannot set asset ownership with a NULL asset definition.");
AssertFatal(mpAssetDefinition != NULL, "Asset ownership assigned but has a NULL asset definition.");
AssertFatal(mpAssetDefinition->mAssetName == pAssetDefinition->mAssetName, "Asset ownership differs by asset name.");
AssertFatal(mpAssetDefinition->mAssetDescription == pAssetDefinition->mAssetDescription, "Asset ownership differs by asset description.");
AssertFatal(mpAssetDefinition->mAssetCategory == pAssetDefinition->mAssetCategory, "Asset ownership differs by asset category.");
AssertFatal(mpAssetDefinition->mAssetAutoUnload == pAssetDefinition->mAssetAutoUnload, "Asset ownership differs by asset auto-unload flag.");
AssertFatal(mpAssetDefinition->mAssetInternal == pAssetDefinition->mAssetInternal, "Asset ownership differs by asset internal flag.");
// Transfer asset definition ownership state.
delete mpAssetDefinition;
mpAssetDefinition = pAssetDefinition;
// Flag as owned.
// NOTE: This must be done prior to initializing the asset so any initialization can assume ownership.
mpOwningAssetManager = pAssetManager;
// Initialize the asset.
initializeAsset();
// Flag asset as initialized.
mAssetInitialized = true;
}
<commit_msg>set initial asset loaded state to not loaded<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2013 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.
//-----------------------------------------------------------------------------
#ifndef _ASSET_BASE_H_
#include "assetBase.h"
#endif
#ifndef _ASSET_MANAGER_H_
#include "assetManager.h"
#endif
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
// Script bindings.
#include "assetBase_ScriptBinding.h"
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT(AssetBase);
//-----------------------------------------------------------------------------
StringTableEntry assetNameField = StringTable->insert("AssetName");
StringTableEntry assetDescriptionField = StringTable->insert("AssetDescription");
StringTableEntry assetCategoryField = StringTable->insert("AssetCategory");
StringTableEntry assetAutoUnloadField = StringTable->insert("AssetAutoUnload");
StringTableEntry assetInternalField = StringTable->insert("AssetInternal");
StringTableEntry assetPrivateField = StringTable->insert("AssetPrivate");
//-----------------------------------------------------------------------------
const String AssetBase::mErrCodeStrings[] =
{
"Failed",
"Ok",
"NotLoaded",
"BadFileReference",
"InvalidFormat",
"DependencyNotFound",
"FileTooLarge",
"UsingFallback",
"UnKnown"
};
AssetBase::AssetBase() :
mpOwningAssetManager(NULL),
mAcquireReferenceCount(0),
mAssetInitialized(false)
{
// Generate an asset definition.
mpAssetDefinition = new AssetDefinition();
mInternalName = StringTable->EmptyString();
mClassName = StringTable->EmptyString();
mSuperClassName = StringTable->EmptyString();
mLoadedState = AssetErrCode::NotLoaded;
}
//-----------------------------------------------------------------------------
AssetBase::~AssetBase()
{
// If the asset manager does not own the asset then we own the
// asset definition so delete it.
if (!getOwned())
SAFE_DELETE(mpAssetDefinition);
}
//-----------------------------------------------------------------------------
void AssetBase::initPersistFields()
{
// Call parent.
Parent::initPersistFields();
// Asset configuration.
addProtectedField(assetNameField, TypeString, 0, &setAssetName, &getAssetName, &writeAssetName, "The name of the asset. The is not a unique identification like an asset Id.");
addProtectedField(assetDescriptionField, TypeString, 0, &setAssetDescription, &getAssetDescription, &writeAssetDescription, "The simple description of the asset contents.");
addProtectedField(assetCategoryField, TypeString, 0, &setAssetCategory, &getAssetCategory, &writeAssetCategory, "An arbitrary category that can be used to categorized assets.");
addProtectedField(assetAutoUnloadField, TypeBool, 0, &setAssetAutoUnload, &getAssetAutoUnload, &writeAssetAutoUnload, "Whether the asset is automatically unloaded when an asset is released and has no other acquisitions or not.");
addProtectedField(assetInternalField, TypeBool, 0, &setAssetInternal, &getAssetInternal, &writeAssetInternal, "Whether the asset is used internally only or not.");
addProtectedField(assetPrivateField, TypeBool, 0, &defaultProtectedNotSetFn, &getAssetPrivate, &defaultProtectedNotWriteFn, "Whether the asset is private or not.");
}
//------------------------------------------------------------------------------
void AssetBase::copyTo(SimObject* object)
{
// Call to parent.
Parent::copyTo(object);
// Cast to asset.
AssetBase* pAsset = static_cast<AssetBase*>(object);
// Sanity!
AssertFatal(pAsset != NULL, "AssetBase::copyTo() - Object is not the correct type.");
// Copy state.
pAsset->setAssetName(getAssetName());
pAsset->setAssetDescription(getAssetDescription());
pAsset->setAssetCategory(getAssetCategory());
pAsset->setAssetAutoUnload(getAssetAutoUnload());
pAsset->setAssetInternal(getAssetInternal());
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetDescription(const char* pAssetDescription)
{
// Fetch asset description.
StringTableEntry assetDescription = StringTable->insert(pAssetDescription);
// Ignore no change.
if (mpAssetDefinition->mAssetDescription == assetDescription)
return;
// Update.
mpAssetDefinition->mAssetDescription = assetDescription;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetCategory(const char* pAssetCategory)
{
// Fetch asset category.
StringTableEntry assetCategory = StringTable->insert(pAssetCategory);
// Ignore no change.
if (mpAssetDefinition->mAssetCategory == assetCategory)
return;
// Update.
mpAssetDefinition->mAssetCategory = assetCategory;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetAutoUnload(const bool autoUnload)
{
// Ignore no change.
if (mpAssetDefinition->mAssetAutoUnload == autoUnload)
return;
// Update.
mpAssetDefinition->mAssetAutoUnload = autoUnload;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetInternal(const bool assetInternal)
{
// Ignore no change,
if (mpAssetDefinition->mAssetInternal == assetInternal)
return;
// Update.
mpAssetDefinition->mAssetInternal = assetInternal;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
StringTableEntry AssetBase::expandAssetFilePath(const char* pAssetFilePath) const
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_ExpandAssetFilePath);
// Sanity!
AssertFatal(pAssetFilePath != NULL, "Cannot expand a NULL asset path.");
// Fetch asset file-path length.
const U32 assetFilePathLength = dStrlen(pAssetFilePath);
// Are there any characters in the path?
if (assetFilePathLength == 0)
{
// No, so return empty.
return StringTable->EmptyString();
}
// Fetch the asset base-path hint.
StringTableEntry assetBasePathHint;
if (getOwned() && !getAssetPrivate())
{
assetBasePathHint = mpOwningAssetManager->getAssetPath(getAssetId());
}
else
{
assetBasePathHint = NULL;
}
// Expand the path with the asset base-path hint.
char assetFilePathBuffer[1024];
Con::expandPath(assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetFilePath, assetBasePathHint);
return StringTable->insert(assetFilePathBuffer);
}
//-----------------------------------------------------------------------------
StringTableEntry AssetBase::collapseAssetFilePath(const char* pAssetFilePath) const
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_CollapseAssetFilePath);
// Sanity!
AssertFatal(pAssetFilePath != NULL, "Cannot collapse a NULL asset path.");
// Fetch asset file-path length.
const U32 assetFilePathLength = dStrlen(pAssetFilePath);
// Are there any characters in the path?
if (assetFilePathLength == 0)
{
// No, so return empty.
return StringTable->EmptyString();
}
char assetFilePathBuffer[1024];
// Is the asset not owned or private?
if (!getOwned() || getAssetPrivate())
{
// Yes, so we can only collapse the path using the platform layer.
Con::collapsePath(assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetFilePath);
return StringTable->insert(assetFilePathBuffer);
}
// Fetch asset base-path.
StringTableEntry assetBasePath = mpOwningAssetManager->getAssetPath(getAssetId());
// Is the asset file-path location within the asset base-path?
if (Con::isBasePath(pAssetFilePath, assetBasePath))
{
// Yes, so fetch path relative to the asset base-path.
StringTableEntry relativePath = Platform::makeRelativePathName(pAssetFilePath, assetBasePath);
// Format the collapsed path.
dSprintf(assetFilePathBuffer, sizeof(assetFilePathBuffer), "%s", relativePath);
}
else
{
// No, so we can collapse the path using the platform layer.
Con::collapsePath(assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetFilePath);
}
return StringTable->insert(assetFilePathBuffer);
}
//-----------------------------------------------------------------------------
void AssetBase::refreshAsset(void)
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_RefreshAsset);
// Finish if asset is not owned or is not initialized.
if (mpOwningAssetManager == NULL || !mAssetInitialized)
return;
// Yes, so refresh the asset via the asset manager.
mpOwningAssetManager->refreshAsset(getAssetId());
}
//-----------------------------------------------------------------------------
S32 AssetBase::getAssetDependencyFieldCount(const char* pFieldName)
{
S32 matchedFieldCount = 0;
SimFieldDictionary* fieldDictionary = getFieldDictionary();
for (SimFieldDictionaryIterator itr(fieldDictionary); *itr; ++itr)
{
SimFieldDictionary::Entry* entry = *itr;
if (String(entry->slotName).startsWith(pFieldName))
{
matchedFieldCount++;
}
}
return matchedFieldCount;
}
//-----------------------------------------------------------------------------
StringTableEntry AssetBase::getAssetDependencyField(const char* pFieldName, S32 index)
{
SimFieldDictionary* fieldDictionary = getFieldDictionary();
for (SimFieldDictionaryIterator itr(fieldDictionary); *itr; ++itr)
{
SimFieldDictionary::Entry* entry = *itr;
String slotName = String(entry->slotName);
if (slotName.startsWith(pFieldName))
{
S32 trailingNum;
String::GetTrailingNumber(slotName.c_str(), trailingNum);
if (trailingNum == index)
{
return StringTable->insert(String(entry->value).replace(ASSET_ID_FIELD_PREFIX, "").c_str());
}
}
}
return StringTable->EmptyString();
}
//-----------------------------------------------------------------------------
void AssetBase::clearAssetDependencyFields(const char* pFieldName)
{
SimFieldDictionary* fieldDictionary = getFieldDictionary();
for (SimFieldDictionaryIterator itr(fieldDictionary); *itr; ++itr)
{
SimFieldDictionary::Entry* entry = *itr;
if (String(entry->slotName).startsWith(pFieldName))
{
setDataField(entry->slotName, NULL, "");
}
}
}
//-----------------------------------------------------------------------------
void AssetBase::addAssetDependencyField(const char* pFieldName, const char* pAssetId)
{
U32 existingFieldCount = getAssetDependencyFieldCount(pFieldName);
//we have a match!
char depSlotName[50];
dSprintf(depSlotName, sizeof(depSlotName), "%s%d", pFieldName, existingFieldCount);
char depValue[255];
dSprintf(depValue, sizeof(depValue), "%s=%s", ASSET_ID_SIGNATURE, pAssetId);
setDataField(StringTable->insert(depSlotName), NULL, StringTable->insert(depValue));
}
//-----------------------------------------------------------------------------
bool AssetBase::saveAsset()
{
// Set the format mode.
Taml taml;
// Yes, so set it.
taml.setFormatMode(Taml::getFormatModeEnum("xml"));
// Turn-off auto-formatting.
taml.setAutoFormat(false);
// Read object.
bool success = taml.write(this, AssetDatabase.getAssetFilePath(getAssetId()));
if (!success)
return false;
return true;
}
//-----------------------------------------------------------------------------
void AssetBase::acquireAssetReference(void)
{
// Acquired the acquired reference count.
if (mpOwningAssetManager != NULL)
mpOwningAssetManager->acquireAcquiredReferenceCount();
mAcquireReferenceCount++;
}
//-----------------------------------------------------------------------------
bool AssetBase::releaseAssetReference(void)
{
// Are there any acquisition references?
if (mAcquireReferenceCount == 0)
{
// Return "unload" unless auto unload is off.
return mpAssetDefinition->mAssetAutoUnload;
}
// Release the acquired reference count.
if (mpOwningAssetManager != NULL)
mpOwningAssetManager->releaseAcquiredReferenceCount();
// Release reference.
mAcquireReferenceCount--;
// Are there any acquisition references?
if (mAcquireReferenceCount == 0)
{
// No, so return "unload" unless auto unload is off.
return mpAssetDefinition->mAssetAutoUnload;
}
// Return "don't unload".
return false;
}
//-----------------------------------------------------------------------------
void AssetBase::setOwned(AssetManager* pAssetManager, AssetDefinition* pAssetDefinition)
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_setOwned);
// Sanity!
AssertFatal(pAssetManager != NULL, "Cannot set asset ownership with NULL asset manager.");
AssertFatal(mpOwningAssetManager == NULL, "Cannot set asset ownership if it is already owned.");
AssertFatal(pAssetDefinition != NULL, "Cannot set asset ownership with a NULL asset definition.");
AssertFatal(mpAssetDefinition != NULL, "Asset ownership assigned but has a NULL asset definition.");
AssertFatal(mpAssetDefinition->mAssetName == pAssetDefinition->mAssetName, "Asset ownership differs by asset name.");
AssertFatal(mpAssetDefinition->mAssetDescription == pAssetDefinition->mAssetDescription, "Asset ownership differs by asset description.");
AssertFatal(mpAssetDefinition->mAssetCategory == pAssetDefinition->mAssetCategory, "Asset ownership differs by asset category.");
AssertFatal(mpAssetDefinition->mAssetAutoUnload == pAssetDefinition->mAssetAutoUnload, "Asset ownership differs by asset auto-unload flag.");
AssertFatal(mpAssetDefinition->mAssetInternal == pAssetDefinition->mAssetInternal, "Asset ownership differs by asset internal flag.");
// Transfer asset definition ownership state.
delete mpAssetDefinition;
mpAssetDefinition = pAssetDefinition;
// Flag as owned.
// NOTE: This must be done prior to initializing the asset so any initialization can assume ownership.
mpOwningAssetManager = pAssetManager;
// Initialize the asset.
initializeAsset();
// Flag asset as initialized.
mAssetInitialized = true;
}
<|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.
*
* $Id$
*
*/
#include <pcl/pcl_config.h>
#ifdef HAVE_QHULL
#ifndef PCL_SURFACE_IMPL_CONVEX_HULL_H_
#define PCL_SURFACE_IMPL_CONVEX_HULL_H_
#include "pcl/surface/convex_hull.h"
#include <pcl/common/common.h>
#include <pcl/common/eigen.h>
#include <pcl/common/transforms.h>
#include <pcl/common/io.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <stdio.h>
#include <stdlib.h>
extern "C"
{
#ifdef HAVE_QHULL_2011
# include "libqhull/libqhull.h"
# include "libqhull/mem.h"
# include "libqhull/qset.h"
# include "libqhull/geom.h"
# include "libqhull/merge.h"
# include "libqhull/poly.h"
# include "libqhull/io.h"
# include "libqhull/stat.h"
#else
# include "qhull/qhull.h"
# include "qhull/mem.h"
# include "qhull/qset.h"
# include "qhull/geom.h"
# include "qhull/merge.h"
# include "qhull/poly.h"
# include "qhull/io.h"
# include "qhull/stat.h"
#endif
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::performReconstruction (PointCloud &hull, std::vector<pcl::Vertices> &polygons,
bool fill_polygon_data)
{
// FInd the principal directions
EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix;
Eigen::Vector4f xyz_centroid;
compute3DCentroid (*input_, *indices_, xyz_centroid);
computeCovarianceMatrix (*input_, *indices_, xyz_centroid, covariance_matrix);
EIGEN_ALIGN16 Eigen::Vector3f eigen_values;
EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors;
pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values);
Eigen::Affine3f transform1;
transform1.setIdentity ();
int dim = 3;
if (eigen_values[0] / eigen_values[2] < 1.0e-5)
{
// We have points laying on a plane, using 2d convex hull
// Compute transformation bring eigen_vectors.col(i) to z-axis
eigen_vectors.col (2) = eigen_vectors.col (0).cross (eigen_vectors.col (1));
eigen_vectors.col (1) = eigen_vectors.col (2).cross (eigen_vectors.col (0));
transform1 (0, 2) = eigen_vectors (0, 0);
transform1 (1, 2) = eigen_vectors (1, 0);
transform1 (2, 2) = eigen_vectors (2, 0);
transform1 (0, 1) = eigen_vectors (0, 1);
transform1 (1, 1) = eigen_vectors (1, 1);
transform1 (2, 1) = eigen_vectors (2, 1);
transform1 (0, 0) = eigen_vectors (0, 2);
transform1 (1, 0) = eigen_vectors (1, 2);
transform1 (2, 0) = eigen_vectors (2, 2);
transform1 = transform1.inverse ();
dim = 2;
}
else
transform1.setIdentity ();
dim_ = dim;
PointCloud cloud_transformed;
pcl::demeanPointCloud (*input_, *indices_, xyz_centroid, cloud_transformed);
pcl::transformPointCloud (cloud_transformed, cloud_transformed, transform1);
// True if qhull should free points in qh_freeqhull() or reallocation
boolT ismalloc = True;
// output from qh_produce_output(), use NULL to skip qh_produce_output()
FILE *outfile = NULL;
std::string flags_str;
flags_str = "qhull Tc";
if (compute_area_)
{
flags_str.append (" FA");
outfile = stderr;
}
// option flags for qhull, see qh_opt.htm
//char flags[] = "qhull Tc FA";
char * flags = (char *)flags_str.c_str();
// error messages from qhull code
FILE *errfile = stderr;
// 0 if no error from qhull
int exitcode;
// Array of coordinates for each point
coordT *points = (coordT *)calloc (cloud_transformed.points.size () * dim, sizeof(coordT));
for (size_t i = 0; i < cloud_transformed.points.size (); ++i)
{
points[i * dim + 0] = (coordT)cloud_transformed.points[i].x;
points[i * dim + 1] = (coordT)cloud_transformed.points[i].y;
if (dim > 2)
points[i * dim + 2] = (coordT)cloud_transformed.points[i].z;
}
// Compute convex hull
exitcode = qh_new_qhull (dim, cloud_transformed.points.size (), points, ismalloc, flags, outfile, errfile);
if (exitcode != 0)
{
PCL_ERROR ("[pcl::%s::performReconstrution] ERROR: qhull was unable to compute a convex hull for the given point cloud (%lu)!\n", getClassName ().c_str (), (unsigned long) input_->points.size ());
//check if it fails because of NaN values...
if (!cloud_transformed.is_dense)
{
bool NaNvalues = false;
for (size_t i = 0; i < cloud_transformed.size (); ++i)
{
if (!pcl_isfinite (cloud_transformed.points[i].x) ||
!pcl_isfinite (cloud_transformed.points[i].y) ||
!pcl_isfinite (cloud_transformed.points[i].z))
{
NaNvalues = true;
break;
}
}
if (NaNvalues)
PCL_ERROR ("[pcl::%s::performReconstruction] ERROR: point cloud contains NaN values, consider running pcl::PassThrough filter first to remove NaNs!\n", getClassName ().c_str ());
}
hull.points.resize (0);
hull.width = hull.height = 0;
polygons.resize (0);
qh_freeqhull (!qh_ALL);
int curlong, totlong;
qh_memfreeshort (&curlong, &totlong);
return;
}
qh_triangulate ();
int num_facets = qh num_facets;
int num_vertices = qh num_vertices;
hull.points.resize (num_vertices);
vertexT * vertex;
int i = 0;
// Max vertex id
int max_vertex_id = -1;
FORALLvertices
{
if ((int)vertex->id > max_vertex_id)
max_vertex_id = vertex->id;
}
++max_vertex_id;
std::vector<int> qhid_to_pcidx (max_vertex_id);
FORALLvertices
{
// Add vertices to hull point_cloud
hull.points[i].x = vertex->point[0];
hull.points[i].y = vertex->point[1];
if (dim>2)
hull.points[i].z = vertex->point[2];
else
hull.points[i].z = 0;
qhid_to_pcidx[vertex->id] = i; // map the vertex id of qhull to the point cloud index
++i;
}
if (compute_area_)
{
total_area_ = qh totarea;
total_volume_ = qh totvol;
}
if (fill_polygon_data)
{
if (dim == 3)
{
polygons.resize (num_facets);
int dd = 0;
facetT * facet;
FORALLfacets
{
polygons[dd].vertices.resize (3);
// Needed by FOREACHvertex_i_
int vertex_n, vertex_i;
FOREACHvertex_i_((*facet).vertices)
//facet_vertices.vertices.push_back (qhid_to_pcidx[vertex->id]);
polygons[dd].vertices[vertex_i] = qhid_to_pcidx[vertex->id];
++dd;
}
}
else
{
// dim=2, we want to return just a polygon with all vertices sorted
// so that they form a non-intersecting polygon...
// this can be moved to the upper loop probably and here just
// the sorting + populate
Eigen::Vector4f centroid;
pcl::compute3DCentroid (hull, centroid);
centroid[3] = 0;
polygons.resize (1);
int num_vertices = qh num_vertices, dd = 0;
// Copy all vertices
std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices);
FORALLvertices
{
idx_points[dd].first = qhid_to_pcidx[vertex->id];
idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid;
++dd;
}
// Sort idx_points
std::sort (idx_points.begin (), idx_points.end (), comparePoints2D);
polygons[0].vertices.resize (idx_points.size () + 1);
//Sort also points...
PointCloud hull_sorted;
hull_sorted.points.resize (hull.points.size ());
for (size_t j = 0; j < idx_points.size (); ++j)
hull_sorted.points[j] = hull.points[idx_points[j].first];
hull.points = hull_sorted.points;
// Populate points
for (size_t j = 0; j < idx_points.size (); ++j)
polygons[0].vertices[j] = j;
polygons[0].vertices[idx_points.size ()] = 0;
}
}
else
{
if (dim == 2)
{
// We want to sort the points
Eigen::Vector4f centroid;
pcl::compute3DCentroid (hull, centroid);
centroid[3] = 0;
polygons.resize (1);
int num_vertices = qh num_vertices, dd = 0;
// Copy all vertices
std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices);
FORALLvertices
{
idx_points[dd].first = qhid_to_pcidx[vertex->id];
idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid;
++dd;
}
// Sort idx_points
std::sort (idx_points.begin (), idx_points.end (), comparePoints2D);
//Sort also points...
PointCloud hull_sorted;
hull_sorted.points.resize (hull.points.size ());
for (size_t j = 0; j < idx_points.size (); ++j)
hull_sorted.points[j] = hull.points[idx_points[j].first];
hull.points = hull_sorted.points;
}
}
// Deallocates memory (also the points)
qh_freeqhull(!qh_ALL);
int curlong, totlong;
qh_memfreeshort (&curlong, &totlong);
// Rotate the hull point cloud by transform's inverse
// If the input point cloud has been rotated
if (dim == 2)
{
Eigen::Affine3f transInverse = transform1.inverse ();
pcl::transformPointCloud (hull, hull, transInverse);
//for 2D sets, the qhull library delivers the actual area of the 2d hull in the volume
if(compute_area_)
{
total_area_ = total_volume_;
total_volume_ = 0.0;
}
}
xyz_centroid[0] = -xyz_centroid[0];
xyz_centroid[1] = -xyz_centroid[1];
xyz_centroid[2] = -xyz_centroid[2];
pcl::demeanPointCloud (hull, xyz_centroid, hull);
//if keep_information_
if (keep_information_)
{
//build a tree with the original points
pcl::KdTreeFLANN<PointInT> tree (true);
tree.setInputCloud (input_, indices_);
std::vector<int> neighbor;
std::vector<float> distances;
neighbor.resize (1);
distances.resize (1);
//for each point in the convex hull, search for the nearest neighbor
std::vector<int> indices;
indices.resize (hull.points.size ());
for (size_t i = 0; i < hull.points.size (); i++)
{
tree.nearestKSearch (hull.points[i], 1, neighbor, distances);
indices[i] = (*indices_)[neighbor[0]];
}
//replace point with the closest neighbor in the original point cloud
pcl::copyPointCloud (*input_, indices, hull);
}
hull.width = hull.points.size ();
hull.height = 1;
hull.is_dense = false;
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::reconstruct (PointCloud &output)
{
output.header = input_->header;
if (!initCompute ())
{
output.points.clear ();
return;
}
// Perform the actual surface reconstruction
std::vector<pcl::Vertices> polygons;
performReconstruction (output, polygons, false);
output.width = output.points.size ();
output.height = 1;
output.is_dense = true;
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::reconstruct (PointCloud &points, std::vector<pcl::Vertices> &polygons)
{
points.header = input_->header;
if (!initCompute ())
{
points.points.clear ();
return;
}
// Perform the actual surface reconstruction
performReconstruction (points, polygons, true);
points.width = points.points.size ();
points.height = 1;
points.is_dense = true;
deinitCompute ();
}
#define PCL_INSTANTIATE_ConvexHull(T) template class PCL_EXPORTS pcl::ConvexHull<T>;
#endif // PCL_SURFACE_IMPL_CONVEX_HULL_H_
#endif
<commit_msg>do not do any processing if the input point cloud is empty<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.
*
* $Id$
*
*/
#include <pcl/pcl_config.h>
#ifdef HAVE_QHULL
#ifndef PCL_SURFACE_IMPL_CONVEX_HULL_H_
#define PCL_SURFACE_IMPL_CONVEX_HULL_H_
#include "pcl/surface/convex_hull.h"
#include <pcl/common/common.h>
#include <pcl/common/eigen.h>
#include <pcl/common/transforms.h>
#include <pcl/common/io.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <stdio.h>
#include <stdlib.h>
extern "C"
{
#ifdef HAVE_QHULL_2011
# include "libqhull/libqhull.h"
# include "libqhull/mem.h"
# include "libqhull/qset.h"
# include "libqhull/geom.h"
# include "libqhull/merge.h"
# include "libqhull/poly.h"
# include "libqhull/io.h"
# include "libqhull/stat.h"
#else
# include "qhull/qhull.h"
# include "qhull/mem.h"
# include "qhull/qset.h"
# include "qhull/geom.h"
# include "qhull/merge.h"
# include "qhull/poly.h"
# include "qhull/io.h"
# include "qhull/stat.h"
#endif
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::performReconstruction (PointCloud &hull, std::vector<pcl::Vertices> &polygons,
bool fill_polygon_data)
{
// FInd the principal directions
EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix;
Eigen::Vector4f xyz_centroid;
compute3DCentroid (*input_, *indices_, xyz_centroid);
computeCovarianceMatrix (*input_, *indices_, xyz_centroid, covariance_matrix);
EIGEN_ALIGN16 Eigen::Vector3f eigen_values;
EIGEN_ALIGN16 Eigen::Matrix3f eigen_vectors;
pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values);
Eigen::Affine3f transform1;
transform1.setIdentity ();
int dim = 3;
if (eigen_values[0] / eigen_values[2] < 1.0e-5)
{
// We have points laying on a plane, using 2d convex hull
// Compute transformation bring eigen_vectors.col(i) to z-axis
eigen_vectors.col (2) = eigen_vectors.col (0).cross (eigen_vectors.col (1));
eigen_vectors.col (1) = eigen_vectors.col (2).cross (eigen_vectors.col (0));
transform1 (0, 2) = eigen_vectors (0, 0);
transform1 (1, 2) = eigen_vectors (1, 0);
transform1 (2, 2) = eigen_vectors (2, 0);
transform1 (0, 1) = eigen_vectors (0, 1);
transform1 (1, 1) = eigen_vectors (1, 1);
transform1 (2, 1) = eigen_vectors (2, 1);
transform1 (0, 0) = eigen_vectors (0, 2);
transform1 (1, 0) = eigen_vectors (1, 2);
transform1 (2, 0) = eigen_vectors (2, 2);
transform1 = transform1.inverse ();
dim = 2;
}
else
transform1.setIdentity ();
dim_ = dim;
PointCloud cloud_transformed;
pcl::demeanPointCloud (*input_, *indices_, xyz_centroid, cloud_transformed);
pcl::transformPointCloud (cloud_transformed, cloud_transformed, transform1);
// True if qhull should free points in qh_freeqhull() or reallocation
boolT ismalloc = True;
// output from qh_produce_output(), use NULL to skip qh_produce_output()
FILE *outfile = NULL;
std::string flags_str;
flags_str = "qhull Tc";
if (compute_area_)
{
flags_str.append (" FA");
outfile = stderr;
}
// option flags for qhull, see qh_opt.htm
//char flags[] = "qhull Tc FA";
char * flags = (char *)flags_str.c_str();
// error messages from qhull code
FILE *errfile = stderr;
// 0 if no error from qhull
int exitcode;
// Array of coordinates for each point
coordT *points = (coordT *)calloc (cloud_transformed.points.size () * dim, sizeof(coordT));
for (size_t i = 0; i < cloud_transformed.points.size (); ++i)
{
points[i * dim + 0] = (coordT)cloud_transformed.points[i].x;
points[i * dim + 1] = (coordT)cloud_transformed.points[i].y;
if (dim > 2)
points[i * dim + 2] = (coordT)cloud_transformed.points[i].z;
}
// Compute convex hull
exitcode = qh_new_qhull (dim, cloud_transformed.points.size (), points, ismalloc, flags, outfile, errfile);
if (exitcode != 0)
{
PCL_ERROR ("[pcl::%s::performReconstrution] ERROR: qhull was unable to compute a convex hull for the given point cloud (%lu)!\n", getClassName ().c_str (), (unsigned long) input_->points.size ());
//check if it fails because of NaN values...
if (!cloud_transformed.is_dense)
{
bool NaNvalues = false;
for (size_t i = 0; i < cloud_transformed.size (); ++i)
{
if (!pcl_isfinite (cloud_transformed.points[i].x) ||
!pcl_isfinite (cloud_transformed.points[i].y) ||
!pcl_isfinite (cloud_transformed.points[i].z))
{
NaNvalues = true;
break;
}
}
if (NaNvalues)
PCL_ERROR ("[pcl::%s::performReconstruction] ERROR: point cloud contains NaN values, consider running pcl::PassThrough filter first to remove NaNs!\n", getClassName ().c_str ());
}
hull.points.resize (0);
hull.width = hull.height = 0;
polygons.resize (0);
qh_freeqhull (!qh_ALL);
int curlong, totlong;
qh_memfreeshort (&curlong, &totlong);
return;
}
qh_triangulate ();
int num_facets = qh num_facets;
int num_vertices = qh num_vertices;
hull.points.resize (num_vertices);
vertexT * vertex;
int i = 0;
// Max vertex id
int max_vertex_id = -1;
FORALLvertices
{
if ((int)vertex->id > max_vertex_id)
max_vertex_id = vertex->id;
}
++max_vertex_id;
std::vector<int> qhid_to_pcidx (max_vertex_id);
FORALLvertices
{
// Add vertices to hull point_cloud
hull.points[i].x = vertex->point[0];
hull.points[i].y = vertex->point[1];
if (dim>2)
hull.points[i].z = vertex->point[2];
else
hull.points[i].z = 0;
qhid_to_pcidx[vertex->id] = i; // map the vertex id of qhull to the point cloud index
++i;
}
if (compute_area_)
{
total_area_ = qh totarea;
total_volume_ = qh totvol;
}
if (fill_polygon_data)
{
if (dim == 3)
{
polygons.resize (num_facets);
int dd = 0;
facetT * facet;
FORALLfacets
{
polygons[dd].vertices.resize (3);
// Needed by FOREACHvertex_i_
int vertex_n, vertex_i;
FOREACHvertex_i_((*facet).vertices)
//facet_vertices.vertices.push_back (qhid_to_pcidx[vertex->id]);
polygons[dd].vertices[vertex_i] = qhid_to_pcidx[vertex->id];
++dd;
}
}
else
{
// dim=2, we want to return just a polygon with all vertices sorted
// so that they form a non-intersecting polygon...
// this can be moved to the upper loop probably and here just
// the sorting + populate
Eigen::Vector4f centroid;
pcl::compute3DCentroid (hull, centroid);
centroid[3] = 0;
polygons.resize (1);
int num_vertices = qh num_vertices, dd = 0;
// Copy all vertices
std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices);
FORALLvertices
{
idx_points[dd].first = qhid_to_pcidx[vertex->id];
idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid;
++dd;
}
// Sort idx_points
std::sort (idx_points.begin (), idx_points.end (), comparePoints2D);
polygons[0].vertices.resize (idx_points.size () + 1);
//Sort also points...
PointCloud hull_sorted;
hull_sorted.points.resize (hull.points.size ());
for (size_t j = 0; j < idx_points.size (); ++j)
hull_sorted.points[j] = hull.points[idx_points[j].first];
hull.points = hull_sorted.points;
// Populate points
for (size_t j = 0; j < idx_points.size (); ++j)
polygons[0].vertices[j] = j;
polygons[0].vertices[idx_points.size ()] = 0;
}
}
else
{
if (dim == 2)
{
// We want to sort the points
Eigen::Vector4f centroid;
pcl::compute3DCentroid (hull, centroid);
centroid[3] = 0;
polygons.resize (1);
int num_vertices = qh num_vertices, dd = 0;
// Copy all vertices
std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices);
FORALLvertices
{
idx_points[dd].first = qhid_to_pcidx[vertex->id];
idx_points[dd].second = hull.points[idx_points[dd].first].getVector4fMap () - centroid;
++dd;
}
// Sort idx_points
std::sort (idx_points.begin (), idx_points.end (), comparePoints2D);
//Sort also points...
PointCloud hull_sorted;
hull_sorted.points.resize (hull.points.size ());
for (size_t j = 0; j < idx_points.size (); ++j)
hull_sorted.points[j] = hull.points[idx_points[j].first];
hull.points = hull_sorted.points;
}
}
// Deallocates memory (also the points)
qh_freeqhull(!qh_ALL);
int curlong, totlong;
qh_memfreeshort (&curlong, &totlong);
// Rotate the hull point cloud by transform's inverse
// If the input point cloud has been rotated
if (dim == 2)
{
Eigen::Affine3f transInverse = transform1.inverse ();
pcl::transformPointCloud (hull, hull, transInverse);
//for 2D sets, the qhull library delivers the actual area of the 2d hull in the volume
if(compute_area_)
{
total_area_ = total_volume_;
total_volume_ = 0.0;
}
}
xyz_centroid[0] = -xyz_centroid[0];
xyz_centroid[1] = -xyz_centroid[1];
xyz_centroid[2] = -xyz_centroid[2];
pcl::demeanPointCloud (hull, xyz_centroid, hull);
//if keep_information_
if (keep_information_)
{
//build a tree with the original points
pcl::KdTreeFLANN<PointInT> tree (true);
tree.setInputCloud (input_, indices_);
std::vector<int> neighbor;
std::vector<float> distances;
neighbor.resize (1);
distances.resize (1);
//for each point in the convex hull, search for the nearest neighbor
std::vector<int> indices;
indices.resize (hull.points.size ());
for (size_t i = 0; i < hull.points.size (); i++)
{
tree.nearestKSearch (hull.points[i], 1, neighbor, distances);
indices[i] = (*indices_)[neighbor[0]];
}
//replace point with the closest neighbor in the original point cloud
pcl::copyPointCloud (*input_, indices, hull);
}
hull.width = hull.points.size ();
hull.height = 1;
hull.is_dense = false;
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::reconstruct (PointCloud &output)
{
output.header = input_->header;
if (!initCompute () || input_->points.empty ())
{
output.points.clear ();
return;
}
// Perform the actual surface reconstruction
std::vector<pcl::Vertices> polygons;
performReconstruction (output, polygons, false);
output.width = output.points.size ();
output.height = 1;
output.is_dense = true;
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::ConvexHull<PointInT>::reconstruct (PointCloud &points, std::vector<pcl::Vertices> &polygons)
{
points.header = input_->header;
if (!initCompute () || input_->points.empty ())
{
points.points.clear ();
return;
}
// Perform the actual surface reconstruction
performReconstruction (points, polygons, true);
points.width = points.points.size ();
points.height = 1;
points.is_dense = true;
deinitCompute ();
}
#define PCL_INSTANTIATE_ConvexHull(T) template class PCL_EXPORTS pcl::ConvexHull<T>;
#endif // PCL_SURFACE_IMPL_CONVEX_HULL_H_
#endif
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "InputMenu.h"
/* system implementation headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "BzfWindow.h"
#include "StateDatabase.h"
/* local implementation headers */
#include "MainWindow.h"
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "LocalPlayer.h"
/* FIXME - from playing.h */
MainWindow* getMainWindow();
InputMenu::InputMenu() : keyboardMapMenu(NULL)
{
std::string currentJoystickDevice = BZDB.get("joystickname");
// add controls
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* label = new HUDuiLabel;
label->setFont(MainMenu::getFont());
label->setString("Input Setting");
list.push_back(label);
keyMapping = new HUDuiLabel;
keyMapping->setFont(MainMenu::getFont());
keyMapping->setLabel("Change Key Mapping");
list.push_back(keyMapping);
HUDuiList* option = new HUDuiList;
option = new HUDuiList;
std::vector<std::string>* options = &option->getList();
// set joystick Device
option->setFont(MainMenu::getFont());
option->setLabel("Joystick device:");
option->setCallback(callback, (void*)"J");
options = &option->getList();
options->push_back(std::string("off"));
std::vector<std::string> joystickDevices;
getMainWindow()->getJoyDevices(joystickDevices);
int i;
for (i = 0; i < (int)joystickDevices.size(); i++) {
options->push_back(joystickDevices[i]);
}
joystickDevices.erase(joystickDevices.begin(), joystickDevices.end());
for (i = 0; i < (int)options->size(); i++) {
if ((*options)[i].compare(currentJoystickDevice) == 0) {
option->setIndex(i);
break;
}
}
option->update();
list.push_back(option);
forceInput = new HUDuiList;
forceInput->setFont(MainMenu::getFont());
forceInput->setLabel("Force input device:");
forceInput->setCallback(callback, (void*)"F");
options = &forceInput->getList();
options->push_back("Do not force");
options->push_back(LocalPlayer::getInputMethodName(LocalPlayer::Keyboard));
options->push_back(LocalPlayer::getInputMethodName(LocalPlayer::Mouse));
options->push_back(LocalPlayer::getInputMethodName(LocalPlayer::Joystick));
forceInput->update();
list.push_back(forceInput);
initNavigation(list, 1,list.size()-1);
}
InputMenu::~InputMenu()
{
delete keyboardMapMenu;
}
void InputMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == keyMapping) {
if (!keyboardMapMenu) keyboardMapMenu = new KeyboardMapMenu;
HUDDialogStack::get()->push(keyboardMapMenu);
}
}
void InputMenu::callback(HUDuiControl* w, void* data) {
HUDuiList* list = (HUDuiList*)w;
std::vector<std::string> *options = &list->getList();
std::string selectedOption = (*options)[list->getIndex()];
switch (((const char*)data)[0]) {
case 'J':
BZDB.set("joystickname", selectedOption);
getMainWindow()->initJoystick(selectedOption);
break;
case 'F':
{
LocalPlayer* myTank = LocalPlayer::getMyTank();
// Do we force or not?
if (selectedOption == "Do not force") {
BZDB.set("allowInputChange", "1");
} else {
BZDB.set("allowInputChange", "0");
BZDB.set("forceInputDevice", selectedOption);
}
// Set the current input device to whatever we're forced to
if (myTank) {
// FIXME - right now setInputMethod(Joystick) has no effect
// someone who knows about the joystick code should fix this
myTank->setInputMethod(BZDB.get("forceInputDevice"));
}
}
break;
}
}
void InputMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
int i;
// use a big font for title, smaller font for the rest
const float titleFontWidth = (float)height / 10.0f;
const float titleFontHeight = (float)height / 10.0f;
const float fontWidth = (float)height / 30.0f;
const float fontHeight = (float)height / 30.0f;
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontWidth, titleFontHeight);
const OpenGLTexFont& titleFont = title->getFont();
const float titleWidth = titleFont.getWidth(title->getString());
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleFont.getHeight();
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width + 0.5f * titleWidth);
y -= 0.6f * titleFont.getHeight();
const int count = list.size();
for (i = 1; i < count; i++) {
list[i]->setFontSize(fontWidth, fontHeight);
list[i]->setPosition(x, y);
y -= 1.0f * list[i]->getFont().getHeight();
}
// load current settings
// FIXME - hardcoded upper bound is ugly
std::vector<std::string> *options = &forceInput->getList();
for (i = 0; i < 4; i++) {
std::string currentOption = (*options)[i];
if (BZDB.get("forceInputDevice") == currentOption)
forceInput->setIndex(i);
}
if (BZDB.isTrue("allowInputChange"))
forceInput->setIndex(0);
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Fix hardcoded upper bound<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "InputMenu.h"
/* system implementation headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "BzfWindow.h"
#include "StateDatabase.h"
/* local implementation headers */
#include "MainWindow.h"
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "LocalPlayer.h"
/* FIXME - from playing.h */
MainWindow* getMainWindow();
InputMenu::InputMenu() : keyboardMapMenu(NULL)
{
std::string currentJoystickDevice = BZDB.get("joystickname");
// add controls
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* label = new HUDuiLabel;
label->setFont(MainMenu::getFont());
label->setString("Input Setting");
list.push_back(label);
keyMapping = new HUDuiLabel;
keyMapping->setFont(MainMenu::getFont());
keyMapping->setLabel("Change Key Mapping");
list.push_back(keyMapping);
HUDuiList* option = new HUDuiList;
option = new HUDuiList;
std::vector<std::string>* options = &option->getList();
// set joystick Device
option->setFont(MainMenu::getFont());
option->setLabel("Joystick device:");
option->setCallback(callback, (void*)"J");
options = &option->getList();
options->push_back(std::string("off"));
std::vector<std::string> joystickDevices;
getMainWindow()->getJoyDevices(joystickDevices);
int i;
for (i = 0; i < (int)joystickDevices.size(); i++) {
options->push_back(joystickDevices[i]);
}
joystickDevices.erase(joystickDevices.begin(), joystickDevices.end());
for (i = 0; i < (int)options->size(); i++) {
if ((*options)[i].compare(currentJoystickDevice) == 0) {
option->setIndex(i);
break;
}
}
option->update();
list.push_back(option);
forceInput = new HUDuiList;
forceInput->setFont(MainMenu::getFont());
forceInput->setLabel("Force input device:");
forceInput->setCallback(callback, (void*)"F");
options = &forceInput->getList();
options->push_back("Do not force");
options->push_back(LocalPlayer::getInputMethodName(LocalPlayer::Keyboard));
options->push_back(LocalPlayer::getInputMethodName(LocalPlayer::Mouse));
options->push_back(LocalPlayer::getInputMethodName(LocalPlayer::Joystick));
forceInput->update();
list.push_back(forceInput);
initNavigation(list, 1,list.size()-1);
}
InputMenu::~InputMenu()
{
delete keyboardMapMenu;
}
void InputMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == keyMapping) {
if (!keyboardMapMenu) keyboardMapMenu = new KeyboardMapMenu;
HUDDialogStack::get()->push(keyboardMapMenu);
}
}
void InputMenu::callback(HUDuiControl* w, void* data) {
HUDuiList* list = (HUDuiList*)w;
std::vector<std::string> *options = &list->getList();
std::string selectedOption = (*options)[list->getIndex()];
switch (((const char*)data)[0]) {
case 'J':
BZDB.set("joystickname", selectedOption);
getMainWindow()->initJoystick(selectedOption);
break;
case 'F':
{
LocalPlayer* myTank = LocalPlayer::getMyTank();
// Do we force or not?
if (selectedOption == "Do not force") {
BZDB.set("allowInputChange", "1");
} else {
BZDB.set("allowInputChange", "0");
BZDB.set("forceInputDevice", selectedOption);
}
// Set the current input device to whatever we're forced to
if (myTank) {
// FIXME - right now setInputMethod(Joystick) has no effect
// someone who knows about the joystick code should fix this
myTank->setInputMethod(BZDB.get("forceInputDevice"));
}
}
break;
}
}
void InputMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
int i;
// use a big font for title, smaller font for the rest
const float titleFontWidth = (float)height / 10.0f;
const float titleFontHeight = (float)height / 10.0f;
const float fontWidth = (float)height / 30.0f;
const float fontHeight = (float)height / 30.0f;
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontWidth, titleFontHeight);
const OpenGLTexFont& titleFont = title->getFont();
const float titleWidth = titleFont.getWidth(title->getString());
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleFont.getHeight();
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width + 0.5f * titleWidth);
y -= 0.6f * titleFont.getHeight();
const int count = list.size();
for (i = 1; i < count; i++) {
list[i]->setFontSize(fontWidth, fontHeight);
list[i]->setPosition(x, y);
y -= 1.0f * list[i]->getFont().getHeight();
}
// load current settings
std::vector<std::string> *options = &forceInput->getList();
for (i = 0; i < options->size(); i++) {
std::string currentOption = (*options)[i];
if (BZDB.get("forceInputDevice") == currentOption)
forceInput->setIndex(i);
}
if (BZDB.isTrue("allowInputChange"))
forceInput->setIndex(0);
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>//===- Symbols.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Symbols.h"
#include "InputSection.h"
#include "Error.h"
#include "InputFiles.h"
#include "llvm/ADT/STLExtras.h"
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf2;
static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
if (VA == STV_DEFAULT)
return VB;
if (VB == STV_DEFAULT)
return VA;
return std::min(VA, VB);
}
// Returns 1, 0 or -1 if this symbol should take precedence
// over the Other, tie or lose, respectively.
template <class ELFT> int SymbolBody::compare(SymbolBody *Other) {
assert(!isLazy() && !Other->isLazy());
std::pair<bool, bool> L(isDefined(), !isWeak());
std::pair<bool, bool> R(Other->isDefined(), !Other->isWeak());
// Normalize
if (L > R)
return -Other->compare<ELFT>(this);
Visibility = Other->Visibility =
getMinVisibility(Visibility, Other->Visibility);
IsUsedInRegularObj |= Other->IsUsedInRegularObj;
Other->IsUsedInRegularObj |= IsUsedInRegularObj;
if (L != R)
return -1;
if (!L.first || !L.second)
return 1;
if (isShared())
return -1;
if (Other->isShared())
return 1;
if (isCommon()) {
if (!Other->isCommon())
return -1;
auto *ThisC = cast<DefinedCommon<ELFT>>(this);
auto *OtherC = cast<DefinedCommon<ELFT>>(Other);
typename DefinedCommon<ELFT>::uintX_t MaxAlign =
std::max(ThisC->MaxAlignment, OtherC->MaxAlignment);
if (ThisC->Sym.st_size >= OtherC->Sym.st_size) {
ThisC->MaxAlignment = MaxAlign;
return 1;
}
OtherC->MaxAlignment = MaxAlign;
return -1;
}
if (Other->isCommon())
return 1;
return 0;
}
std::unique_ptr<InputFile> Lazy::getMember() {
MemoryBufferRef MBRef = File->getMember(&Sym);
// getMember returns an empty buffer if the member was already
// read from the library.
if (MBRef.getBuffer().empty())
return std::unique_ptr<InputFile>(nullptr);
return createELFFile<ObjectFile>(MBRef);
}
template <class ELFT> static void doInitSymbols() {
DefinedAbsolute<ELFT>::IgnoreUndef.setBinding(STB_WEAK);
DefinedAbsolute<ELFT>::IgnoreUndef.setVisibility(STV_HIDDEN);
Undefined<ELFT>::Optional.setVisibility(STV_HIDDEN);
}
void lld::elf2::initSymbols() {
doInitSymbols<ELF32LE>();
doInitSymbols<ELF32BE>();
doInitSymbols<ELF64LE>();
doInitSymbols<ELF64BE>();
}
template int SymbolBody::compare<ELF32LE>(SymbolBody *Other);
template int SymbolBody::compare<ELF32BE>(SymbolBody *Other);
template int SymbolBody::compare<ELF64LE>(SymbolBody *Other);
template int SymbolBody::compare<ELF64BE>(SymbolBody *Other);
<commit_msg>ELF2: Avoid bitwise-OR hack. NFC.<commit_after>//===- Symbols.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Symbols.h"
#include "InputSection.h"
#include "Error.h"
#include "InputFiles.h"
#include "llvm/ADT/STLExtras.h"
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf2;
static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {
if (VA == STV_DEFAULT)
return VB;
if (VB == STV_DEFAULT)
return VA;
return std::min(VA, VB);
}
// Returns 1, 0 or -1 if this symbol should take precedence
// over the Other, tie or lose, respectively.
template <class ELFT> int SymbolBody::compare(SymbolBody *Other) {
assert(!isLazy() && !Other->isLazy());
std::pair<bool, bool> L(isDefined(), !isWeak());
std::pair<bool, bool> R(Other->isDefined(), !Other->isWeak());
// Normalize
if (L > R)
return -Other->compare<ELFT>(this);
Visibility = Other->Visibility =
getMinVisibility(Visibility, Other->Visibility);
if (IsUsedInRegularObj || Other->IsUsedInRegularObj)
IsUsedInRegularObj = Other->IsUsedInRegularObj = true;
if (L != R)
return -1;
if (!L.first || !L.second)
return 1;
if (isShared())
return -1;
if (Other->isShared())
return 1;
if (isCommon()) {
if (!Other->isCommon())
return -1;
auto *ThisC = cast<DefinedCommon<ELFT>>(this);
auto *OtherC = cast<DefinedCommon<ELFT>>(Other);
typename DefinedCommon<ELFT>::uintX_t MaxAlign =
std::max(ThisC->MaxAlignment, OtherC->MaxAlignment);
if (ThisC->Sym.st_size >= OtherC->Sym.st_size) {
ThisC->MaxAlignment = MaxAlign;
return 1;
}
OtherC->MaxAlignment = MaxAlign;
return -1;
}
if (Other->isCommon())
return 1;
return 0;
}
std::unique_ptr<InputFile> Lazy::getMember() {
MemoryBufferRef MBRef = File->getMember(&Sym);
// getMember returns an empty buffer if the member was already
// read from the library.
if (MBRef.getBuffer().empty())
return std::unique_ptr<InputFile>(nullptr);
return createELFFile<ObjectFile>(MBRef);
}
template <class ELFT> static void doInitSymbols() {
DefinedAbsolute<ELFT>::IgnoreUndef.setBinding(STB_WEAK);
DefinedAbsolute<ELFT>::IgnoreUndef.setVisibility(STV_HIDDEN);
Undefined<ELFT>::Optional.setVisibility(STV_HIDDEN);
}
void lld::elf2::initSymbols() {
doInitSymbols<ELF32LE>();
doInitSymbols<ELF32BE>();
doInitSymbols<ELF64LE>();
doInitSymbols<ELF64BE>();
}
template int SymbolBody::compare<ELF32LE>(SymbolBody *Other);
template int SymbolBody::compare<ELF32BE>(SymbolBody *Other);
template int SymbolBody::compare<ELF64LE>(SymbolBody *Other);
template int SymbolBody::compare<ELF64BE>(SymbolBody *Other);
<|endoftext|> |
<commit_before>/*
open source routing machine
Copyright (C) Dennis Luxen, others 2010
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#include "ScriptingEnvironment.h"
ScriptingEnvironment::ScriptingEnvironment() {}
ScriptingEnvironment::ScriptingEnvironment(const char * fileName) {
INFO("Using script " << fileName);
// Create a new lua state
for(int i = 0; i < omp_get_max_threads(); ++i)
luaStateVector.push_back(luaL_newstate());
// Connect LuaBind to this lua state for all threads
#pragma omp parallel
{
lua_State * myLuaState = getLuaStateForThreadID(omp_get_thread_num());
luabind::open(myLuaState);
//open utility libraries string library;
luaL_openlibs(myLuaState);
luaAddScriptFolderToLoadPath( myLuaState, fileName );
// Add our function to the state's global scope
luabind::module(myLuaState) [
luabind::def("print", LUA_print<std::string>),
luabind::def("parseMaxspeed", parseMaxspeed),
luabind::def("durationIsValid", durationIsValid),
luabind::def("parseDuration", parseDuration)
];
luabind::module(myLuaState) [
luabind::class_<HashTable<std::string, std::string> >("keyVals")
.def("Add", &HashTable<std::string, std::string>::Add)
.def("Find", &HashTable<std::string, std::string>::Find)
.def("Holds", &HashTable<std::string, std::string>::Holds)
];
luabind::module(myLuaState) [
luabind::class_<ImportNode>("Node")
.def(luabind::constructor<>())
.def_readwrite("lat", &ImportNode::lat)
.def_readwrite("lon", &ImportNode::lon)
.def_readwrite("id", &ImportNode::id)
.def_readwrite("bollard", &ImportNode::bollard)
.def_readwrite("traffic_light", &ImportNode::trafficLight)
.def_readwrite("tags", &ImportNode::keyVals)
];
luabind::module(myLuaState) [
luabind::class_<_Way>("Way")
.def(luabind::constructor<>())
.def_readwrite("name", &_Way::name)
.def_readwrite("speed", &_Way::speed)
.def_readwrite("type", &_Way::type)
.def_readwrite("access", &_Way::access)
.def_readwrite("roundabout", &_Way::roundabout)
.def_readwrite("is_duration_set", &_Way::isDurationSet)
.def_readwrite("is_access_restricted", &_Way::isAccessRestricted)
.def_readwrite("ignore_in_grid", &_Way::ignoreInGrid)
.def_readwrite("tags", &_Way::keyVals)
.def_readwrite("direction", &_Way::direction)
.enum_("constants")
[
luabind::value("notSure", 0),
luabind::value("oneway", 1),
luabind::value("bidirectional", 2),
luabind::value("opposite", 3)
]
];
luabind::module(myLuaState) [
luabind::class_<std::vector<std::string> >("vector")
.def("Add", &std::vector<std::string>::push_back)
];
// Now call our function in a lua script
//#pragma omp critical
// {
// INFO("Parsing speedprofile from " << fileName );
// }
if(0 != luaL_dofile(myLuaState, fileName) ) {
ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block");
}
}
}
ScriptingEnvironment::~ScriptingEnvironment() {
for(unsigned i = 0; i < luaStateVector.size(); ++i) {
// luaStateVector[i];
}
}
lua_State * ScriptingEnvironment::getLuaStateForThreadID(const int id) {
return luaStateVector[id];
}
<commit_msg>Removing dead code.<commit_after>/*
open source routing machine
Copyright (C) Dennis Luxen, others 2010
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#include "ScriptingEnvironment.h"
ScriptingEnvironment::ScriptingEnvironment() {}
ScriptingEnvironment::ScriptingEnvironment(const char * fileName) {
INFO("Using script " << fileName);
// Create a new lua state
for(int i = 0; i < omp_get_max_threads(); ++i)
luaStateVector.push_back(luaL_newstate());
// Connect LuaBind to this lua state for all threads
#pragma omp parallel
{
lua_State * myLuaState = getLuaStateForThreadID(omp_get_thread_num());
luabind::open(myLuaState);
//open utility libraries string library;
luaL_openlibs(myLuaState);
luaAddScriptFolderToLoadPath( myLuaState, fileName );
// Add our function to the state's global scope
luabind::module(myLuaState) [
luabind::def("print", LUA_print<std::string>),
luabind::def("parseMaxspeed", parseMaxspeed),
luabind::def("durationIsValid", durationIsValid),
luabind::def("parseDuration", parseDuration)
];
luabind::module(myLuaState) [
luabind::class_<HashTable<std::string, std::string> >("keyVals")
.def("Add", &HashTable<std::string, std::string>::Add)
.def("Find", &HashTable<std::string, std::string>::Find)
.def("Holds", &HashTable<std::string, std::string>::Holds)
];
luabind::module(myLuaState) [
luabind::class_<ImportNode>("Node")
.def(luabind::constructor<>())
.def_readwrite("lat", &ImportNode::lat)
.def_readwrite("lon", &ImportNode::lon)
.def_readwrite("id", &ImportNode::id)
.def_readwrite("bollard", &ImportNode::bollard)
.def_readwrite("traffic_light", &ImportNode::trafficLight)
.def_readwrite("tags", &ImportNode::keyVals)
];
luabind::module(myLuaState) [
luabind::class_<_Way>("Way")
.def(luabind::constructor<>())
.def_readwrite("name", &_Way::name)
.def_readwrite("speed", &_Way::speed)
.def_readwrite("type", &_Way::type)
.def_readwrite("access", &_Way::access)
.def_readwrite("roundabout", &_Way::roundabout)
.def_readwrite("is_duration_set", &_Way::isDurationSet)
.def_readwrite("is_access_restricted", &_Way::isAccessRestricted)
.def_readwrite("ignore_in_grid", &_Way::ignoreInGrid)
.def_readwrite("tags", &_Way::keyVals)
.def_readwrite("direction", &_Way::direction)
.enum_("constants")
[
luabind::value("notSure", 0),
luabind::value("oneway", 1),
luabind::value("bidirectional", 2),
luabind::value("opposite", 3)
]
];
luabind::module(myLuaState) [
luabind::class_<std::vector<std::string> >("vector")
.def("Add", &std::vector<std::string>::push_back)
];
if(0 != luaL_dofile(myLuaState, fileName) ) {
ERR(lua_tostring(myLuaState,-1)<< " occured in scripting block");
}
}
}
ScriptingEnvironment::~ScriptingEnvironment() {
for(unsigned i = 0; i < luaStateVector.size(); ++i) {
// luaStateVector[i];
}
}
lua_State * ScriptingEnvironment::getLuaStateForThreadID(const int id) {
return luaStateVector[id];
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _WIN32
#pragma warning(4:4786)
#endif
#include <string>
#include <istream>
#include <fstream>
#include <stdlib.h>
#include "Permissions.h"
#include "MD5.h"
std::map<std::string, PlayerAccessInfo> groupAccess;
std::map<std::string, PlayerAccessInfo> userDatabase;
std::map<std::string, std::string> passwordDatabase;
bool hasGroup(PlayerAccessInfo& info, const std::string &group)
{
std::string str = group;
makeupper(str);
std::vector<std::string>::iterator itr = info.groups.begin();
while (itr != info.groups.end()) {
if ((*itr) == str)
return true;
itr++;
}
return false;
}
bool addGroup(PlayerAccessInfo& info, const std::string &group)
{
if (hasGroup(info, group))
return false;
std::string str = group;
makeupper(str);
info.groups.push_back(str);
return true;
}
bool removeGroup(PlayerAccessInfo& info, const std::string &group)
{
if (!hasGroup(info, group))
return false;
std::string str = group;
makeupper(str);
std::vector<std::string>::iterator itr = info.groups.begin();
while (itr != info.groups.end()) {
if ((*itr) == str) {
itr = info.groups.erase(itr);
return true;
} else
itr++;
}
return false;
}
bool hasPerm(PlayerAccessInfo& info, AccessPerm right)
{
if (info.explicitDenys.test(right))
return false;
if (info.explicitAllows.test(right))
return true;
std::vector<std::string>::iterator itr = info.groups.begin();
std::map<std::string, PlayerAccessInfo>::iterator group;
while (itr != info.groups.end()) {
group = groupAccess.find(*itr);
if (group != groupAccess.end())
if (group->second.explicitAllows.test(right))
return true;
itr++;
}
return false;
}
bool userExists(const std::string &nick)
{
std::string str = nick;
makeupper(str);
std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.find(str);
if (itr == userDatabase.end())
return false;
return true;
}
//FIXME - check for non-existing user (throw?)
PlayerAccessInfo& getUserInfo(const std::string &nick)
{
// if (!userExists(nick))
// return false;
std::string str = nick;
makeupper(str);
std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.find(str);
// if (itr == userDatabase.end())
// return false;
return itr->second;
}
bool setUserInfo(const std::string &nick, PlayerAccessInfo& info)
{
std::string str = nick;
makeupper(str);
userDatabase[str] = info;
return true;
}
bool verifyUserPassword(const std::string &nick, const std::string &pass)
{
std::string str1 = nick;
makeupper(str1);
std::map<std::string, std::string>::iterator itr = passwordDatabase.find(str1);
if (itr == passwordDatabase.end())
return false;
return itr->second == MD5(pass).hexdigest();
}
void setUserPassword(const std::string &nick, const std::string &pass)
{
std::string str1 = nick;
makeupper(str1);
// assume it's already a hash when length is 32 (FIXME?)
passwordDatabase[str1] = pass.size()==32 ? pass : MD5(pass).hexdigest();
}
std::string nameFromPerm(AccessPerm perm)
{
switch (perm) {
case idleStats: return "idleStats";
case lagStats: return "lagStats";
case flagMod: return "flagMod";
case flagHistory: return "flagHistory";
case lagwarn: return "lagwarn";
case kick: return "kick";
case ban: return "ban";
case banlist: return "banlist";
case unban: return "unban";
case countdown: return "countdown";
case endGame: return "endGame";
case shutdownServer: return "shutdownServer";
case superKill: return "superKill";
case playerList: return "playerList";
case info: return "info";
case listPerms: return "listPerms";
case showOthers: return "showOthers";
case removePerms: return "removePerms";
case setPassword: return "setPassword";
case setPerms: return "setPerms";
case setAll: return "setAll";
default: return NULL;
};
}
AccessPerm permFromName(const std::string &name)
{
if (name == "IDLESTATS") return idleStats;
if (name == "LAGSTATS") return lagStats;
if (name == "FLAGMOD") return flagMod;
if (name == "FLAGHISTORY") return flagHistory;
if (name == "LAGWARN") return lagwarn;
if (name == "KICK") return kick;
if (name == "BAN") return ban;
if (name == "BANLIST") return banlist;
if (name == "UNBAN") return unban;
if (name == "COUNTDOWN") return countdown;
if (name == "ENDGAME") return endGame;
if (name == "SHUTDOWNSERVER") return shutdownServer;
if (name == "SUPERKILL") return superKill;
if (name == "PLAYERLIST") return playerList;
if (name == "INFO") return info;
if (name == "LISTPERMS") return listPerms;
if (name == "SHOWOTHERS") return showOthers;
if (name == "REMOVEPERMS") return removePerms;
if (name == "SETPASSWORD") return setPassword;
if (name == "SETPERMS") return setPerms;
if (name == "SETALL") return setAll;
return lastPerm;
}
void parsePermissionString(const std::string &permissionString, std::bitset<lastPerm> &perms)
{
if (permissionString.length() < 1)
return;
perms.reset();
std::istringstream permStream(permissionString);
std::string word;
while (permStream >> word) {
makeupper(word);
AccessPerm perm = permFromName(word);
if (perm != lastPerm)
perms.set(perm);
}
}
bool readPassFile(const std::string &filename)
{
std::ifstream in(filename.c_str());
if (!in)
return false;
std::string line;
while (std::getline(in, line)) {
std::string::size_type colonpos = line.find(':');
if (colonpos != std::string::npos) {
std::string name = line.substr(0, colonpos);
std::string pass = line.substr(colonpos + 1);
makeupper(name);
setUserPassword(name.c_str(), pass.c_str());
}
}
return (passwordDatabase.size() > 0);
}
bool writePassFile(const std::string &filename)
{
std::ofstream out(filename.c_str());
if (!out)
return false;
std::map<std::string, std::string>::iterator itr = passwordDatabase.begin();
while (itr != passwordDatabase.end()) {
out << itr->first << ':' << itr->second << std::endl;
itr++;
}
out.close();
return true;
}
bool readGroupsFile(const std::string &filename)
{
std::ifstream in(filename.c_str());
if (!in)
return false;
std::string line;
while (std::getline(in, line)) {
std::string::size_type colonpos = line.find(':');
if (colonpos != std::string::npos) {
std::string name = line.substr(0, colonpos);
std::string perm = line.substr(colonpos + 1);
makeupper(name);
PlayerAccessInfo info;
parsePermissionString(perm, info.explicitAllows);
info.verified = true;
groupAccess[name] = info;
}
}
return true;
}
bool readPermsFile(const std::string &filename)
{
std::ifstream in(filename.c_str());
if (!in)
return false;
for (;;) {
// 1st line - name
std::string name;
if (!std::getline(in, name))
break;
PlayerAccessInfo info;
// 2nd line - groups
std::string groupline;
std::getline(in, groupline); // FIXME -it's an error when line cannot be read
std::istringstream groupstream(groupline);
std::string group;
while (groupstream >> group) {
info.groups.push_back(group);
}
// 3rd line - allows
std::string perms;
std::getline(in, perms);
parsePermissionString(perms, info.explicitAllows);
std::getline(in, perms);
parsePermissionString(perms, info.explicitDenys);
userDatabase[name] = info;
}
return true;
}
bool writePermsFile(const std::string &filename)
{
int i;
std::ofstream out(filename.c_str());
if (!out)
return false;
std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.begin();
std::vector<std::string>::iterator group;
while (itr != userDatabase.end()) {
out << itr->first << std::endl;
group = itr->second.groups.begin();
while (group != itr->second.groups.end()) {
out << (*group) << ' ';
group++;
}
out << std::endl;
// allows
for (i = 0; i < lastPerm; i++)
if (itr->second.explicitAllows.test(i))
out << nameFromPerm((AccessPerm) i);
out << std::endl;
// denys
for (i = 0; i < lastPerm; i++)
if (itr->second.explicitDenys.test(i))
out << nameFromPerm((AccessPerm) i);
out << std::endl;
itr++;
}
out.close();
return true;
}
std::string groupsFile;
std::string passFile;
std::string userDatabaseFile;
void updateDatabases()
{
if(passFile.size())
writePassFile(passFile);
if(userDatabaseFile.size())
writePermsFile(userDatabaseFile);
}
// ex: shiftwidth=2 tabstop=8
<commit_msg>remove istream<commit_after>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _WIN32
#pragma warning(4:4786)
#endif
#include <string>
#include <fstream>
#include <stdlib.h>
#include "Permissions.h"
#include "MD5.h"
std::map<std::string, PlayerAccessInfo> groupAccess;
std::map<std::string, PlayerAccessInfo> userDatabase;
std::map<std::string, std::string> passwordDatabase;
bool hasGroup(PlayerAccessInfo& info, const std::string &group)
{
std::string str = group;
makeupper(str);
std::vector<std::string>::iterator itr = info.groups.begin();
while (itr != info.groups.end()) {
if ((*itr) == str)
return true;
itr++;
}
return false;
}
bool addGroup(PlayerAccessInfo& info, const std::string &group)
{
if (hasGroup(info, group))
return false;
std::string str = group;
makeupper(str);
info.groups.push_back(str);
return true;
}
bool removeGroup(PlayerAccessInfo& info, const std::string &group)
{
if (!hasGroup(info, group))
return false;
std::string str = group;
makeupper(str);
std::vector<std::string>::iterator itr = info.groups.begin();
while (itr != info.groups.end()) {
if ((*itr) == str) {
itr = info.groups.erase(itr);
return true;
} else
itr++;
}
return false;
}
bool hasPerm(PlayerAccessInfo& info, AccessPerm right)
{
if (info.explicitDenys.test(right))
return false;
if (info.explicitAllows.test(right))
return true;
std::vector<std::string>::iterator itr = info.groups.begin();
std::map<std::string, PlayerAccessInfo>::iterator group;
while (itr != info.groups.end()) {
group = groupAccess.find(*itr);
if (group != groupAccess.end())
if (group->second.explicitAllows.test(right))
return true;
itr++;
}
return false;
}
bool userExists(const std::string &nick)
{
std::string str = nick;
makeupper(str);
std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.find(str);
if (itr == userDatabase.end())
return false;
return true;
}
//FIXME - check for non-existing user (throw?)
PlayerAccessInfo& getUserInfo(const std::string &nick)
{
// if (!userExists(nick))
// return false;
std::string str = nick;
makeupper(str);
std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.find(str);
// if (itr == userDatabase.end())
// return false;
return itr->second;
}
bool setUserInfo(const std::string &nick, PlayerAccessInfo& info)
{
std::string str = nick;
makeupper(str);
userDatabase[str] = info;
return true;
}
bool verifyUserPassword(const std::string &nick, const std::string &pass)
{
std::string str1 = nick;
makeupper(str1);
std::map<std::string, std::string>::iterator itr = passwordDatabase.find(str1);
if (itr == passwordDatabase.end())
return false;
return itr->second == MD5(pass).hexdigest();
}
void setUserPassword(const std::string &nick, const std::string &pass)
{
std::string str1 = nick;
makeupper(str1);
// assume it's already a hash when length is 32 (FIXME?)
passwordDatabase[str1] = pass.size()==32 ? pass : MD5(pass).hexdigest();
}
std::string nameFromPerm(AccessPerm perm)
{
switch (perm) {
case idleStats: return "idleStats";
case lagStats: return "lagStats";
case flagMod: return "flagMod";
case flagHistory: return "flagHistory";
case lagwarn: return "lagwarn";
case kick: return "kick";
case ban: return "ban";
case banlist: return "banlist";
case unban: return "unban";
case countdown: return "countdown";
case endGame: return "endGame";
case shutdownServer: return "shutdownServer";
case superKill: return "superKill";
case playerList: return "playerList";
case info: return "info";
case listPerms: return "listPerms";
case showOthers: return "showOthers";
case removePerms: return "removePerms";
case setPassword: return "setPassword";
case setPerms: return "setPerms";
case setAll: return "setAll";
default: return NULL;
};
}
AccessPerm permFromName(const std::string &name)
{
if (name == "IDLESTATS") return idleStats;
if (name == "LAGSTATS") return lagStats;
if (name == "FLAGMOD") return flagMod;
if (name == "FLAGHISTORY") return flagHistory;
if (name == "LAGWARN") return lagwarn;
if (name == "KICK") return kick;
if (name == "BAN") return ban;
if (name == "BANLIST") return banlist;
if (name == "UNBAN") return unban;
if (name == "COUNTDOWN") return countdown;
if (name == "ENDGAME") return endGame;
if (name == "SHUTDOWNSERVER") return shutdownServer;
if (name == "SUPERKILL") return superKill;
if (name == "PLAYERLIST") return playerList;
if (name == "INFO") return info;
if (name == "LISTPERMS") return listPerms;
if (name == "SHOWOTHERS") return showOthers;
if (name == "REMOVEPERMS") return removePerms;
if (name == "SETPASSWORD") return setPassword;
if (name == "SETPERMS") return setPerms;
if (name == "SETALL") return setAll;
return lastPerm;
}
void parsePermissionString(const std::string &permissionString, std::bitset<lastPerm> &perms)
{
if (permissionString.length() < 1)
return;
perms.reset();
std::istringstream permStream(permissionString);
std::string word;
while (permStream >> word) {
makeupper(word);
AccessPerm perm = permFromName(word);
if (perm != lastPerm)
perms.set(perm);
}
}
bool readPassFile(const std::string &filename)
{
std::ifstream in(filename.c_str());
if (!in)
return false;
std::string line;
while (std::getline(in, line)) {
std::string::size_type colonpos = line.find(':');
if (colonpos != std::string::npos) {
std::string name = line.substr(0, colonpos);
std::string pass = line.substr(colonpos + 1);
makeupper(name);
setUserPassword(name.c_str(), pass.c_str());
}
}
return (passwordDatabase.size() > 0);
}
bool writePassFile(const std::string &filename)
{
std::ofstream out(filename.c_str());
if (!out)
return false;
std::map<std::string, std::string>::iterator itr = passwordDatabase.begin();
while (itr != passwordDatabase.end()) {
out << itr->first << ':' << itr->second << std::endl;
itr++;
}
out.close();
return true;
}
bool readGroupsFile(const std::string &filename)
{
std::ifstream in(filename.c_str());
if (!in)
return false;
std::string line;
while (std::getline(in, line)) {
std::string::size_type colonpos = line.find(':');
if (colonpos != std::string::npos) {
std::string name = line.substr(0, colonpos);
std::string perm = line.substr(colonpos + 1);
makeupper(name);
PlayerAccessInfo info;
parsePermissionString(perm, info.explicitAllows);
info.verified = true;
groupAccess[name] = info;
}
}
return true;
}
bool readPermsFile(const std::string &filename)
{
std::ifstream in(filename.c_str());
if (!in)
return false;
for (;;) {
// 1st line - name
std::string name;
if (!std::getline(in, name))
break;
PlayerAccessInfo info;
// 2nd line - groups
std::string groupline;
std::getline(in, groupline); // FIXME -it's an error when line cannot be read
std::istringstream groupstream(groupline);
std::string group;
while (groupstream >> group) {
info.groups.push_back(group);
}
// 3rd line - allows
std::string perms;
std::getline(in, perms);
parsePermissionString(perms, info.explicitAllows);
std::getline(in, perms);
parsePermissionString(perms, info.explicitDenys);
userDatabase[name] = info;
}
return true;
}
bool writePermsFile(const std::string &filename)
{
int i;
std::ofstream out(filename.c_str());
if (!out)
return false;
std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.begin();
std::vector<std::string>::iterator group;
while (itr != userDatabase.end()) {
out << itr->first << std::endl;
group = itr->second.groups.begin();
while (group != itr->second.groups.end()) {
out << (*group) << ' ';
group++;
}
out << std::endl;
// allows
for (i = 0; i < lastPerm; i++)
if (itr->second.explicitAllows.test(i))
out << nameFromPerm((AccessPerm) i);
out << std::endl;
// denys
for (i = 0; i < lastPerm; i++)
if (itr->second.explicitDenys.test(i))
out << nameFromPerm((AccessPerm) i);
out << std::endl;
itr++;
}
out.close();
return true;
}
std::string groupsFile;
std::string passFile;
std::string userDatabaseFile;
void updateDatabases()
{
if(passFile.size())
writePassFile(passFile);
if(userDatabaseFile.size())
writePermsFile(userDatabaseFile);
}
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>//===- Symbols.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Symbols.h"
#include "Error.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Writer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include <cstring>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
DefinedRegular *ElfSym::Bss;
DefinedRegular *ElfSym::Etext1;
DefinedRegular *ElfSym::Etext2;
DefinedRegular *ElfSym::Edata1;
DefinedRegular *ElfSym::Edata2;
DefinedRegular *ElfSym::End1;
DefinedRegular *ElfSym::End2;
DefinedRegular *ElfSym::GlobalOffsetTable;
DefinedRegular *ElfSym::MipsGp;
DefinedRegular *ElfSym::MipsGpDisp;
DefinedRegular *ElfSym::MipsLocalGp;
static uint64_t getSymVA(const SymbolBody &Body, int64_t &Addend) {
switch (Body.kind()) {
case SymbolBody::DefinedRegularKind: {
auto &D = cast<DefinedRegular>(Body);
SectionBase *IS = D.Section;
if (auto *ISB = dyn_cast_or_null<InputSectionBase>(IS))
IS = ISB->Repl;
// According to the ELF spec reference to a local symbol from outside
// the group are not allowed. Unfortunately .eh_frame breaks that rule
// and must be treated specially. For now we just replace the symbol with
// 0.
if (IS == &InputSection::Discarded)
return 0;
// This is an absolute symbol.
if (!IS)
return D.Value;
uint64_t Offset = D.Value;
// An object in an SHF_MERGE section might be referenced via a
// section symbol (as a hack for reducing the number of local
// symbols).
// Depending on the addend, the reference via a section symbol
// refers to a different object in the merge section.
// Since the objects in the merge section are not necessarily
// contiguous in the output, the addend can thus affect the final
// VA in a non-linear way.
// To make this work, we incorporate the addend into the section
// offset (and zero out the addend for later processing) so that
// we find the right object in the section.
if (D.isSection()) {
Offset += Addend;
Addend = 0;
}
const OutputSection *OutSec = IS->getOutputSection();
// In the typical case, this is actually very simple and boils
// down to adding together 3 numbers:
// 1. The address of the output section.
// 2. The offset of the input section within the output section.
// 3. The offset within the input section (this addition happens
// inside InputSection::getOffset).
//
// If you understand the data structures involved with this next
// line (and how they get built), then you have a pretty good
// understanding of the linker.
uint64_t VA = (OutSec ? OutSec->Addr : 0) + IS->getOffset(Offset);
if (D.isTls() && !Config->Relocatable) {
if (!Out::TlsPhdr)
fatal(toString(D.getFile()) +
" has an STT_TLS symbol but doesn't have an SHF_TLS section");
return VA - Out::TlsPhdr->p_vaddr;
}
return VA;
}
case SymbolBody::DefinedCommonKind:
llvm_unreachable("common are converted to bss");
case SymbolBody::SharedKind: {
auto &SS = cast<SharedSymbol>(Body);
if (SS.CopyRelSec)
return SS.CopyRelSec->getParent()->Addr + SS.CopyRelSec->OutSecOff;
if (SS.NeedsPltAddr)
return Body.getPltVA();
return 0;
}
case SymbolBody::UndefinedKind:
return 0;
case SymbolBody::LazyArchiveKind:
case SymbolBody::LazyObjectKind:
assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
return 0;
}
llvm_unreachable("invalid symbol kind");
}
SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolKind(K), NeedsPltAddr(false), IsLocal(IsLocal),
IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
IsInIgot(false), IsPreemptible(false), Type(Type), StOther(StOther),
Name(Name) {}
bool SymbolBody::isUndefWeak() const {
if (isLocal())
return false;
return symbol()->isWeak() && (isUndefined() || isLazy());
}
InputFile *SymbolBody::getFile() const {
if (isLocal()) {
const SectionBase *Sec = cast<DefinedRegular>(this)->Section;
// Local absolute symbols actually have a file, but that is not currently
// used. We could support that by having a mostly redundant InputFile in
// SymbolBody, or having a special absolute section if needed.
return Sec ? cast<InputSectionBase>(Sec)->File : nullptr;
}
return symbol()->File;
}
// Overwrites all attributes with Other's so that this symbol becomes
// an alias to Other. This is useful for handling some options such as
// --wrap.
void SymbolBody::copyFrom(SymbolBody *Other) {
memcpy(symbol()->Body.buffer, Other->symbol()->Body.buffer,
sizeof(Symbol::Body));
}
uint64_t SymbolBody::getVA(int64_t Addend) const {
uint64_t OutVA = getSymVA(*this, Addend);
return OutVA + Addend;
}
uint64_t SymbolBody::getGotVA() const {
return InX::Got->getVA() + getGotOffset();
}
uint64_t SymbolBody::getGotOffset() const {
return GotIndex * Target->GotEntrySize;
}
uint64_t SymbolBody::getGotPltVA() const {
if (this->IsInIgot)
return InX::IgotPlt->getVA() + getGotPltOffset();
return InX::GotPlt->getVA() + getGotPltOffset();
}
uint64_t SymbolBody::getGotPltOffset() const {
return GotPltIndex * Target->GotPltEntrySize;
}
uint64_t SymbolBody::getPltVA() const {
if (this->IsInIplt)
return InX::Iplt->getVA() + PltIndex * Target->PltEntrySize;
return InX::Plt->getVA() + Target->PltHeaderSize +
PltIndex * Target->PltEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
if (const auto *C = dyn_cast<DefinedCommon>(this))
return C->Size;
if (const auto *DR = dyn_cast<DefinedRegular>(this))
return DR->Size;
if (const auto *S = dyn_cast<SharedSymbol>(this))
return S->getSize<ELFT>();
return 0;
}
OutputSection *SymbolBody::getOutputSection() const {
if (auto *S = dyn_cast<DefinedRegular>(this)) {
if (S->Section)
return S->Section->getOutputSection();
return nullptr;
}
if (auto *S = dyn_cast<SharedSymbol>(this)) {
if (S->CopyRelSec)
return S->CopyRelSec->getParent();
return nullptr;
}
if (auto *S = dyn_cast<DefinedCommon>(this)) {
if (Config->DefineCommon)
return S->Section->getParent();
return nullptr;
}
return nullptr;
}
// If a symbol name contains '@', the characters after that is
// a symbol version name. This function parses that.
void SymbolBody::parseSymbolVersion() {
StringRef S = getName();
size_t Pos = S.find('@');
if (Pos == 0 || Pos == StringRef::npos)
return;
StringRef Verstr = S.substr(Pos + 1);
if (Verstr.empty())
return;
// Truncate the symbol name so that it doesn't include the version string.
Name = {S.data(), Pos};
// If this is not in this DSO, it is not a definition.
if (!isInCurrentDSO())
return;
// '@@' in a symbol name means the default version.
// It is usually the most recent one.
bool IsDefault = (Verstr[0] == '@');
if (IsDefault)
Verstr = Verstr.substr(1);
for (VersionDefinition &Ver : Config->VersionDefinitions) {
if (Ver.Name != Verstr)
continue;
if (IsDefault)
symbol()->VersionId = Ver.Id;
else
symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
return;
}
// It is an error if the specified version is not defined.
// Usually version script is not provided when linking executable,
// but we may still want to override a versioned symbol from DSO,
// so we do not report error in this case.
if (Config->Shared)
error(toString(getFile()) + ": symbol " + S + " has undefined version " +
Verstr);
}
Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(K, Name, IsLocal, StOther, Type) {}
template <class ELFT> bool DefinedRegular::isMipsPIC() const {
typedef typename ELFT::Ehdr Elf_Ehdr;
if (!Section || !isFunc())
return false;
auto *Sec = cast<InputSectionBase>(Section);
const Elf_Ehdr *Hdr = Sec->template getFile<ELFT>()->getObj().getHeader();
return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
(Hdr->e_flags & EF_MIPS_PIC);
}
Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {}
DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint32_t Alignment,
uint8_t StOther, uint8_t Type)
: Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
Type),
Alignment(Alignment), Size(Size) {}
// If a shared symbol is referred via a copy relocation, its alignment
// becomes part of the ABI. This function returns a symbol alignment.
// Because symbols don't have alignment attributes, we need to infer that.
template <class ELFT> uint32_t SharedSymbol::getAlignment() const {
SharedFile<ELFT> *File = getFile<ELFT>();
uint32_t SecAlign = File->getSection(getSym<ELFT>())->sh_addralign;
uint64_t SymValue = getSym<ELFT>().st_value;
uint32_t SymAlign = uint32_t(1) << countTrailingZeros(SymValue);
return std::min(SecAlign, SymAlign);
}
InputFile *Lazy::fetch() {
if (auto *S = dyn_cast<LazyArchive>(this))
return S->fetch();
return cast<LazyObject>(this)->fetch();
}
LazyArchive::LazyArchive(const llvm::object::Archive::Symbol S, uint8_t Type)
: Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {}
LazyObject::LazyObject(StringRef Name, uint8_t Type)
: Lazy(LazyObjectKind, Name, Type) {}
ArchiveFile *LazyArchive::getFile() {
return cast<ArchiveFile>(SymbolBody::getFile());
}
InputFile *LazyArchive::fetch() {
std::pair<MemoryBufferRef, uint64_t> MBInfo = getFile()->getMember(&Sym);
// getMember returns an empty buffer if the member was already
// read from the library.
if (MBInfo.first.getBuffer().empty())
return nullptr;
return createObjectFile(MBInfo.first, getFile()->getName(), MBInfo.second);
}
LazyObjFile *LazyObject::getFile() {
return cast<LazyObjFile>(SymbolBody::getFile());
}
InputFile *LazyObject::fetch() { return getFile()->fetch(); }
uint8_t Symbol::computeBinding() const {
if (Config->Relocatable)
return Binding;
if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
return STB_LOCAL;
if (VersionId == VER_NDX_LOCAL && body()->isInCurrentDSO())
return STB_LOCAL;
if (Config->NoGnuUnique && Binding == STB_GNU_UNIQUE)
return STB_GLOBAL;
return Binding;
}
bool Symbol::includeInDynsym() const {
if (!Config->HasDynSymTab)
return false;
if (computeBinding() == STB_LOCAL)
return false;
if (!body()->isInCurrentDSO())
return true;
return ExportDynamic;
}
// Print out a log message for --trace-symbol.
void elf::printTraceSymbol(Symbol *Sym) {
SymbolBody *B = Sym->body();
std::string S;
if (B->isUndefined())
S = ": reference to ";
else if (B->isCommon())
S = ": common definition of ";
else
S = ": definition of ";
message(toString(Sym->File) + S + B->getName());
}
// Returns a symbol for an error message.
std::string lld::toString(const SymbolBody &B) {
if (Config->Demangle)
if (Optional<std::string> S = demangle(B.getName()))
return *S;
return B.getName();
}
template uint32_t SymbolBody::template getSize<ELF32LE>() const;
template uint32_t SymbolBody::template getSize<ELF32BE>() const;
template uint64_t SymbolBody::template getSize<ELF64LE>() const;
template uint64_t SymbolBody::template getSize<ELF64BE>() const;
template bool DefinedRegular::template isMipsPIC<ELF32LE>() const;
template bool DefinedRegular::template isMipsPIC<ELF32BE>() const;
template bool DefinedRegular::template isMipsPIC<ELF64LE>() const;
template bool DefinedRegular::template isMipsPIC<ELF64BE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF32LE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF32BE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF64LE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF64BE>() const;
<commit_msg>Add comment.<commit_after>//===- Symbols.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Symbols.h"
#include "Error.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Writer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include <cstring>
using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;
DefinedRegular *ElfSym::Bss;
DefinedRegular *ElfSym::Etext1;
DefinedRegular *ElfSym::Etext2;
DefinedRegular *ElfSym::Edata1;
DefinedRegular *ElfSym::Edata2;
DefinedRegular *ElfSym::End1;
DefinedRegular *ElfSym::End2;
DefinedRegular *ElfSym::GlobalOffsetTable;
DefinedRegular *ElfSym::MipsGp;
DefinedRegular *ElfSym::MipsGpDisp;
DefinedRegular *ElfSym::MipsLocalGp;
static uint64_t getSymVA(const SymbolBody &Body, int64_t &Addend) {
switch (Body.kind()) {
case SymbolBody::DefinedRegularKind: {
auto &D = cast<DefinedRegular>(Body);
SectionBase *IS = D.Section;
if (auto *ISB = dyn_cast_or_null<InputSectionBase>(IS))
IS = ISB->Repl;
// According to the ELF spec reference to a local symbol from outside
// the group are not allowed. Unfortunately .eh_frame breaks that rule
// and must be treated specially. For now we just replace the symbol with
// 0.
if (IS == &InputSection::Discarded)
return 0;
// This is an absolute symbol.
if (!IS)
return D.Value;
uint64_t Offset = D.Value;
// An object in an SHF_MERGE section might be referenced via a
// section symbol (as a hack for reducing the number of local
// symbols).
// Depending on the addend, the reference via a section symbol
// refers to a different object in the merge section.
// Since the objects in the merge section are not necessarily
// contiguous in the output, the addend can thus affect the final
// VA in a non-linear way.
// To make this work, we incorporate the addend into the section
// offset (and zero out the addend for later processing) so that
// we find the right object in the section.
if (D.isSection()) {
Offset += Addend;
Addend = 0;
}
const OutputSection *OutSec = IS->getOutputSection();
// In the typical case, this is actually very simple and boils
// down to adding together 3 numbers:
// 1. The address of the output section.
// 2. The offset of the input section within the output section.
// 3. The offset within the input section (this addition happens
// inside InputSection::getOffset).
//
// If you understand the data structures involved with this next
// line (and how they get built), then you have a pretty good
// understanding of the linker.
uint64_t VA = (OutSec ? OutSec->Addr : 0) + IS->getOffset(Offset);
if (D.isTls() && !Config->Relocatable) {
if (!Out::TlsPhdr)
fatal(toString(D.getFile()) +
" has an STT_TLS symbol but doesn't have an SHF_TLS section");
return VA - Out::TlsPhdr->p_vaddr;
}
return VA;
}
case SymbolBody::DefinedCommonKind:
llvm_unreachable("common are converted to bss");
case SymbolBody::SharedKind: {
auto &SS = cast<SharedSymbol>(Body);
if (SS.CopyRelSec)
return SS.CopyRelSec->getParent()->Addr + SS.CopyRelSec->OutSecOff;
if (SS.NeedsPltAddr)
return Body.getPltVA();
return 0;
}
case SymbolBody::UndefinedKind:
return 0;
case SymbolBody::LazyArchiveKind:
case SymbolBody::LazyObjectKind:
assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
return 0;
}
llvm_unreachable("invalid symbol kind");
}
SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolKind(K), NeedsPltAddr(false), IsLocal(IsLocal),
IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
IsInIgot(false), IsPreemptible(false), Type(Type), StOther(StOther),
Name(Name) {}
// Returns true if this is a weak undefined symbol.
bool SymbolBody::isUndefWeak() const {
// A note on isLazy() in the following expression: If you add a weak
// undefined symbol and then a lazy symbol to the symbol table, the
// combined result is a lazy weak symbol. isLazy is for that sitaution.
//
// Weak undefined symbols shouldn't fetch archive members (for
// compatibility with other linkers), but we still want to memorize
// that there are lazy symbols, because strong undefined symbols
// could be added later which triggers archive member fetching.
// Thus, the weak lazy symbol is a valid concept in lld.
return !isLocal() && symbol()->isWeak() && (isUndefined() || isLazy());
}
InputFile *SymbolBody::getFile() const {
if (isLocal()) {
const SectionBase *Sec = cast<DefinedRegular>(this)->Section;
// Local absolute symbols actually have a file, but that is not currently
// used. We could support that by having a mostly redundant InputFile in
// SymbolBody, or having a special absolute section if needed.
return Sec ? cast<InputSectionBase>(Sec)->File : nullptr;
}
return symbol()->File;
}
// Overwrites all attributes with Other's so that this symbol becomes
// an alias to Other. This is useful for handling some options such as
// --wrap.
void SymbolBody::copyFrom(SymbolBody *Other) {
memcpy(symbol()->Body.buffer, Other->symbol()->Body.buffer,
sizeof(Symbol::Body));
}
uint64_t SymbolBody::getVA(int64_t Addend) const {
uint64_t OutVA = getSymVA(*this, Addend);
return OutVA + Addend;
}
uint64_t SymbolBody::getGotVA() const {
return InX::Got->getVA() + getGotOffset();
}
uint64_t SymbolBody::getGotOffset() const {
return GotIndex * Target->GotEntrySize;
}
uint64_t SymbolBody::getGotPltVA() const {
if (this->IsInIgot)
return InX::IgotPlt->getVA() + getGotPltOffset();
return InX::GotPlt->getVA() + getGotPltOffset();
}
uint64_t SymbolBody::getGotPltOffset() const {
return GotPltIndex * Target->GotPltEntrySize;
}
uint64_t SymbolBody::getPltVA() const {
if (this->IsInIplt)
return InX::Iplt->getVA() + PltIndex * Target->PltEntrySize;
return InX::Plt->getVA() + Target->PltHeaderSize +
PltIndex * Target->PltEntrySize;
}
template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
if (const auto *C = dyn_cast<DefinedCommon>(this))
return C->Size;
if (const auto *DR = dyn_cast<DefinedRegular>(this))
return DR->Size;
if (const auto *S = dyn_cast<SharedSymbol>(this))
return S->getSize<ELFT>();
return 0;
}
OutputSection *SymbolBody::getOutputSection() const {
if (auto *S = dyn_cast<DefinedRegular>(this)) {
if (S->Section)
return S->Section->getOutputSection();
return nullptr;
}
if (auto *S = dyn_cast<SharedSymbol>(this)) {
if (S->CopyRelSec)
return S->CopyRelSec->getParent();
return nullptr;
}
if (auto *S = dyn_cast<DefinedCommon>(this)) {
if (Config->DefineCommon)
return S->Section->getParent();
return nullptr;
}
return nullptr;
}
// If a symbol name contains '@', the characters after that is
// a symbol version name. This function parses that.
void SymbolBody::parseSymbolVersion() {
StringRef S = getName();
size_t Pos = S.find('@');
if (Pos == 0 || Pos == StringRef::npos)
return;
StringRef Verstr = S.substr(Pos + 1);
if (Verstr.empty())
return;
// Truncate the symbol name so that it doesn't include the version string.
Name = {S.data(), Pos};
// If this is not in this DSO, it is not a definition.
if (!isInCurrentDSO())
return;
// '@@' in a symbol name means the default version.
// It is usually the most recent one.
bool IsDefault = (Verstr[0] == '@');
if (IsDefault)
Verstr = Verstr.substr(1);
for (VersionDefinition &Ver : Config->VersionDefinitions) {
if (Ver.Name != Verstr)
continue;
if (IsDefault)
symbol()->VersionId = Ver.Id;
else
symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
return;
}
// It is an error if the specified version is not defined.
// Usually version script is not provided when linking executable,
// but we may still want to override a versioned symbol from DSO,
// so we do not report error in this case.
if (Config->Shared)
error(toString(getFile()) + ": symbol " + S + " has undefined version " +
Verstr);
}
Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(K, Name, IsLocal, StOther, Type) {}
template <class ELFT> bool DefinedRegular::isMipsPIC() const {
typedef typename ELFT::Ehdr Elf_Ehdr;
if (!Section || !isFunc())
return false;
auto *Sec = cast<InputSectionBase>(Section);
const Elf_Ehdr *Hdr = Sec->template getFile<ELFT>()->getObj().getHeader();
return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
(Hdr->e_flags & EF_MIPS_PIC);
}
Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
uint8_t Type)
: SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {}
DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint32_t Alignment,
uint8_t StOther, uint8_t Type)
: Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
Type),
Alignment(Alignment), Size(Size) {}
// If a shared symbol is referred via a copy relocation, its alignment
// becomes part of the ABI. This function returns a symbol alignment.
// Because symbols don't have alignment attributes, we need to infer that.
template <class ELFT> uint32_t SharedSymbol::getAlignment() const {
SharedFile<ELFT> *File = getFile<ELFT>();
uint32_t SecAlign = File->getSection(getSym<ELFT>())->sh_addralign;
uint64_t SymValue = getSym<ELFT>().st_value;
uint32_t SymAlign = uint32_t(1) << countTrailingZeros(SymValue);
return std::min(SecAlign, SymAlign);
}
InputFile *Lazy::fetch() {
if (auto *S = dyn_cast<LazyArchive>(this))
return S->fetch();
return cast<LazyObject>(this)->fetch();
}
LazyArchive::LazyArchive(const llvm::object::Archive::Symbol S, uint8_t Type)
: Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {}
LazyObject::LazyObject(StringRef Name, uint8_t Type)
: Lazy(LazyObjectKind, Name, Type) {}
ArchiveFile *LazyArchive::getFile() {
return cast<ArchiveFile>(SymbolBody::getFile());
}
InputFile *LazyArchive::fetch() {
std::pair<MemoryBufferRef, uint64_t> MBInfo = getFile()->getMember(&Sym);
// getMember returns an empty buffer if the member was already
// read from the library.
if (MBInfo.first.getBuffer().empty())
return nullptr;
return createObjectFile(MBInfo.first, getFile()->getName(), MBInfo.second);
}
LazyObjFile *LazyObject::getFile() {
return cast<LazyObjFile>(SymbolBody::getFile());
}
InputFile *LazyObject::fetch() { return getFile()->fetch(); }
uint8_t Symbol::computeBinding() const {
if (Config->Relocatable)
return Binding;
if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
return STB_LOCAL;
if (VersionId == VER_NDX_LOCAL && body()->isInCurrentDSO())
return STB_LOCAL;
if (Config->NoGnuUnique && Binding == STB_GNU_UNIQUE)
return STB_GLOBAL;
return Binding;
}
bool Symbol::includeInDynsym() const {
if (!Config->HasDynSymTab)
return false;
if (computeBinding() == STB_LOCAL)
return false;
if (!body()->isInCurrentDSO())
return true;
return ExportDynamic;
}
// Print out a log message for --trace-symbol.
void elf::printTraceSymbol(Symbol *Sym) {
SymbolBody *B = Sym->body();
std::string S;
if (B->isUndefined())
S = ": reference to ";
else if (B->isCommon())
S = ": common definition of ";
else
S = ": definition of ";
message(toString(Sym->File) + S + B->getName());
}
// Returns a symbol for an error message.
std::string lld::toString(const SymbolBody &B) {
if (Config->Demangle)
if (Optional<std::string> S = demangle(B.getName()))
return *S;
return B.getName();
}
template uint32_t SymbolBody::template getSize<ELF32LE>() const;
template uint32_t SymbolBody::template getSize<ELF32BE>() const;
template uint64_t SymbolBody::template getSize<ELF64LE>() const;
template uint64_t SymbolBody::template getSize<ELF64BE>() const;
template bool DefinedRegular::template isMipsPIC<ELF32LE>() const;
template bool DefinedRegular::template isMipsPIC<ELF32BE>() const;
template bool DefinedRegular::template isMipsPIC<ELF64LE>() const;
template bool DefinedRegular::template isMipsPIC<ELF64BE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF32LE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF32BE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF64LE>() const;
template uint32_t SharedSymbol::template getAlignment<ELF64BE>() const;
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <tf/transform_listener.h>
#include "planner_modules_pr2/module_param_cache.h"
//#include "hardcoded_facts/geometryPoses.h"
#include "planner_modules_pr2/navstack_module.h"
#include <pluginlib/class_loader.h>
#include "continual_planning_executive/stateCreator.h"
#include "continual_planning_executive/goalCreator.h"
static pluginlib::ClassLoader<continual_planning_executive::StateCreator>* s_StateCreatorLoader = NULL;
continual_planning_executive::StateCreator* s_StateCreatorRobotLocation = NULL;
continual_planning_executive::StateCreator* s_StateCreatorRobotLocationInRoom = NULL;
static pluginlib::ClassLoader<continual_planning_executive::GoalCreator>* s_GoalCreatorLoader = NULL;
continual_planning_executive::GoalCreator* s_GoalCreator = NULL;
//ModuleParamCacheDouble g_PathCostCache;
bool loadStateCreator()
{
try {
// create here with new as it can't go out of scope
s_StateCreatorLoader
= new pluginlib::ClassLoader<continual_planning_executive::StateCreator>
("continual_planning_executive", "continual_planning_executive::StateCreator");
} catch(pluginlib::PluginlibException & ex) {
// possible reason for failure: no known plugins
ROS_ERROR("Could not instantiate class loader for continual_planning_executive::StateCreator - are there plugins registered? Error: %s", ex.what());
return false;
}
// This should be name + params
std::string state_creator_name = "tidyup_actions/state_creator_robot_pose";
std::deque<std::string> state_creator_entry;
state_creator_entry.push_back("robot_location");
state_creator_entry.push_back("location");
state_creator_entry.push_back("at-base");
state_creator_entry.push_back("location");
ROS_INFO("Loading state creator %s", state_creator_name.c_str());
try {
s_StateCreatorRobotLocation = s_StateCreatorLoader->createClassInstance(state_creator_name);
s_StateCreatorRobotLocation->initialize(state_creator_entry);
} catch(pluginlib::PluginlibException & ex) {
ROS_ERROR("Failed to load StateCreator instance for: %s. Error: %s.",
state_creator_name.c_str(), ex.what());
return false;
}
state_creator_name = "tidyup_actions/state_creator_robot_location_in_room";
state_creator_entry.clear();
state_creator_entry.push_back("robot_location");
state_creator_entry.push_back("location");
ROS_INFO("Loading state creator %s", state_creator_name.c_str());
try {
s_StateCreatorRobotLocationInRoom = s_StateCreatorLoader->createClassInstance(state_creator_name);
s_StateCreatorRobotLocationInRoom->initialize(state_creator_entry);
} catch(pluginlib::PluginlibException & ex) {
ROS_ERROR("Failed to load StateCreator instance for: %s. Error: %s.",
state_creator_name.c_str(), ex.what());
return false;
}
return true;
}
bool loadGoalCreator()
{
try {
// create here with new as it can't go out of scope
s_GoalCreatorLoader
= new pluginlib::ClassLoader<continual_planning_executive::GoalCreator>
("continual_planning_executive", "continual_planning_executive::GoalCreator");
} catch(pluginlib::PluginlibException & ex) {
// possible reason for failure: no known plugins
ROS_ERROR("Could not instantiate class loader for continual_planning_executive::GoalCreator - are there plugins registered? Error: %s", ex.what());
return false;
}
// This should be name + params
std::string goal_creator_name = "tidyup_actions/goal_creator_tidyup_objects";
std::deque<std::string> goal_creator_entry;
ROS_INFO("Loading goal creator %s", goal_creator_name.c_str());
try {
s_GoalCreator = s_GoalCreatorLoader->createClassInstance(goal_creator_name);
s_GoalCreator->initialize(goal_creator_entry);
} catch(pluginlib::PluginlibException & ex) {
ROS_ERROR("Failed to load GoalCreator instance for: %s. Error: %s.",
goal_creator_name.c_str(), ex.what());
return false;
}
return true;
}
void precacheEntry(const std::string & start, const std::string & goal, geometry_msgs::PoseStamped startPose, geometry_msgs::PoseStamped goalPose)
{
nav_msgs::GetPlan srv;
nav_msgs::GetPlan::Request & request = srv.request;
// create the path planning query for service
request.start.header.frame_id = g_WorldFrame;
request.goal.header.frame_id = g_WorldFrame;
request.start.pose = startPose.pose;
request.goal.pose = goalPose.pose;
request.tolerance = g_GoalTolerance;
// first lookup in the cache if we answered the query already
double cost = modules::INFINITE_COST;
std::string cacheKey = computePathCacheKey(start, goal, srv.request.start.pose, srv.request.goal.pose);
if(g_PathCostCache.get(cacheKey, cost)) {
ROS_INFO("Already got cost %.f for: %s", cost, cacheKey.c_str());
return;
}
bool callSuccessful;
cost = callPlanningService(srv, start, goal, callSuccessful);
if(callSuccessful) { // only cache real computed paths (including INFINITE_COST)
//bool isRobotLocation =
// (parameterList[0].value == "robot_location" || parameterList[1].value == "robot_location");
//g_PathCostCache.set(cacheKey, cost, !isRobotLocation); // do no param cache robot_location calls
ROS_INFO("Adding cache entry %s = %f", cacheKey.c_str(), cost);
g_PathCostCache.set(cacheKey, cost, true); // do param cache robot_location calls - they contain the location pose now (safe)
}
}
bool fillPoseStamped(const std::string & name, const SymbolicState & state, geometry_msgs::PoseStamped & ps)
{
Predicate p;
p.parameters.push_back(name);
p.name = "frame-id";
if(!state.hasObjectFluent(p, &ps.header.frame_id))
return false;
p.name = "x";
if(!state.hasNumericalFluent(p, &ps.pose.position.x))
return false;
p.name = "y";
if(!state.hasNumericalFluent(p, &ps.pose.position.y))
return false;
p.name = "z";
if(!state.hasNumericalFluent(p, &ps.pose.position.z))
return false;
p.name = "qx";
if(!state.hasNumericalFluent(p, &ps.pose.orientation.x))
return false;
p.name = "qy";
if(!state.hasNumericalFluent(p, &ps.pose.orientation.y))
return false;
p.name = "qz";
if(!state.hasNumericalFluent(p, &ps.pose.orientation.z))
return false;
p.name = "qw";
if(!state.hasNumericalFluent(p, &ps.pose.orientation.w))
return false;
return true;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "precache_navigation");
ros::NodeHandle nh;
tf::TransformListener tfl;
if(argc != 2) {
ROS_FATAL("Usage: %s <poses_file>", argv[0]);
return 1;
}
ROS_INFO("Loading poses from %s", argv[1]);
//GeometryPoses posesLoader;
//if(!posesLoader.load(argv[1])) {
// ROS_FATAL("Failed to load poses.");
// return 1;
//}
ros::NodeHandle nhPriv("~");
// for the goal creator
nhPriv.setParam("locations", argv[1]);
// TODO sigint
if(!loadStateCreator()) {
ROS_FATAL("Failed to load state creator.");
return 1;
}
if(!loadGoalCreator()) {
ROS_FATAL("Failed to load goal creator.");
return 1;
}
// Read the params as set for tfd_modules and set them for us, as navstack_init will read those.
nh.param("tfd_modules/trans_speed", g_TransSpeed, g_TransSpeed);
nh.param("tfd_modules/rot_speed", g_RotSpeed, g_RotSpeed);
nhPriv.setParam("trans_speed", g_TransSpeed);
nhPriv.setParam("rot_speed", g_RotSpeed);
int navstack_argc = 4;
char** navstack_argv = new char*[navstack_argc];
navstack_argv[0] = "precache_navigation";
navstack_argv[1] = "/map";
navstack_argv[2] = "0.05";
navstack_argv[3] = "1";
navstack_init(navstack_argc, navstack_argv);
delete[] navstack_argv;
//const std::map<std::string, geometry_msgs::PoseStamped> & poses = posesLoader.getPoses();
SymbolicState currentState;
SymbolicState goalState;
s_GoalCreator->fillStateAndGoal(currentState, goalState);
while(!s_StateCreatorRobotLocation->fillState(currentState)) {
ROS_WARN("State estimation failed.");
usleep(1000*1000);
}
while(!s_StateCreatorRobotLocationInRoom->fillState(currentState)) {
ROS_WARN("State location in room estimation failed.");
usleep(1000*1000);
}
ROS_INFO("State estimation done.");
geometry_msgs::PoseStamped robotLocation;
if(!fillPoseStamped("robot_location", currentState, robotLocation)) {
ROS_FATAL("Could not estimate robot location");
return 1;
}
Predicate robotLocationInRoom;
robotLocationInRoom.name = "location-in-room";
robotLocationInRoom.parameters.push_back("robot_location");
std::string roomRobotLocation;
if(!currentState.hasObjectFluent(robotLocationInRoom, &roomRobotLocation)) {
ROS_ERROR("Could not determine room for robot_location");
}
const multimap<string, string> & typedObjects = currentState.getTypedObjects();
for(multimap<string, string>::const_iterator it1 = typedObjects.begin(); it1 != typedObjects.end(); it1++) {
//printf("At1 %s %s\n", it1->first.c_str(), it1->second.c_str());
if(it1->first != "manipulation_location"
&& it1->first != "door_in_location"
&& it1->first != "door_out_location")
continue;
Predicate inRoom1;
inRoom1.name = "location-in-room";
inRoom1.parameters.push_back(it1->second);
std::string room1;
if(!currentState.hasObjectFluent(inRoom1, &room1))
continue;
geometry_msgs::PoseStamped pose1;
if(!fillPoseStamped(it1->second, currentState, pose1)) {
ROS_ERROR("Could not find pose for %s.", it1->second.c_str());
continue;
}
for(multimap<string, string>::const_iterator it2 = typedObjects.begin(); it2 != typedObjects.end(); it2++){
//printf("At2 %s %s\n", it2->first.c_str(), it2->second.c_str());
if(it2->first != "manipulation_location"
&& it2->first != "door_in_location"
&& it2->first != "door_out_location")
continue;
if(it1->second == it2->second)
continue;
Predicate inRoom2;
inRoom2.name = "location-in-room";
inRoom2.parameters.push_back(it2->second);
std::string room2;
if(!currentState.hasObjectFluent(inRoom2, &room2))
continue;
if(room1 != room2)
continue;
if(it2->first == "door_out_location")
continue;
geometry_msgs::PoseStamped pose2;
if(!fillPoseStamped(it2->second, currentState, pose2)) {
ROS_ERROR("Could not find pose for %s.", it2->second.c_str());
continue;
}
ROS_INFO("Precaching: %s - %s", it1->second.c_str(), it2->second.c_str());
precacheEntry(it1->second, it2->second, pose1, pose2);
}
// Also add paths for robot_location
if(room1 != roomRobotLocation)
continue;
if(it1->first == "door_out_location")
continue;
ROS_INFO("Precaching: %s - %s", "robot_location", it1->second.c_str());
precacheEntry("robot_location", it1->second, robotLocation, pose1);
}
// through door?
// robot location in room? for init robot_location caches
// TODO test precache run quick!
/*
// location pairs
for(std::map<std::string, geometry_msgs::PoseStamped>::const_iterator it1 = poses.begin(); it1 != poses.end(); it1++) {
for(std::map<std::string, geometry_msgs::PoseStamped>::const_iterator it2 = poses.begin(); it2 != poses.end(); it2++) {
if(it1->first == it2->first)
continue;
ROS_INFO("Precaching: %s - %s", it1->first.c_str(), it2->first.c_str());
precacheEntry(it1->first, it2->first, it1->second, it2->second);
}
}
// current location - location
for(std::map<std::string, geometry_msgs::PoseStamped>::const_iterator it1 = poses.begin(); it1 != poses.end(); it1++) {
ROS_INFO("Precaching: %s - %s", it1->first.c_str(), "robot_location");
precacheEntry(it1->first, "robot_location", it1->second, robotLocation);
ROS_INFO("Precaching: %s - %s", "robot_location", it1->first.c_str());
precacheEntry("robot_location", it1->first, robotLocation, it1->second);
}
*/
// TODO only same room
// TODO weird stuff happening
// door in/out
// door needs to be open in planning scene
// please try only 1 goal pose
// table1 pose looks off
ROS_INFO("Precaching done.\n\n\n");
return 0;
}
<commit_msg>add SIGINT + option to query only specific start/goal to precache_navigation<commit_after>#include <ros/ros.h>
#include <tf/transform_listener.h>
#include "planner_modules_pr2/module_param_cache.h"
//#include "hardcoded_facts/geometryPoses.h"
#include "planner_modules_pr2/navstack_module.h"
#include <pluginlib/class_loader.h>
#include "continual_planning_executive/stateCreator.h"
#include "continual_planning_executive/goalCreator.h"
#include <signal.h>
static pluginlib::ClassLoader<continual_planning_executive::StateCreator>* s_StateCreatorLoader = NULL;
continual_planning_executive::StateCreator* s_StateCreatorRobotLocation = NULL;
continual_planning_executive::StateCreator* s_StateCreatorRobotLocationInRoom = NULL;
static pluginlib::ClassLoader<continual_planning_executive::GoalCreator>* s_GoalCreatorLoader = NULL;
continual_planning_executive::GoalCreator* s_GoalCreator = NULL;
bool keepRunning = true;
//ModuleParamCacheDouble g_PathCostCache;
void signal_handler(int )
{
keepRunning = false;
}
bool loadStateCreator()
{
try {
// create here with new as it can't go out of scope
s_StateCreatorLoader
= new pluginlib::ClassLoader<continual_planning_executive::StateCreator>
("continual_planning_executive", "continual_planning_executive::StateCreator");
} catch(pluginlib::PluginlibException & ex) {
// possible reason for failure: no known plugins
ROS_ERROR("Could not instantiate class loader for continual_planning_executive::StateCreator - are there plugins registered? Error: %s", ex.what());
return false;
}
// This should be name + params
std::string state_creator_name = "tidyup_actions/state_creator_robot_pose";
std::deque<std::string> state_creator_entry;
state_creator_entry.push_back("robot_location");
state_creator_entry.push_back("location");
state_creator_entry.push_back("at-base");
state_creator_entry.push_back("location");
ROS_INFO("Loading state creator %s", state_creator_name.c_str());
try {
s_StateCreatorRobotLocation = s_StateCreatorLoader->createClassInstance(state_creator_name);
s_StateCreatorRobotLocation->initialize(state_creator_entry);
} catch(pluginlib::PluginlibException & ex) {
ROS_ERROR("Failed to load StateCreator instance for: %s. Error: %s.",
state_creator_name.c_str(), ex.what());
return false;
}
state_creator_name = "tidyup_actions/state_creator_robot_location_in_room";
state_creator_entry.clear();
state_creator_entry.push_back("robot_location");
state_creator_entry.push_back("location");
ROS_INFO("Loading state creator %s", state_creator_name.c_str());
try {
s_StateCreatorRobotLocationInRoom = s_StateCreatorLoader->createClassInstance(state_creator_name);
s_StateCreatorRobotLocationInRoom->initialize(state_creator_entry);
} catch(pluginlib::PluginlibException & ex) {
ROS_ERROR("Failed to load StateCreator instance for: %s. Error: %s.",
state_creator_name.c_str(), ex.what());
return false;
}
return true;
}
bool loadGoalCreator()
{
try {
// create here with new as it can't go out of scope
s_GoalCreatorLoader
= new pluginlib::ClassLoader<continual_planning_executive::GoalCreator>
("continual_planning_executive", "continual_planning_executive::GoalCreator");
} catch(pluginlib::PluginlibException & ex) {
// possible reason for failure: no known plugins
ROS_ERROR("Could not instantiate class loader for continual_planning_executive::GoalCreator - are there plugins registered? Error: %s", ex.what());
return false;
}
// This should be name + params
std::string goal_creator_name = "tidyup_actions/goal_creator_tidyup_objects";
std::deque<std::string> goal_creator_entry;
ROS_INFO("Loading goal creator %s", goal_creator_name.c_str());
try {
s_GoalCreator = s_GoalCreatorLoader->createClassInstance(goal_creator_name);
s_GoalCreator->initialize(goal_creator_entry);
} catch(pluginlib::PluginlibException & ex) {
ROS_ERROR("Failed to load GoalCreator instance for: %s. Error: %s.",
goal_creator_name.c_str(), ex.what());
return false;
}
return true;
}
void precacheEntry(const std::string & start, const std::string & goal, geometry_msgs::PoseStamped startPose, geometry_msgs::PoseStamped goalPose)
{
nav_msgs::GetPlan srv;
nav_msgs::GetPlan::Request & request = srv.request;
// create the path planning query for service
request.start.header.frame_id = g_WorldFrame;
request.goal.header.frame_id = g_WorldFrame;
request.start.pose = startPose.pose;
request.goal.pose = goalPose.pose;
request.tolerance = g_GoalTolerance;
// first lookup in the cache if we answered the query already
double cost = modules::INFINITE_COST;
std::string cacheKey = computePathCacheKey(start, goal, srv.request.start.pose, srv.request.goal.pose);
if(g_PathCostCache.get(cacheKey, cost)) {
ROS_INFO("Already got cost %.f for: %s", cost, cacheKey.c_str());
return;
}
bool callSuccessful;
cost = callPlanningService(srv, start, goal, callSuccessful);
if(callSuccessful) { // only cache real computed paths (including INFINITE_COST)
//bool isRobotLocation =
// (parameterList[0].value == "robot_location" || parameterList[1].value == "robot_location");
//g_PathCostCache.set(cacheKey, cost, !isRobotLocation); // do no param cache robot_location calls
ROS_INFO("Adding cache entry %s = %f", cacheKey.c_str(), cost);
g_PathCostCache.set(cacheKey, cost, true); // do param cache robot_location calls - they contain the location pose now (safe)
}
}
bool fillPoseStamped(const std::string & name, const SymbolicState & state, geometry_msgs::PoseStamped & ps)
{
Predicate p;
p.parameters.push_back(name);
p.name = "frame-id";
if(!state.hasObjectFluent(p, &ps.header.frame_id))
return false;
p.name = "x";
if(!state.hasNumericalFluent(p, &ps.pose.position.x))
return false;
p.name = "y";
if(!state.hasNumericalFluent(p, &ps.pose.position.y))
return false;
p.name = "z";
if(!state.hasNumericalFluent(p, &ps.pose.position.z))
return false;
p.name = "qx";
if(!state.hasNumericalFluent(p, &ps.pose.orientation.x))
return false;
p.name = "qy";
if(!state.hasNumericalFluent(p, &ps.pose.orientation.y))
return false;
p.name = "qz";
if(!state.hasNumericalFluent(p, &ps.pose.orientation.z))
return false;
p.name = "qw";
if(!state.hasNumericalFluent(p, &ps.pose.orientation.w))
return false;
return true;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "precache_navigation", ros::init_options::NoSigintHandler);
ros::NodeHandle nh;
tf::TransformListener tfl;
if(argc != 2 && argc != 4) {
ROS_FATAL("Usage: %s <poses_file> [<start_location_name> <goal_location_name>]", argv[0]);
return 1;
}
std::string startLocationName;
std::string goalLocationName;
if(argc == 4) {
startLocationName = argv[2];
goalLocationName = argv[3];
}
ROS_INFO("Loading poses from %s", argv[1]);
//GeometryPoses posesLoader;
//if(!posesLoader.load(argv[1])) {
// ROS_FATAL("Failed to load poses.");
// return 1;
//}
ros::NodeHandle nhPriv("~");
// for the goal creator
nhPriv.setParam("locations", argv[1]);
if(!loadStateCreator()) {
ROS_FATAL("Failed to load state creator.");
return 1;
}
if(!loadGoalCreator()) {
ROS_FATAL("Failed to load goal creator.");
return 1;
}
// Read the params as set for tfd_modules and set them for us, as navstack_init will read those.
nh.param("tfd_modules/trans_speed", g_TransSpeed, g_TransSpeed);
nh.param("tfd_modules/rot_speed", g_RotSpeed, g_RotSpeed);
nhPriv.setParam("trans_speed", g_TransSpeed);
nhPriv.setParam("rot_speed", g_RotSpeed);
int navstack_argc = 4;
char** navstack_argv = new char*[navstack_argc];
navstack_argv[0] = "precache_navigation";
navstack_argv[1] = "/map";
navstack_argv[2] = "0.05";
navstack_argv[3] = "1";
navstack_init(navstack_argc, navstack_argv);
delete[] navstack_argv;
//const std::map<std::string, geometry_msgs::PoseStamped> & poses = posesLoader.getPoses();
SymbolicState currentState;
SymbolicState goalState;
s_GoalCreator->fillStateAndGoal(currentState, goalState);
while(!s_StateCreatorRobotLocation->fillState(currentState)) {
ROS_WARN("State estimation failed.");
usleep(1000*1000);
}
while(!s_StateCreatorRobotLocationInRoom->fillState(currentState)) {
ROS_WARN("State location in room estimation failed.");
usleep(1000*1000);
}
ROS_INFO("State estimation done.");
geometry_msgs::PoseStamped robotLocation;
if(!fillPoseStamped("robot_location", currentState, robotLocation)) {
ROS_FATAL("Could not estimate robot location");
return 1;
}
Predicate robotLocationInRoom;
robotLocationInRoom.name = "location-in-room";
robotLocationInRoom.parameters.push_back("robot_location");
std::string roomRobotLocation;
if(!currentState.hasObjectFluent(robotLocationInRoom, &roomRobotLocation)) {
ROS_ERROR("Could not determine room for robot_location");
}
const multimap<string, string> & typedObjects = currentState.getTypedObjects();
if(startLocationName.empty() || goalLocationName.empty()) {
::signal(SIGINT, signal_handler);
for(multimap<string, string>::const_iterator it1 = typedObjects.begin(); it1 != typedObjects.end(); it1++) {
//printf("At1 %s %s\n", it1->first.c_str(), it1->second.c_str());
if(it1->first != "manipulation_location"
&& it1->first != "door_in_location"
&& it1->first != "door_out_location")
continue;
Predicate inRoom1;
inRoom1.name = "location-in-room";
inRoom1.parameters.push_back(it1->second);
std::string room1;
if(!currentState.hasObjectFluent(inRoom1, &room1))
continue;
geometry_msgs::PoseStamped pose1;
if(!fillPoseStamped(it1->second, currentState, pose1)) {
ROS_ERROR("Could not find pose for %s.", it1->second.c_str());
continue;
}
for(multimap<string, string>::const_iterator it2 = typedObjects.begin(); it2 != typedObjects.end(); it2++){
//printf("At2 %s %s\n", it2->first.c_str(), it2->second.c_str());
if(it2->first != "manipulation_location"
&& it2->first != "door_in_location"
&& it2->first != "door_out_location")
continue;
if(it1->second == it2->second)
continue;
Predicate inRoom2;
inRoom2.name = "location-in-room";
inRoom2.parameters.push_back(it2->second);
std::string room2;
if(!currentState.hasObjectFluent(inRoom2, &room2))
continue;
if(room1 != room2)
continue;
if(it2->first == "door_out_location")
continue;
geometry_msgs::PoseStamped pose2;
if(!fillPoseStamped(it2->second, currentState, pose2)) {
ROS_ERROR("Could not find pose for %s.", it2->second.c_str());
continue;
}
ROS_INFO("Precaching: %s - %s", it1->second.c_str(), it2->second.c_str());
precacheEntry(it1->second, it2->second, pose1, pose2);
}
// Also add paths for robot_location
if(room1 != roomRobotLocation)
continue;
if(it1->first == "door_out_location")
continue;
ROS_INFO("Precaching: %s - %s", "robot_location", it1->second.c_str());
precacheEntry("robot_location", it1->second, robotLocation, pose1);
if(!keepRunning) {
ROS_WARN("Canceled precached due to SIGINT.");
break;
}
}
} else { // use startLocationName, goalLocationName
// FIXME: don't need to handle robot_location explicitly as it's named this in the currentState.
geometry_msgs::PoseStamped pose1;
if(!fillPoseStamped(startLocationName, currentState, pose1)) {
ROS_ERROR("Could not find pose for %s.", startLocationName.c_str());
return 1;
}
geometry_msgs::PoseStamped pose2;
if(!fillPoseStamped(goalLocationName, currentState, pose2)) {
ROS_ERROR("Could not find pose for %s.", goalLocationName.c_str());
return 1;
}
ROS_INFO("Precaching: %s - %s", startLocationName.c_str(), goalLocationName.c_str());
precacheEntry(startLocationName, goalLocationName, pose1, pose2);
}
/*
// location pairs
for(std::map<std::string, geometry_msgs::PoseStamped>::const_iterator it1 = poses.begin(); it1 != poses.end(); it1++) {
for(std::map<std::string, geometry_msgs::PoseStamped>::const_iterator it2 = poses.begin(); it2 != poses.end(); it2++) {
if(it1->first == it2->first)
continue;
ROS_INFO("Precaching: %s - %s", it1->first.c_str(), it2->first.c_str());
precacheEntry(it1->first, it2->first, it1->second, it2->second);
}
}
// current location - location
for(std::map<std::string, geometry_msgs::PoseStamped>::const_iterator it1 = poses.begin(); it1 != poses.end(); it1++) {
ROS_INFO("Precaching: %s - %s", it1->first.c_str(), "robot_location");
precacheEntry(it1->first, "robot_location", it1->second, robotLocation);
ROS_INFO("Precaching: %s - %s", "robot_location", it1->first.c_str());
precacheEntry("robot_location", it1->first, robotLocation, it1->second);
}
*/
// door needs to be open in planning scene
ROS_INFO("Precaching done.\n\n\n");
return 0;
}
<|endoftext|> |
<commit_before>#include "equelle/RuntimeMPI.hpp"
#include <iostream>
#include <mpi.h>
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <zoltan_cpp.h>
#pragma GCC diagnostic pop
#include <opm/core/grid/GridManager.hpp>
#include "EquelleRuntimeCPU.hpp"
#include "equelle/mpiutils.hpp"
namespace equelle {
void RuntimeMPI::initializeZoltan()
{
zoltan.reset( new Zoltan( MPI_COMM_WORLD ) );
// Use hypergraph partitioning
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "LB_METHOD", "GRAPH" ) );
// Partition everything without concern for cost.
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "LB_APPROACH", "PARTITION" ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "PHG_EDGE_SIZE_THRESHOLD", "1.0" ) );
#ifndef EQUELLE_DEBUG
// Check that the query functions return valid input data; 0 or 1. (This slows performance; intended for debugging.)
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "CHECK_HYPERGRAPH", "1" ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "DEBUG_LEVEL", "2" ) );
#endif
}
void RuntimeMPI::initializeGrid()
{
if ( getMPIRank() == 0 ) {
grid_manager.reset( new Opm::GridManager( 6, 1 ) );
} else {
grid_manager.reset( new Opm::GridManager( 0, 0 ) );
}
}
RuntimeMPI::RuntimeMPI()
{
}
RuntimeMPI::~RuntimeMPI()
{
// Zoltan resources must be deleted before we call MPI_Finalize.
zoltan.release();
}
zoltanReturns RuntimeMPI::computePartition()
{
zoltanReturns zr;
void* grid = const_cast<void*>( reinterpret_cast<const void*>( grid_manager->c_grid() ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Num_Obj_Fn( ZoltanGrid::getNumberOfObjects, grid ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Obj_List_Fn( ZoltanGrid::getCellList, grid ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Num_Edges_Multi_Fn( ZoltanGrid::getNumberOfEdgesMulti, grid ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Edge_List_Multi_Fn( ZoltanGrid::getEdgeListMulti, grid ) );
ZOLTAN_SAFE_CALL(
zoltan->LB_Partition( zr.changes, /* 1 if partitioning was changed, 0 otherwise */
zr.numGidEntries, /* Number of integers used for a global ID */
zr.numLidEntries, /* Number of integers used for a local ID */
zr.numImport, /* Number of vertices to be sent to me */
zr.importGlobalGids,/* Global IDs of vertices to be sent to me */
zr.importLocalGids, /* Local IDs of vertices to be sent to me */
zr.importProcs, /* Process rank for source of each incoming vertex */
zr.importToPart, /* New partition for each incoming vertex */
zr.numExport, /* Number of vertices I must send to other processes*/
zr.exportGlobalGids,/* Global IDs of the vertices I must send */
zr.exportLocalGids, /* Local IDs of the vertices I must send */
zr.exportProcs, /* Process to which I send each of the vertices */
zr.exportToPart ) ); /* Partition to which each vertex will belong */
return zr;
}
} // namespace equlle
<commit_msg>Remember to initializeZoltan in RuntimeMPI::ctor.<commit_after>#include "equelle/RuntimeMPI.hpp"
#include <iostream>
#include <mpi.h>
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <zoltan_cpp.h>
#pragma GCC diagnostic pop
#include <opm/core/grid/GridManager.hpp>
#include "EquelleRuntimeCPU.hpp"
#include "equelle/mpiutils.hpp"
namespace equelle {
void RuntimeMPI::initializeZoltan()
{
zoltan.reset( new Zoltan( MPI_COMM_WORLD ) );
// Use hypergraph partitioning
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "LB_METHOD", "GRAPH" ) );
// Partition everything without concern for cost.
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "LB_APPROACH", "PARTITION" ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "PHG_EDGE_SIZE_THRESHOLD", "1.0" ) );
#ifndef EQUELLE_DEBUG
// Check that the query functions return valid input data; 0 or 1. (This slows performance; intended for debugging.)
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "CHECK_HYPERGRAPH", "1" ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Param( "DEBUG_LEVEL", "2" ) );
#endif
}
void RuntimeMPI::initializeGrid()
{
if ( getMPIRank() == 0 ) {
grid_manager.reset( new Opm::GridManager( 6, 1 ) );
} else {
grid_manager.reset( new Opm::GridManager( 0, 0 ) );
}
}
RuntimeMPI::RuntimeMPI()
{
initializeZoltan();
initializeGrid();
}
RuntimeMPI::~RuntimeMPI()
{
// Zoltan resources must be deleted before we call MPI_Finalize.
zoltan.release();
}
zoltanReturns RuntimeMPI::computePartition()
{
zoltanReturns zr;
void* grid = const_cast<void*>( reinterpret_cast<const void*>( grid_manager->c_grid() ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Num_Obj_Fn( ZoltanGrid::getNumberOfObjects, grid ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Obj_List_Fn( ZoltanGrid::getCellList, grid ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Num_Edges_Multi_Fn( ZoltanGrid::getNumberOfEdgesMulti, grid ) );
ZOLTAN_SAFE_CALL( zoltan->Set_Edge_List_Multi_Fn( ZoltanGrid::getEdgeListMulti, grid ) );
ZOLTAN_SAFE_CALL(
zoltan->LB_Partition( zr.changes, /* 1 if partitioning was changed, 0 otherwise */
zr.numGidEntries, /* Number of integers used for a global ID */
zr.numLidEntries, /* Number of integers used for a local ID */
zr.numImport, /* Number of vertices to be sent to me */
zr.importGlobalGids,/* Global IDs of vertices to be sent to me */
zr.importLocalGids, /* Local IDs of vertices to be sent to me */
zr.importProcs, /* Process rank for source of each incoming vertex */
zr.importToPart, /* New partition for each incoming vertex */
zr.numExport, /* Number of vertices I must send to other processes*/
zr.exportGlobalGids,/* Global IDs of the vertices I must send */
zr.exportLocalGids, /* Local IDs of the vertices I must send */
zr.exportProcs, /* Process to which I send each of the vertices */
zr.exportToPart ) ); /* Partition to which each vertex will belong */
return zr;
}
} // namespace equlle
<|endoftext|> |
<commit_before>/** Copyright © 2013, Vladimir Lapshin.
*
* 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.
*
* \brief Trie unit test.
* \author Vladimir Lapshin.
*/
#include <stdint.h>
#include <sstream>
#include <string>
#include <boost/test/unit_test.hpp>
#include "trie.h"
#include "compact_trie.h"
#include "flex_transitions.h"
#include "serializer.h"
namespace {
// Trie type definitions.
typedef strutext::automata::FlexTransitions<char> Trans;
typedef strutext::automata::Trie<Trans, uint64_t> FlexTrie;
typedef strutext::automata::AttrFsmSerializer<FlexTrie> Serializer;
typedef strutext::automata::CompactTrie<Trans, uint64_t> CompactFlexTrie;
// Utilities.
struct TrieUtils {
// Search chain in the passed trie.
static bool CheckCnainInTrie(const std::string& chain, FlexTrie::Attribute attr, const FlexTrie& trie) {
strutext::automata::StateId state = strutext::automata::kStartState;
for (std::string::const_iterator it = chain.begin(); it != chain.end(); ++it) {
state = trie.Go(state, *it);
if (state == strutext::automata::kInvalidState) {
return false;
}
}
// Check if we are in the acceptable state.
if (not trie.IsAcceptable(state)) {
return false;
}
// Check is there the passed value in the attribute list.
const FlexTrie::AttributeList& attrs = trie.GetStateAttributes(state);
for (FlexTrie::AttributeList::const_iterator attribute_it = attrs.begin(); attribute_it != attrs.end(); ++attribute_it) {
if (*attribute_it == attr) {
return true;
}
}
// The chain hasn't been found.
return false;
}
// Adding a chain in the trie.
static void AddChainToTrie(const std::string& chain, FlexTrie::Attribute attr, FlexTrie& trie) {
trie.AddChain(chain.begin(), chain.end(), attr);
}
};
} // namespace.
// Simple work test.
BOOST_AUTO_TEST_CASE(Automata_Trie_SimpleCheck) {
// Create trie and add chains into it.
FlexTrie trie;
TrieUtils::AddChainToTrie("hello", 1, trie);
TrieUtils::AddChainToTrie("bye", 2, trie);
// Check the chains are in the trie.
BOOST_CHECK(TrieUtils::CheckCnainInTrie("hello", 1, trie));
BOOST_CHECK(TrieUtils::CheckCnainInTrie("bye", 2, trie));
}
// Serialization test.
BOOST_AUTO_TEST_CASE(Automata_Trie_Serialize) {
// Create trie and add chains into it.
FlexTrie trie;
TrieUtils::AddChainToTrie("hello", 1, trie);
TrieUtils::AddChainToTrie("bye", 2, trie);
// The stream to serialize chains.
std::stringstream ss;
// Serialize the trie.
Serializer::Serialize(trie, ss);
// Deserialize the trie.
FlexTrie trie1;
Serializer::Deserialize(trie1, ss);
// Check the chains are in the trie.
BOOST_CHECK(TrieUtils::CheckCnainInTrie("hello", 1, trie1));
BOOST_CHECK(TrieUtils::CheckCnainInTrie("bye", 2, trie1));
}
// Serialization test.
BOOST_AUTO_TEST_CASE(Automata_CompactTrie_Check) {
// Create trie and add chains into it.
FlexTrie trie;
TrieUtils::AddChainToTrie("aa", 1, trie);
TrieUtils::AddChainToTrie("ab", 2, trie);
TrieUtils::AddChainToTrie("ba", 3, trie);
TrieUtils::AddChainToTrie("bb", 4, trie);
TrieUtils::AddChainToTrie("xxxbb", 5, trie);
TrieUtils::AddChainToTrie("b", 6, trie);
TrieUtils::AddChainToTrie("x", 7, trie);
TrieUtils::AddChainToTrie("cxbb", 8, trie);
TrieUtils::AddChainToTrie("aa", 9, trie);
CompactFlexTrie compact_trie(trie);
}
<commit_msg>Фикс в сборке с компактным траем.<commit_after>/** Copyright © 2013, Vladimir Lapshin.
*
* 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.
*
* \brief Trie unit test.
* \author Vladimir Lapshin.
*/
#include <stdint.h>
#include <sstream>
#include <string>
#include <boost/test/unit_test.hpp>
#include "trie.h"
#include "flex_transitions.h"
#include "serializer.h"
namespace {
// Trie type definitions.
typedef strutext::automata::FlexTransitions<char> Trans;
typedef strutext::automata::Trie<Trans, uint64_t> FlexTrie;
typedef strutext::automata::AttrFsmSerializer<FlexTrie> Serializer;
// Utilities.
struct TrieUtils {
// Search chain in the passed trie.
static bool CheckCnainInTrie(const std::string& chain, FlexTrie::Attribute attr, const FlexTrie& trie) {
strutext::automata::StateId state = strutext::automata::kStartState;
for (std::string::const_iterator it = chain.begin(); it != chain.end(); ++it) {
state = trie.Go(state, *it);
if (state == strutext::automata::kInvalidState) {
return false;
}
}
// Check if we are in the acceptable state.
if (not trie.IsAcceptable(state)) {
return false;
}
// Check is there the passed value in the attribute list.
const FlexTrie::AttributeList& attrs = trie.GetStateAttributes(state);
for (FlexTrie::AttributeList::const_iterator attribute_it = attrs.begin(); attribute_it != attrs.end(); ++attribute_it) {
if (*attribute_it == attr) {
return true;
}
}
// The chain hasn't been found.
return false;
}
// Adding a chain in the trie.
static void AddChainToTrie(const std::string& chain, FlexTrie::Attribute attr, FlexTrie& trie) {
trie.AddChain(chain.begin(), chain.end(), attr);
}
};
} // namespace.
// Simple work test.
BOOST_AUTO_TEST_CASE(Automata_Trie_SimpleCheck) {
// Create trie and add chains into it.
FlexTrie trie;
TrieUtils::AddChainToTrie("hello", 1, trie);
TrieUtils::AddChainToTrie("bye", 2, trie);
// Check the chains are in the trie.
BOOST_CHECK(TrieUtils::CheckCnainInTrie("hello", 1, trie));
BOOST_CHECK(TrieUtils::CheckCnainInTrie("bye", 2, trie));
}
// Serialization test.
BOOST_AUTO_TEST_CASE(Automata_Trie_Serialize) {
// Create trie and add chains into it.
FlexTrie trie;
TrieUtils::AddChainToTrie("hello", 1, trie);
TrieUtils::AddChainToTrie("bye", 2, trie);
// The stream to serialize chains.
std::stringstream ss;
// Serialize the trie.
Serializer::Serialize(trie, ss);
// Deserialize the trie.
FlexTrie trie1;
Serializer::Deserialize(trie1, ss);
// Check the chains are in the trie.
BOOST_CHECK(TrieUtils::CheckCnainInTrie("hello", 1, trie1));
BOOST_CHECK(TrieUtils::CheckCnainInTrie("bye", 2, trie1));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vendorbase.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: ihi $ $Date: 2007-11-26 18:04:40 $
*
* 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
*
************************************************************************/
#if !defined INCLUDED_JFW_PLUGIN_VENDORBASE_HXX
#define INCLUDED_JFW_PLUGIN_VENDORBASE_HXX
#include "rtl/ustring.hxx"
#include "rtl/ref.hxx"
#include "osl/endian.h"
#include "salhelper/simplereferenceobject.hxx"
#include <vector>
namespace jfw_plugin
{
//Used by subclasses of VendorBase to build paths to Java runtime
#if defined SPARC
#define JFW_PLUGIN_ARCH "sparc"
#elif defined INTEL
#define JFW_PLUGIN_ARCH "i386"
#elif defined POWERPC64
#define JFW_PLUGIN_ARCH "ppc64"
#elif defined POWERPC
#define JFW_PLUGIN_ARCH "ppc"
#elif defined MIPS
#ifdef OSL_BIGENDIAN
# define JFW_PLUGIN_ARCH "mips"
#else
# define JFW_PLUGIN_ARCH "mips32"
#endif
#elif defined S390
#define JFW_PLUGIN_ARCH "s390"
#elif defined X86_64
#define JFW_PLUGIN_ARCH "amd64"
#elif defined ARM
#define JFW_PLUGIN_ARCH "arm"
#else // SPARC, INTEL, POWERPC, MIPS, ARM
#error unknown plattform
#endif // SPARC, INTEL, POWERPC, MIPS, ARM
class MalformedVersionException
{
public:
MalformedVersionException();
MalformedVersionException(const MalformedVersionException &);
virtual ~MalformedVersionException();
MalformedVersionException & operator =(const MalformedVersionException &);
};
class VendorBase: public salhelper::SimpleReferenceObject
{
public:
VendorBase();
/* returns relativ paths to the java executable as
file URLs.
For example "bin/java.exe". You need
to implement this function in a derived class, if
the paths differ. this implmentation provides for
Windows "bin/java.exe" and for Unix "bin/java".
The paths are relative file URLs. That is, they always
contain '/' even on windows. The paths are relative
to the installation directory of a JRE.
The signature of this function must correspond to
getJavaExePaths_func.
*/
static char const* const * getJavaExePaths(int* size);
/* creates an instance of this class. MUST be overridden
in a derived class.
####################################################
OVERRIDE in derived class
###################################################
@param
Key - value pairs of the system properties of the JRE.
*/
static rtl::Reference<VendorBase> createInstance();
/* called automatically on the instance created by createInstance.
@return
true - the object could completely initialize.
false - the object could not completly initialize. In this case
it will be discarded by the caller.
*/
virtual bool initialize(
std::vector<std::pair<rtl::OUString, rtl::OUString> > props);
/* returns relative file URLs to the runtime library.
For example "/bin/client/jvm.dll"
*/
virtual char const* const* getRuntimePaths(int* size);
virtual char const* const* getLibraryPaths(int* size);
virtual const rtl::OUString & getVendor() const;
virtual const rtl::OUString & getVersion() const;
virtual const rtl::OUString & getHome() const;
virtual const rtl::OUString & getRuntimeLibrary() const;
virtual const rtl::OUString & getLibraryPaths() const;
virtual bool supportsAccessibility() const;
/* determines if prior to running java something has to be done,
like setting the LD_LIBRARY_PATH. This implementation checks
if an LD_LIBRARY_PATH (getLD_LIBRARY_PATH) needs to be set and
if so, needsRestart returns true.
*/
virtual bool needsRestart() const;
/* compares versions of this vendor. MUST be overridden
in a derived class.
####################################################
OVERRIDE in derived class
###################################################
@return
0 this.version == sSecond
1 this.version > sSecond
-1 this.version < sSEcond
@throw
MalformedVersionException if the version string was not recognized.
*/
virtual int compareVersions(const rtl::OUString& sSecond) const;
protected:
rtl::OUString m_sVendor;
rtl::OUString m_sVersion;
rtl::OUString m_sHome;
rtl::OUString m_sRuntimeLibrary;
rtl::OUString m_sLD_LIBRARY_PATH;
bool m_bAccessibility;
typedef rtl::Reference<VendorBase> (* createInstance_func) ();
friend rtl::Reference<VendorBase> createInstance(
createInstance_func pFunc,
std::vector<std::pair<rtl::OUString, rtl::OUString> > properties);
};
}
#endif
<commit_msg>INTEGRATION: CWS ia64port01_DEV300 (1.9.4); FILE MERGED 2008/01/04 19:05:43 cmc 1.9.4.1: #i84999# add ia64<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vendorbase.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2008-02-27 10:03:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#if !defined INCLUDED_JFW_PLUGIN_VENDORBASE_HXX
#define INCLUDED_JFW_PLUGIN_VENDORBASE_HXX
#include "rtl/ustring.hxx"
#include "rtl/ref.hxx"
#include "osl/endian.h"
#include "salhelper/simplereferenceobject.hxx"
#include <vector>
namespace jfw_plugin
{
//Used by subclasses of VendorBase to build paths to Java runtime
#if defined SPARC
#define JFW_PLUGIN_ARCH "sparc"
#elif defined INTEL
#define JFW_PLUGIN_ARCH "i386"
#elif defined POWERPC64
#define JFW_PLUGIN_ARCH "ppc64"
#elif defined POWERPC
#define JFW_PLUGIN_ARCH "ppc"
#elif defined MIPS
#ifdef OSL_BIGENDIAN
# define JFW_PLUGIN_ARCH "mips"
#else
# define JFW_PLUGIN_ARCH "mips32"
#endif
#elif defined S390
#define JFW_PLUGIN_ARCH "s390"
#elif defined X86_64
#define JFW_PLUGIN_ARCH "amd64"
#elif defined ARM
#define JFW_PLUGIN_ARCH "arm"
#elif defined IA64
#define JFW_PLUGIN_ARCH "ia64"
#else // SPARC, INTEL, POWERPC, MIPS, ARM
#error unknown plattform
#endif // SPARC, INTEL, POWERPC, MIPS, ARM
class MalformedVersionException
{
public:
MalformedVersionException();
MalformedVersionException(const MalformedVersionException &);
virtual ~MalformedVersionException();
MalformedVersionException & operator =(const MalformedVersionException &);
};
class VendorBase: public salhelper::SimpleReferenceObject
{
public:
VendorBase();
/* returns relativ paths to the java executable as
file URLs.
For example "bin/java.exe". You need
to implement this function in a derived class, if
the paths differ. this implmentation provides for
Windows "bin/java.exe" and for Unix "bin/java".
The paths are relative file URLs. That is, they always
contain '/' even on windows. The paths are relative
to the installation directory of a JRE.
The signature of this function must correspond to
getJavaExePaths_func.
*/
static char const* const * getJavaExePaths(int* size);
/* creates an instance of this class. MUST be overridden
in a derived class.
####################################################
OVERRIDE in derived class
###################################################
@param
Key - value pairs of the system properties of the JRE.
*/
static rtl::Reference<VendorBase> createInstance();
/* called automatically on the instance created by createInstance.
@return
true - the object could completely initialize.
false - the object could not completly initialize. In this case
it will be discarded by the caller.
*/
virtual bool initialize(
std::vector<std::pair<rtl::OUString, rtl::OUString> > props);
/* returns relative file URLs to the runtime library.
For example "/bin/client/jvm.dll"
*/
virtual char const* const* getRuntimePaths(int* size);
virtual char const* const* getLibraryPaths(int* size);
virtual const rtl::OUString & getVendor() const;
virtual const rtl::OUString & getVersion() const;
virtual const rtl::OUString & getHome() const;
virtual const rtl::OUString & getRuntimeLibrary() const;
virtual const rtl::OUString & getLibraryPaths() const;
virtual bool supportsAccessibility() const;
/* determines if prior to running java something has to be done,
like setting the LD_LIBRARY_PATH. This implementation checks
if an LD_LIBRARY_PATH (getLD_LIBRARY_PATH) needs to be set and
if so, needsRestart returns true.
*/
virtual bool needsRestart() const;
/* compares versions of this vendor. MUST be overridden
in a derived class.
####################################################
OVERRIDE in derived class
###################################################
@return
0 this.version == sSecond
1 this.version > sSecond
-1 this.version < sSEcond
@throw
MalformedVersionException if the version string was not recognized.
*/
virtual int compareVersions(const rtl::OUString& sSecond) const;
protected:
rtl::OUString m_sVendor;
rtl::OUString m_sVersion;
rtl::OUString m_sHome;
rtl::OUString m_sRuntimeLibrary;
rtl::OUString m_sLD_LIBRARY_PATH;
bool m_bAccessibility;
typedef rtl::Reference<VendorBase> (* createInstance_func) ();
friend rtl::Reference<VendorBase> createInstance(
createInstance_func pFunc,
std::vector<std::pair<rtl::OUString, rtl::OUString> > properties);
};
}
#endif
<|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/system_monitor.h"
#include "testing/gtest/include/gtest/gtest.h"
class PowerTest : public base::SystemMonitor::PowerObserver {
public:
PowerTest()
: battery_(false),
power_state_changes_(0),
suspends_(0),
resumes_(0) {};
// PowerObserver callbacks.
void OnPowerStateChange(base::SystemMonitor*) { power_state_changes_++; };
void OnSuspend(base::SystemMonitor*) { suspends_++; };
void OnResume(base::SystemMonitor*) { resumes_++; };
// Test status counts.
bool battery() { return battery_; }
int power_state_changes() { return power_state_changes_; }
int suspends() { return suspends_; }
int resumes() { return resumes_; }
private:
bool battery_; // Do we currently think we're on battery power.
int power_state_changes_; // Count of OnPowerStateChange notifications.
int suspends_; // Count of OnSuspend notifications.
int resumes_; // Count of OnResume notifications.
};
TEST(SystemMonitor, PowerNotifications) {
const int kObservers = 5;
base::SystemMonitor* monitor = base::SystemMonitor::Get();
PowerTest test[kObservers];
for (int index = 0; index < kObservers; ++index)
monitor->AddObserver(&test[index]);
// Send a bunch of power changes. Since the battery power hasn't
// actually changed, we shouldn't get notifications.
for (int index = 0; index < 5; index++) {
monitor->ProcessPowerMessage(base::SystemMonitor::POWER_STATE_EVENT);
EXPECT_EQ(test[0].power_state_changes(), 0);
}
// Sending resume when not suspended should have no effect.
monitor->ProcessPowerMessage(base::SystemMonitor::RESUME_EVENT);
EXPECT_EQ(test[0].resumes(), 0);
// Pretend we suspended.
monitor->ProcessPowerMessage(base::SystemMonitor::SUSPEND_EVENT);
EXPECT_EQ(test[0].suspends(), 1);
// Send a second suspend notification. This should be suppressed.
monitor->ProcessPowerMessage(base::SystemMonitor::SUSPEND_EVENT);
EXPECT_EQ(test[0].suspends(), 1);
// Pretend we were awakened.
monitor->ProcessPowerMessage(base::SystemMonitor::RESUME_EVENT);
EXPECT_EQ(test[0].resumes(), 1);
// Send a duplicate resume notification. This should be suppressed.
monitor->ProcessPowerMessage(base::SystemMonitor::RESUME_EVENT);
EXPECT_EQ(test[0].resumes(), 1);
}
<commit_msg>Fix unit test for system monitor. Not sure how I missed this!<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/system_monitor.h"
#include "testing/gtest/include/gtest/gtest.h"
class PowerTest : public base::SystemMonitor::PowerObserver {
public:
PowerTest()
: battery_(false),
power_state_changes_(0),
suspends_(0),
resumes_(0) {};
// PowerObserver callbacks.
void OnPowerStateChange(base::SystemMonitor*) { power_state_changes_++; };
void OnSuspend(base::SystemMonitor*) { suspends_++; };
void OnResume(base::SystemMonitor*) { resumes_++; };
// Test status counts.
bool battery() { return battery_; }
int power_state_changes() { return power_state_changes_; }
int suspends() { return suspends_; }
int resumes() { return resumes_; }
private:
bool battery_; // Do we currently think we're on battery power.
int power_state_changes_; // Count of OnPowerStateChange notifications.
int suspends_; // Count of OnSuspend notifications.
int resumes_; // Count of OnResume notifications.
};
TEST(SystemMonitor, PowerNotifications) {
const int kObservers = 5;
// Initialize a message loop for this to run on.
MessageLoop loop;
// Initialize time() since it registers as a SystemMonitor observer.
base::Time now = base::Time::Now();
base::SystemMonitor* monitor = base::SystemMonitor::Get();
PowerTest test[kObservers];
for (int index = 0; index < kObservers; ++index)
monitor->AddObserver(&test[index]);
// Send a bunch of power changes. Since the battery power hasn't
// actually changed, we shouldn't get notifications.
for (int index = 0; index < 5; index++) {
monitor->ProcessPowerMessage(base::SystemMonitor::POWER_STATE_EVENT);
EXPECT_EQ(test[0].power_state_changes(), 0);
}
// Sending resume when not suspended should have no effect.
monitor->ProcessPowerMessage(base::SystemMonitor::RESUME_EVENT);
loop.RunAllPending();
EXPECT_EQ(test[0].resumes(), 0);
// Pretend we suspended.
monitor->ProcessPowerMessage(base::SystemMonitor::SUSPEND_EVENT);
loop.RunAllPending();
EXPECT_EQ(test[0].suspends(), 1);
// Send a second suspend notification. This should be suppressed.
monitor->ProcessPowerMessage(base::SystemMonitor::SUSPEND_EVENT);
loop.RunAllPending();
EXPECT_EQ(test[0].suspends(), 1);
// Pretend we were awakened.
monitor->ProcessPowerMessage(base::SystemMonitor::RESUME_EVENT);
loop.RunAllPending();
EXPECT_EQ(test[0].resumes(), 1);
// Send a duplicate resume notification. This should be suppressed.
monitor->ProcessPowerMessage(base::SystemMonitor::RESUME_EVENT);
loop.RunAllPending();
EXPECT_EQ(test[0].resumes(), 1);
}
<|endoftext|> |
<commit_before>#include "CommandLine.h"
#include "Command.h"
#include "InternalCommands.h"
#include "Environment.h"
#include "Script.h"
#include "Arg.h"
#include "StringArray.h"
#include "Where.h"
#include "TmpFile.h"
#include "VarString.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include "Feeder.h"
#include "GlueString.h"
using namespace std;
CommandLine::CommandLine(Feeder *f, Environment *env) : Element(f,env)
{
m_pipe[0] = -1;
m_pipe[1] = -1;
m_pipe_prev = -1;
m_is_strout = false;
m_if = false;
m_is_wait = false;
}
CommandLine::~CommandLine()
{
}
/* parse of command line, where command line means
* the combination of one command, args, and where.
m_nodes: command arg arg ...
or
m_nodes: string procedure
*/
bool CommandLine::parse(void)
{
m_feeder->getPos(&m_start_line, &m_start_char);
// start from a literal or an array of literals
if(add(new StringArray(m_feeder,m_env))){
m_feeder->getPos(&m_end_line, &m_end_char);
m_is_strout = true;
return true;
}
// start from a command
if(!add(new Command(m_feeder,m_env)))
return false;
if(!m_feeder->comment() && !m_feeder->atNewLine()){
m_feeder->blank();
parseArgs();
}
auto *c = (Command *)m_nodes[0];
if(c->m_is_internal && c->m_name == "wait"){
m_is_wait = true;
}
m_feeder->getPos(&m_end_line, &m_end_char);
return true;
}
void CommandLine::parseArgs(void)
{
while(add(new Arg(m_feeder,m_env))){
if(m_feeder->comment() || m_feeder->atNewLine())
return;
m_feeder->blank();
}
}
void CommandLine::parentPipeProc(void)
{
if(m_pipe_prev >= 0)
close(m_pipe_prev);
m_pipe_prev = m_pipe[0];
close(m_pipe[1]);
}
void CommandLine::childPipeProc(void)
{
if(m_pipe[1] >= 0)
close(m_pipe[0]);
if(m_pipe_prev > 0) {
dup2(m_pipe_prev, 0);
close(m_pipe_prev);
}
if(m_pipe[1] > 1){
dup2(m_pipe[1], 1);
close(m_pipe[1]);
}
}
void CommandLine::execErrorExit(void)
{
m_error_msg = "Command error";
m_exit_status = 127;
throw this;
}
int CommandLine::exec(void)
{
cout << flush;
if(! eval())
return -1;
int pid = fork();
if(pid < 0)
exit(1);
if (pid == 0){//child
if(m_env->m_v_opt)
cerr << "+ pid " << getpid() << " fork " << endl;
m_env->m_level++;
childPipeProc();
//The child process should not access to the source code.
m_feeder->close();
//open a file or a string variable
if(m_outfile != NULL){
if(m_outfile->exec() != 0){
m_error_msg = "Cannot prepare file";
m_exit_status = 1;
throw this;
}
}else if(m_outstr != NULL){
if(m_outstr->exec() != 0){
m_error_msg = "Cannot prepare file";
m_exit_status = 1;
throw this;
}
}
if(m_is_strout){
execCommandLine();
}else if(((Command *)m_nodes[0])->m_is_proc){
execProcedure();
}else{
execCommandLine();
}
execErrorExit();
}
/*parent*/
parentPipeProc();
return pid;
}
const char** CommandLine::makeArgv(void)
{
if(m_is_strout){
return ((StringArray *)m_nodes[0])->makeArgv();
}
auto argv = new const char* [m_nodes.size() + 2];
Command *com = (Command *)m_nodes[0];
argv[0] = com->getStr();
int skip = 0;
// in the case of proc, argv[0] is glue and argv[1] is
// the procedure file.
if(com->m_is_proc){
skip = 1;
argv[1] = argv[0];
argv[0] = m_env->m_glue_path.c_str();
}
for (int i=1;i < (int)m_nodes.size();i++){
argv[i+skip] = ((Arg *)m_nodes[i])->getEvaledString();
}
argv[m_nodes.size()+skip] = NULL;
return argv;
}
void CommandLine::execCommandLine(void)
{
auto argv = makeArgv();
if(m_env->m_v_opt)
cerr << "+ pid " << getpid() << " exec line "
<< m_start_line << " " << argv[0] << endl;
if(m_is_strout){ // execution of string output
InternalCommands::exec(argv,m_env,m_feeder,this);
}else if(((Command *)m_nodes[0])->m_is_internal){// execution of internal command
InternalCommands::exec(argv,m_env,m_feeder,this);
}else{
execv(argv[0],(char **)argv);
}
}
void CommandLine::execProcedure(void)
{
auto argv = makeArgv();
// argv[1]: script file
// argv[2,3,...]: args
//
ifstream ifs(argv[1]);
Feeder feeder(&ifs);
m_env->subshellInit(argv);
/*
m_env->m_pid = getpid();
//set args
m_env->m_args.clear();
int p = 2;
while(argv[p] != NULL){
m_env->m_args.push_back(argv[p]);
p++;
}
*/
Script s(&feeder,m_env);
s.parse();
int es = s.exec();
m_env->removeFiles();
exit(es);
/*
// send the shell level for the case where the child is glue.
string lv = "GLUELEVEL=" + to_string(m_env->m_level);
if(putenv((char *)lv.c_str()) != 0){
m_error_msg = "putenv error";
m_exit_status = 1;
throw this;
}
if(m_env->m_v_opt)
cerr << "+ pid " << getpid() << " exec line "
<< m_start_line << " " << argv[0] << endl;
execv(argv[0],(char **)argv);
*/
}
bool CommandLine::eval(void)
{
for(auto s : m_nodes){
if( ! s->eval() ){
m_error_msg = "evaluation of args failed";
throw this;
}
}
return true;
}
void CommandLine::setPipe(int *pip,int prev)
{
m_pipe[0] = pip[0];
m_pipe[1] = pip[1];
m_pipe_prev = prev;
}
<commit_msg>Clean up<commit_after>#include "CommandLine.h"
#include "Command.h"
#include "InternalCommands.h"
#include "Environment.h"
#include "Script.h"
#include "Arg.h"
#include "StringArray.h"
#include "Where.h"
#include "TmpFile.h"
#include "VarString.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include "Feeder.h"
#include "GlueString.h"
using namespace std;
CommandLine::CommandLine(Feeder *f, Environment *env) : Element(f,env)
{
m_pipe[0] = -1;
m_pipe[1] = -1;
m_pipe_prev = -1;
m_is_strout = false;
m_if = false;
m_is_wait = false;
}
CommandLine::~CommandLine()
{
}
/* parse of command line, where command line means
* the combination of one command, args, and where.
m_nodes: command arg arg ...
or
m_nodes: string procedure
*/
bool CommandLine::parse(void)
{
m_feeder->getPos(&m_start_line, &m_start_char);
// start from a literal or an array of literals
if(add(new StringArray(m_feeder,m_env))){
m_feeder->getPos(&m_end_line, &m_end_char);
m_is_strout = true;
return true;
}
// start from a command
if(!add(new Command(m_feeder,m_env)))
return false;
if(!m_feeder->comment() && !m_feeder->atNewLine()){
m_feeder->blank();
parseArgs();
}
auto *c = (Command *)m_nodes[0];
if(c->m_is_internal && c->m_name == "wait"){
m_is_wait = true;
}
m_feeder->getPos(&m_end_line, &m_end_char);
return true;
}
void CommandLine::parseArgs(void)
{
while(add(new Arg(m_feeder,m_env))){
if(m_feeder->comment() || m_feeder->atNewLine())
return;
m_feeder->blank();
}
}
void CommandLine::parentPipeProc(void)
{
if(m_pipe_prev >= 0)
close(m_pipe_prev);
m_pipe_prev = m_pipe[0];
close(m_pipe[1]);
}
void CommandLine::childPipeProc(void)
{
if(m_pipe[1] >= 0)
close(m_pipe[0]);
if(m_pipe_prev > 0) {
dup2(m_pipe_prev, 0);
close(m_pipe_prev);
}
if(m_pipe[1] > 1){
dup2(m_pipe[1], 1);
close(m_pipe[1]);
}
}
void CommandLine::execErrorExit(void)
{
m_error_msg = "Command error";
m_exit_status = 127;
throw this;
}
int CommandLine::exec(void)
{
cout << flush;
if(! eval())
return -1;
int pid = fork();
if(pid < 0)
exit(1);
if (pid == 0){//child
if(m_env->m_v_opt)
cerr << "+ pid " << getpid() << " fork " << endl;
m_env->m_level++;
childPipeProc();
//The child process should not access to the source code.
m_feeder->close();
//open a file or a string variable
if(m_outfile != NULL){
if(m_outfile->exec() != 0){
m_error_msg = "Cannot prepare file";
m_exit_status = 1;
throw this;
}
}else if(m_outstr != NULL){
if(m_outstr->exec() != 0){
m_error_msg = "Cannot prepare file";
m_exit_status = 1;
throw this;
}
}
if(m_is_strout){
execCommandLine();
}else if(((Command *)m_nodes[0])->m_is_proc){
execProcedure();
}else{
execCommandLine();
}
execErrorExit();
}
/*parent*/
parentPipeProc();
return pid;
}
const char** CommandLine::makeArgv(void)
{
if(m_is_strout){
return ((StringArray *)m_nodes[0])->makeArgv();
}
auto argv = new const char* [m_nodes.size() + 2];
Command *com = (Command *)m_nodes[0];
argv[0] = com->getStr();
int skip = 0;
// in the case of proc, argv[0] is glue and argv[1] is
// the procedure file.
if(com->m_is_proc){
skip = 1;
argv[1] = argv[0];
argv[0] = m_env->m_glue_path.c_str();
}
for (int i=1;i < (int)m_nodes.size();i++){
argv[i+skip] = ((Arg *)m_nodes[i])->getEvaledString();
}
argv[m_nodes.size()+skip] = NULL;
return argv;
}
void CommandLine::execCommandLine(void)
{
auto argv = makeArgv();
if(m_env->m_v_opt)
cerr << "+ pid " << getpid() << " exec line "
<< m_start_line << " " << argv[0] << endl;
if(m_is_strout){ // execution of string output
InternalCommands::exec(argv,m_env,m_feeder,this);
}else if(((Command *)m_nodes[0])->m_is_internal){// execution of internal command
InternalCommands::exec(argv,m_env,m_feeder,this);
}else{
execv(argv[0],(char **)argv);
}
}
void CommandLine::execProcedure(void)
{
auto argv = makeArgv();
// argv[1]: script file
// argv[2,3,...]: args
//
ifstream ifs(argv[1]);
Feeder feeder(&ifs);
m_env->subshellInit(argv);
Script s(&feeder,m_env);
s.parse();
s.exec();
}
bool CommandLine::eval(void)
{
for(auto s : m_nodes){
if( ! s->eval() ){
m_error_msg = "evaluation of args failed";
throw this;
}
}
return true;
}
void CommandLine::setPipe(int *pip,int prev)
{
m_pipe[0] = pip[0];
m_pipe[1] = pip[1];
m_pipe_prev = prev;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2020, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS 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 "config.h"
#include "sql_util.hh"
#include "column_namer.hh"
#include "log_search_table.hh"
const static std::string LOG_MSG_INSTANCE = "log_msg_instance";
static auto instance_name = intern_string::lookup("log_msg_instance");
static auto instance_meta = logline_value_meta(
instance_name, value_kind_t::VALUE_INTEGER, 0);
static auto empty = intern_string::lookup("", 0);
log_search_table::log_search_table(pcrepp pattern,
intern_string_t table_name)
: log_vtab_impl(table_name),
lst_regex(std::move(pattern)),
lst_instance(-1)
{
this->vi_supports_indexes = false;
this->get_columns_int(this->lst_cols);
}
void log_search_table::get_columns_int(std::vector<vtab_column> &cols)
{
column_namer cn;
cols.emplace_back(LOG_MSG_INSTANCE, SQLITE_INTEGER);
for (int lpc = 0; lpc < this->lst_regex.get_capture_count(); lpc++) {
std::string collator;
std::string colname;
int sqlite_type = SQLITE3_TEXT;
colname = cn.add_column(this->lst_regex.name_for_capture(lpc));
if (this->lst_regex.captures().size() ==
(size_t) this->lst_regex.get_capture_count()) {
auto iter = this->lst_regex.cap_begin() + lpc;
auto cap_re = this->lst_regex.get_pattern()
.substr(iter->c_begin, iter->length());
sqlite_type = guess_type_from_pcre(cap_re, collator);
switch (sqlite_type) {
case SQLITE_FLOAT:
this->lst_column_metas.emplace_back(
intern_string::lookup(colname),
value_kind_t::VALUE_FLOAT,
cols.size());
break;
case SQLITE_INTEGER:
this->lst_column_metas.emplace_back(
intern_string::lookup(colname),
value_kind_t::VALUE_INTEGER,
cols.size());
break;
default:
this->lst_column_metas.emplace_back(
intern_string::lookup(colname),
value_kind_t::VALUE_TEXT,
cols.size());
break;
}
}
cols.emplace_back(colname, sqlite_type, collator);
}
}
void
log_search_table::get_foreign_keys(std::vector<std::string> &keys_inout) const
{
log_vtab_impl::get_foreign_keys(keys_inout);
keys_inout.emplace_back("log_msg_instance");
}
bool log_search_table::next(log_cursor &lc, logfile_sub_source &lss)
{
if (lc.lc_curr_line == -1_vl) {
this->lst_instance = -1;
}
lc.lc_curr_line = lc.lc_curr_line + 1_vl;
lc.lc_sub_index = 0;
if (lc.lc_curr_line == (int) lss.text_line_count()) {
return true;
}
auto cl = lss.at(lc.lc_curr_line);
auto lf = lss.find(cl);
auto lf_iter = lf->begin() + cl;
if (!lf_iter->is_message()) {
return false;
}
string_attrs_t sa;
std::vector<logline_value> line_values;
lf->read_full_message(lf_iter, this->lst_current_line);
lf->get_format()->annotate(cl, this->lst_current_line, sa, line_values,
false);
pcre_input pi(this->lst_current_line.get_data(),
0,
this->lst_current_line.length());
if (!this->lst_regex.match(this->lst_match_context, pi)) {
return false;
}
this->lst_instance += 1;
return true;
}
void
log_search_table::extract(std::shared_ptr<logfile> lf, uint64_t line_number,
shared_buffer_ref &line,
std::vector<logline_value> &values)
{
values.emplace_back(instance_meta, this->lst_instance);
for (int lpc = 0; lpc < this->lst_regex.get_capture_count(); lpc++) {
auto cap = this->lst_match_context[lpc];
values.emplace_back(this->lst_column_metas[lpc], line,
line_range{cap->c_begin, cap->c_end});
}
}
<commit_msg>[build] unused var<commit_after>/**
* Copyright (c) 2020, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS 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 "config.h"
#include "sql_util.hh"
#include "column_namer.hh"
#include "log_search_table.hh"
const static std::string LOG_MSG_INSTANCE = "log_msg_instance";
static auto instance_name = intern_string::lookup("log_msg_instance");
static auto instance_meta = logline_value_meta(
instance_name, value_kind_t::VALUE_INTEGER, 0);
log_search_table::log_search_table(pcrepp pattern,
intern_string_t table_name)
: log_vtab_impl(table_name),
lst_regex(std::move(pattern)),
lst_instance(-1)
{
this->vi_supports_indexes = false;
this->get_columns_int(this->lst_cols);
}
void log_search_table::get_columns_int(std::vector<vtab_column> &cols)
{
column_namer cn;
cols.emplace_back(LOG_MSG_INSTANCE, SQLITE_INTEGER);
for (int lpc = 0; lpc < this->lst_regex.get_capture_count(); lpc++) {
std::string collator;
std::string colname;
int sqlite_type = SQLITE3_TEXT;
colname = cn.add_column(this->lst_regex.name_for_capture(lpc));
if (this->lst_regex.captures().size() ==
(size_t) this->lst_regex.get_capture_count()) {
auto iter = this->lst_regex.cap_begin() + lpc;
auto cap_re = this->lst_regex.get_pattern()
.substr(iter->c_begin, iter->length());
sqlite_type = guess_type_from_pcre(cap_re, collator);
switch (sqlite_type) {
case SQLITE_FLOAT:
this->lst_column_metas.emplace_back(
intern_string::lookup(colname),
value_kind_t::VALUE_FLOAT,
cols.size());
break;
case SQLITE_INTEGER:
this->lst_column_metas.emplace_back(
intern_string::lookup(colname),
value_kind_t::VALUE_INTEGER,
cols.size());
break;
default:
this->lst_column_metas.emplace_back(
intern_string::lookup(colname),
value_kind_t::VALUE_TEXT,
cols.size());
break;
}
}
cols.emplace_back(colname, sqlite_type, collator);
}
}
void
log_search_table::get_foreign_keys(std::vector<std::string> &keys_inout) const
{
log_vtab_impl::get_foreign_keys(keys_inout);
keys_inout.emplace_back("log_msg_instance");
}
bool log_search_table::next(log_cursor &lc, logfile_sub_source &lss)
{
if (lc.lc_curr_line == -1_vl) {
this->lst_instance = -1;
}
lc.lc_curr_line = lc.lc_curr_line + 1_vl;
lc.lc_sub_index = 0;
if (lc.lc_curr_line == (int) lss.text_line_count()) {
return true;
}
auto cl = lss.at(lc.lc_curr_line);
auto lf = lss.find(cl);
auto lf_iter = lf->begin() + cl;
if (!lf_iter->is_message()) {
return false;
}
string_attrs_t sa;
std::vector<logline_value> line_values;
lf->read_full_message(lf_iter, this->lst_current_line);
lf->get_format()->annotate(cl, this->lst_current_line, sa, line_values,
false);
pcre_input pi(this->lst_current_line.get_data(),
0,
this->lst_current_line.length());
if (!this->lst_regex.match(this->lst_match_context, pi)) {
return false;
}
this->lst_instance += 1;
return true;
}
void
log_search_table::extract(std::shared_ptr<logfile> lf, uint64_t line_number,
shared_buffer_ref &line,
std::vector<logline_value> &values)
{
values.emplace_back(instance_meta, this->lst_instance);
for (int lpc = 0; lpc < this->lst_regex.get_capture_count(); lpc++) {
auto cap = this->lst_match_context[lpc];
values.emplace_back(this->lst_column_metas[lpc], line,
line_range{cap->c_begin, cap->c_end});
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: vendorlist.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2005-01-25 15:19:28 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "vendorlist.hxx"
#include "gnujre.hxx"
#include "sunjre.hxx"
#include "otherjre.hxx"
#include "osl/thread.h"
#include <stdio.h>
using namespace com::sun::star::uno;
using namespace rtl;
namespace jfw_plugin
{
/* Note: The vendor strings must be UTF-8. For example, if
the string contains an a umlaut then it must be expressed
by "\xXX\xXX"
*/
BEGIN_VENDOR_MAP()
VENDOR_MAP_ENTRY("Sun Microsystems Inc.", SunInfo)
VENDOR_MAP_ENTRY("IBM Corporation", OtherInfo)
VENDOR_MAP_ENTRY("Blackdown Java-Linux Team", OtherInfo)
VENDOR_MAP_ENTRY("Apple Computer, Inc.", OtherInfo)
VENDOR_MAP_ENTRY("Free Software Foundation, Inc.", GnuInfo)
END_VENDOR_MAP()
Sequence<OUString> getVendorNames()
{
const size_t count = sizeof(gVendorMap) / sizeof (VendorSupportMapEntry) - 1;
OUString arNames[count];
for ( sal_Int32 pos = 0; pos < count; ++pos )
{
OString sVendor(gVendorMap[pos].sVendorName);
arNames[pos] = OStringToOUString(sVendor, RTL_TEXTENCODING_UTF8);
}
return Sequence<OUString>(arNames, count);
}
bool isVendorSupported(const rtl::OUString& sVendor)
{
Sequence<OUString> seqNames = getVendorNames();
const OUString * arNames = seqNames.getConstArray();
sal_Int32 count = seqNames.getLength();
for (int i = 0; i < count; i++)
{
if (sVendor.equals(arNames[i]))
return true;
}
#if OSL_DEBUG_LEVEL >= 2
OString sVendorName = OUStringToOString(sVendor, osl_getThreadTextEncoding());
fprintf(stderr, "[Java frameworksunjavaplugin.so]sunjavaplugin does not support vendor: %s.\n",
sVendorName.getStr());
#endif
return false;
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.28); FILE MERGED 2005/09/05 17:12:25 rt 1.4.28.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vendorlist.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:33:20 $
*
* 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 "vendorlist.hxx"
#include "gnujre.hxx"
#include "sunjre.hxx"
#include "otherjre.hxx"
#include "osl/thread.h"
#include <stdio.h>
using namespace com::sun::star::uno;
using namespace rtl;
namespace jfw_plugin
{
/* Note: The vendor strings must be UTF-8. For example, if
the string contains an a umlaut then it must be expressed
by "\xXX\xXX"
*/
BEGIN_VENDOR_MAP()
VENDOR_MAP_ENTRY("Sun Microsystems Inc.", SunInfo)
VENDOR_MAP_ENTRY("IBM Corporation", OtherInfo)
VENDOR_MAP_ENTRY("Blackdown Java-Linux Team", OtherInfo)
VENDOR_MAP_ENTRY("Apple Computer, Inc.", OtherInfo)
VENDOR_MAP_ENTRY("Free Software Foundation, Inc.", GnuInfo)
END_VENDOR_MAP()
Sequence<OUString> getVendorNames()
{
const size_t count = sizeof(gVendorMap) / sizeof (VendorSupportMapEntry) - 1;
OUString arNames[count];
for ( sal_Int32 pos = 0; pos < count; ++pos )
{
OString sVendor(gVendorMap[pos].sVendorName);
arNames[pos] = OStringToOUString(sVendor, RTL_TEXTENCODING_UTF8);
}
return Sequence<OUString>(arNames, count);
}
bool isVendorSupported(const rtl::OUString& sVendor)
{
Sequence<OUString> seqNames = getVendorNames();
const OUString * arNames = seqNames.getConstArray();
sal_Int32 count = seqNames.getLength();
for (int i = 0; i < count; i++)
{
if (sVendor.equals(arNames[i]))
return true;
}
#if OSL_DEBUG_LEVEL >= 2
OString sVendorName = OUStringToOString(sVendor, osl_getThreadTextEncoding());
fprintf(stderr, "[Java frameworksunjavaplugin.so]sunjavaplugin does not support vendor: %s.\n",
sVendorName.getStr());
#endif
return false;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: SlsQueueProcessor.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: pjunck $ $Date: 2004-10-28 13:28:46 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "SlsQueueProcessor.hxx"
namespace sd { namespace slidesorter { namespace cache {
//===== QueueProcessorBase ===================================================
QueueProcessorBase::QueueProcessorBase (void)
: mnTimeBetweenHighPriorityRequests (50/*ms*/),
mnTimeBetweenLowPriorityRequests (250/*ms*/)
{
maTimer.SetTimeoutHdl (LINK(this,QueueProcessorBase,ProcessRequest));
maTimer.SetTimeout (mnTimeBetweenHighPriorityRequests);
}
void QueueProcessorBase::Start (int nPriorityClass)
{
if ( ! maTimer.IsActive())
{
if (nPriorityClass == 0)
maTimer.SetTimeout (mnTimeBetweenHighPriorityRequests);
else
maTimer.SetTimeout (mnTimeBetweenLowPriorityRequests);
maTimer.Start();
}
}
void QueueProcessorBase::Stop (void)
{
if (maTimer.IsActive())
maTimer.Stop();
}
IMPL_LINK(QueueProcessorBase, ProcessRequest, Timer*, pTimer)
{
ProcessRequest();
return 1;
}
} } } // end of namespace ::sd::slidesorter::cache
<commit_msg>INTEGRATION: CWS impress31 (1.3.112); FILE MERGED 2005/01/25 10:51:34 af 1.3.112.1: #i40915# Supressing preview creation during full screen show.<commit_after>/*************************************************************************
*
* $RCSfile: SlsQueueProcessor.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2005-02-17 09:43:47 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "SlsQueueProcessor.hxx"
namespace sd { namespace slidesorter { namespace cache {
//===== QueueProcessorBase ===================================================
QueueProcessorBase::QueueProcessorBase (void)
: mnTimeBetweenHighPriorityRequests (50/*ms*/),
mnTimeBetweenLowPriorityRequests (250/*ms*/),
mnTimeBetweenRequestsWhenNotIdle (1000/*ms*/)
{
maTimer.SetTimeoutHdl (LINK(this,QueueProcessorBase,ProcessRequest));
maTimer.SetTimeout (mnTimeBetweenHighPriorityRequests);
}
void QueueProcessorBase::Start (int nPriorityClass)
{
if ( ! maTimer.IsActive())
{
if (nPriorityClass == 0)
maTimer.SetTimeout (mnTimeBetweenHighPriorityRequests);
else
maTimer.SetTimeout (mnTimeBetweenLowPriorityRequests);
maTimer.Start();
}
}
void QueueProcessorBase::Stop (void)
{
if (maTimer.IsActive())
maTimer.Stop();
}
IMPL_LINK(QueueProcessorBase, ProcessRequest, Timer*, pTimer)
{
ProcessRequest();
return 1;
}
} } } // end of namespace ::sd::slidesorter::cache
<|endoftext|> |
<commit_before>//
// src/mach-o/container.cc
// tbd
//
// Created by inoahdev on 4/24/17.
// Copyright © 2017 inoahdev. All rights reserved.
//
#include <cstdio>
#include <cstdlib>
#include "headers/symbol_table.h"
#include "container.h"
namespace macho {
container::open_result container::open(FILE *stream, long base, size_t size) noexcept {
this->stream = stream;
this->base = base;
this->size = size;
auto calculated_size_result = open_result::ok;
const auto calculated_size = calculate_size(calculated_size_result);
if (calculated_size_result != open_result::ok) {
return calculated_size_result;
}
if (!size) {
this->size = calculated_size;
}
return validate();
}
container::open_result container::open_from_library(FILE *stream, long base, size_t size) noexcept {
this->stream = stream;
this->base = base;
this->size = size;
auto calculated_size_result = open_result::ok;
const auto calculated_size = calculate_size(calculated_size_result);
if (calculated_size_result != open_result::ok) {
return calculated_size_result;
}
if (!size) {
this->size = calculated_size;
}
const auto result = validate();
if (result != open_result::ok) {
return result;
}
auto is_library = false;
auto iteration_result = iterate_load_commands([&](const struct load_command *swapped, const struct load_command *load_cmd) {
if (swapped->cmd != load_commands::identification_dylib) {
return true;
}
is_library = true;
return false;
});
switch (iteration_result) {
case load_command_iteration_result::ok:
break;
case load_command_iteration_result::stream_seek_error:
return open_result::stream_seek_error;
case load_command_iteration_result::stream_read_error:
return open_result::stream_read_error;
case load_command_iteration_result::load_command_is_too_small:
case load_command_iteration_result::load_command_is_too_large:
return open_result::invalid_macho;
}
if (!is_library) {
return open_result::not_a_library;
}
return open_result::ok;
}
container::open_result container::validate() noexcept {
auto &magic = header.magic;
const auto is_big_endian = this->is_big_endian();
const auto stream_position = ftell(stream);
if (fseek(stream, base, SEEK_SET) != 0) {
return open_result::stream_seek_error;
}
if (fread(&magic, sizeof(magic), 1, stream) != 1) {
return open_result::stream_read_error;
}
const auto macho_stream_is_regular = magic_is_thin(magic);
if (macho_stream_is_regular) {
if (fread(&header.cputype, sizeof(header) - sizeof(header.magic), 1, stream) != 1) {
return open_result::stream_read_error;
}
if (is_big_endian) {
swap_mach_header(&header);
}
} else {
const auto macho_stream_is_fat = magic_is_fat(magic);
if (macho_stream_is_fat) {
return open_result::fat_container;
} else {
return open_result::not_a_macho;
}
}
if (fseek(stream, stream_position, SEEK_SET) != 0) {
return open_result::stream_seek_error;
}
return open_result::ok;
}
container::container(container &&container) noexcept :
stream(container.stream), base(container.base), size(container.size), header(container.header), cached_load_commands_(container.cached_load_commands_),
cached_symbol_table_(container.cached_symbol_table_), cached_string_table_(container.cached_string_table_) {
container.base = 0;
container.size = 0;
container.header = {};
container.cached_load_commands_ = nullptr;
container.cached_string_table_ = nullptr;
container.cached_symbol_table_ = nullptr;
}
container& container::operator=(container &&container) noexcept {
stream = container.stream;
base = container.base;
size = container.size;
header = container.header;
cached_load_commands_ = container.cached_load_commands_;
cached_string_table_ = container.cached_string_table_;
cached_symbol_table_ = container.cached_symbol_table_;
container.stream = nullptr;
container.base = 0;
container.size = 0;
container.header = {};
container.cached_load_commands_ = nullptr;
container.cached_string_table_ = nullptr;
container.cached_symbol_table_ = nullptr;
return *this;
}
size_t container::calculate_size(container::open_result &result) noexcept {
const auto position = ftell(stream);
if (fseek(stream, 0, SEEK_END) != 0) {
result = open_result::stream_seek_error;
return 0;
}
auto size = (size_t)ftell(stream);
if (size < base) {
result = open_result::invalid_range;
return size;
}
size -= base;
if (fseek(stream, position, SEEK_SET) != 0) {
result = open_result::stream_seek_error;
return size;
}
result = open_result::ok;
return size;
}
container::~container() {
auto &cached_load_commands = cached_load_commands_;
if (cached_load_commands != nullptr) {
delete[] cached_load_commands;
}
auto &cached_symbol_table = cached_symbol_table_;
if (cached_symbol_table != nullptr) {
delete[] cached_symbol_table;
}
auto &cached_string_table = cached_string_table_;
if (cached_string_table != nullptr) {
delete[] cached_string_table;
}
}
container::load_command_iteration_result container::iterate_load_commands(const std::function<bool (const struct load_command *, const struct load_command *)> &callback) noexcept {
const auto is_big_endian = this->is_big_endian();
const auto &ncmds = header.ncmds;
const auto &sizeofcmds = header.sizeofcmds;
auto &cached_load_commands = cached_load_commands_;
const auto created_cached_load_commands = !cached_load_commands;
auto size_used = 0;
if (!cached_load_commands) {
cached_load_commands = new uint8_t[sizeofcmds];
auto load_command_base = base + sizeof(header);
if (is_64_bit()) {
load_command_base += sizeof(uint32_t);
}
const auto position = ftell(stream);
if (fseek(stream, load_command_base, SEEK_SET) != 0) {
return load_command_iteration_result::stream_seek_error;
}
if (fread(cached_load_commands, sizeofcmds, 1, stream) != 1) {
return load_command_iteration_result::stream_read_error;
}
if (fseek(stream, position, SEEK_SET) != 0) {
return load_command_iteration_result::stream_seek_error;
}
}
auto should_callback = true;
for (auto i = 0, cached_load_commands_index = 0; i < ncmds; i++) {
auto load_cmd = (struct load_command *)&cached_load_commands[cached_load_commands_index];
auto swapped_load_command = *load_cmd;
if (is_big_endian) {
swap_load_command(&swapped_load_command);
}
const auto &cmdsize = swapped_load_command.cmdsize;
if (created_cached_load_commands) {
if (cmdsize < sizeof(struct load_command)) {
return load_command_iteration_result::load_command_is_too_small;
}
if (cmdsize >= sizeofcmds) {
return load_command_iteration_result::load_command_is_too_large;
}
size_used += cmdsize;
if (size_used > sizeofcmds) {
return load_command_iteration_result::load_command_is_too_large;
} else if (size_used == sizeofcmds && i != ncmds - 1) {
return load_command_iteration_result::load_command_is_too_large;
}
}
if (should_callback) {
should_callback = callback(&swapped_load_command, load_cmd);
}
if (!should_callback && !created_cached_load_commands) {
break;
}
cached_load_commands_index += cmdsize;
}
return load_command_iteration_result::ok;
}
container::symbols_iteration_result container::iterate_symbols(const std::function<bool (const struct nlist_64 &, const char *)> &callback) noexcept {
const auto is_big_endian = this->is_big_endian();
const auto position = ftell(stream);
auto &symbol_table = symbol_table_;
if (!symbol_table) {
iterate_load_commands([&](const struct load_command *load_cmd, const struct load_command *load_command) {
if (load_cmd->cmd != load_commands::symbol_table) {
return true;
}
symbol_table = (struct symtab_command *)load_command;
return false;
});
if (!symbol_table) {
return symbols_iteration_result::ok;
}
}
auto &cached_string_table = cached_string_table_;
if (!cached_string_table) {
auto string_table_location = symbol_table->stroff;
if (is_big_endian) {
macho::swap_uint32(&string_table_location);
}
if (!string_table_location) {
return symbols_iteration_result::invalid_string_table;
}
if (string_table_location > size) {
return symbols_iteration_result::invalid_string_table;
}
const auto &string_table_size = symbol_table->strsize;
if (!string_table_size) {
return symbols_iteration_result::invalid_string_table;
}
if (string_table_size > size) {
return symbols_iteration_result::invalid_string_table;
}
const auto string_table_end = string_table_location + string_table_size;
if (string_table_end > size) {
return symbols_iteration_result::invalid_string_table;
}
cached_string_table = new char[string_table_size];
if (fseek(stream, base + string_table_location, SEEK_SET) != 0) {
return symbols_iteration_result::stream_seek_error;
}
if (fread(cached_string_table, string_table_size, 1, stream) != 1) {
return symbols_iteration_result::stream_read_error;
}
}
auto &cached_symbol_table = cached_symbol_table_;
if (!cached_symbol_table) {
auto symbol_table_count = symbol_table->nsyms;
auto symbol_table_location = symbol_table->symoff;
if (is_big_endian) {
macho::swap_uint32(&symbol_table_count);
macho::swap_uint32(&symbol_table_location);
}
if (!symbol_table_count) {
return symbols_iteration_result::no_symbols;
}
if (!symbol_table_location) {
return symbols_iteration_result::invalid_symbol_table;
}
if (symbol_table_location > size) {
return symbols_iteration_result::invalid_symbol_table;
}
if (fseek(stream, base + symbol_table_location, SEEK_SET) != 0) {
return symbols_iteration_result::stream_seek_error;
}
const auto is_64_bit = this->is_64_bit();
if (is_64_bit) {
const auto symbol_table_size = sizeof(struct nlist_64) * symbol_table_count;
if (symbol_table_size > size) {
return symbols_iteration_result::invalid_symbol_table;
}
const auto symbol_table_end = symbol_table_location + symbol_table_size;
if (symbol_table_end > size) {
return symbols_iteration_result::invalid_symbol_table;
}
cached_symbol_table = new uint8_t[symbol_table_size];
if (fread(cached_symbol_table, symbol_table_size, 1, stream) != 1) {
return symbols_iteration_result::stream_read_error;
}
if (is_big_endian) {
swap_nlist_64((struct nlist_64 *)cached_symbol_table, symbol_table_count);
}
} else {
const auto symbol_table_size = sizeof(struct nlist) * symbol_table_count;
if (symbol_table_size > size) {
return symbols_iteration_result::invalid_symbol_table;
}
const auto symbol_table_end = symbol_table_location + symbol_table_size;
if (symbol_table_end > size) {
return symbols_iteration_result::invalid_symbol_table;
}
cached_symbol_table = new uint8_t[symbol_table_size];
if (fread(cached_symbol_table, symbol_table_size, 1, stream) != 1) {
return symbols_iteration_result::stream_read_error;
}
if (is_big_endian) {
swap_nlist((struct nlist *)cached_symbol_table, symbol_table_count);
}
}
if (fseek(stream, position, SEEK_SET) != 0) {
return symbols_iteration_result::stream_seek_error;
}
}
const auto &symbol_table_count = symbol_table->nsyms;
const auto &string_table_size = symbol_table->strsize;
const auto string_table_max_index = string_table_size - 1;
const auto container_is_64_bit = this->is_64_bit();
if (container_is_64_bit) {
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = &((struct nlist_64 *)cached_symbol_table)[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry->n_un.n_strx;
if (symbol_table_entry_string_table_index > string_table_max_index) {
return symbols_iteration_result::invalid_symbol_table_entry;
}
const auto symbol_table_string_table_string = &cached_string_table[symbol_table_entry_string_table_index];
const auto result = callback(*symbol_table_entry, symbol_table_string_table_string);
if (!result) {
break;
}
}
} else {
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = &((struct nlist *)cached_symbol_table)[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry->n_un.n_strx;
if (symbol_table_entry_string_table_index > string_table_max_index) {
return symbols_iteration_result::invalid_symbol_table_entry;
}
const struct nlist_64 symbol_table_entry_64 = { { symbol_table_entry->n_un.n_strx }, symbol_table_entry->n_type, symbol_table_entry->n_sect, (uint16_t)symbol_table_entry->n_desc, symbol_table_entry->n_value };
const auto symbol_table_string_table_string = &cached_string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry_64, symbol_table_string_table_string);
if (!result) {
break;
}
}
}
return symbols_iteration_result::ok;
}
}
<commit_msg>Fix bug returning `symbols_iteration_result::ok` when no symbol-table was found<commit_after>//
// src/mach-o/container.cc
// tbd
//
// Created by inoahdev on 4/24/17.
// Copyright © 2017 inoahdev. All rights reserved.
//
#include <cstdio>
#include <cstdlib>
#include "headers/symbol_table.h"
#include "container.h"
namespace macho {
container::open_result container::open(FILE *stream, long base, size_t size) noexcept {
this->stream = stream;
this->base = base;
this->size = size;
auto calculated_size_result = open_result::ok;
const auto calculated_size = calculate_size(calculated_size_result);
if (calculated_size_result != open_result::ok) {
return calculated_size_result;
}
if (!size) {
this->size = calculated_size;
}
return validate();
}
container::open_result container::open_from_library(FILE *stream, long base, size_t size) noexcept {
this->stream = stream;
this->base = base;
this->size = size;
auto calculated_size_result = open_result::ok;
const auto calculated_size = calculate_size(calculated_size_result);
if (calculated_size_result != open_result::ok) {
return calculated_size_result;
}
if (!size) {
this->size = calculated_size;
}
const auto result = validate();
if (result != open_result::ok) {
return result;
}
auto is_library = false;
auto iteration_result = iterate_load_commands([&](const struct load_command *swapped, const struct load_command *load_cmd) {
if (swapped->cmd != load_commands::identification_dylib) {
return true;
}
is_library = true;
return false;
});
switch (iteration_result) {
case load_command_iteration_result::ok:
break;
case load_command_iteration_result::stream_seek_error:
return open_result::stream_seek_error;
case load_command_iteration_result::stream_read_error:
return open_result::stream_read_error;
case load_command_iteration_result::load_command_is_too_small:
case load_command_iteration_result::load_command_is_too_large:
return open_result::invalid_macho;
}
if (!is_library) {
return open_result::not_a_library;
}
return open_result::ok;
}
container::open_result container::validate() noexcept {
auto &magic = header.magic;
const auto is_big_endian = this->is_big_endian();
const auto stream_position = ftell(stream);
if (fseek(stream, base, SEEK_SET) != 0) {
return open_result::stream_seek_error;
}
if (fread(&magic, sizeof(magic), 1, stream) != 1) {
return open_result::stream_read_error;
}
const auto macho_stream_is_regular = magic_is_thin(magic);
if (macho_stream_is_regular) {
if (fread(&header.cputype, sizeof(header) - sizeof(header.magic), 1, stream) != 1) {
return open_result::stream_read_error;
}
if (is_big_endian) {
swap_mach_header(&header);
}
} else {
const auto macho_stream_is_fat = magic_is_fat(magic);
if (macho_stream_is_fat) {
return open_result::fat_container;
} else {
return open_result::not_a_macho;
}
}
if (fseek(stream, stream_position, SEEK_SET) != 0) {
return open_result::stream_seek_error;
}
return open_result::ok;
}
container::container(container &&container) noexcept :
stream(container.stream), base(container.base), size(container.size), header(container.header), cached_load_commands_(container.cached_load_commands_),
cached_symbol_table_(container.cached_symbol_table_), cached_string_table_(container.cached_string_table_) {
container.base = 0;
container.size = 0;
container.header = {};
container.cached_load_commands_ = nullptr;
container.cached_string_table_ = nullptr;
container.cached_symbol_table_ = nullptr;
}
container& container::operator=(container &&container) noexcept {
stream = container.stream;
base = container.base;
size = container.size;
header = container.header;
cached_load_commands_ = container.cached_load_commands_;
cached_string_table_ = container.cached_string_table_;
cached_symbol_table_ = container.cached_symbol_table_;
container.stream = nullptr;
container.base = 0;
container.size = 0;
container.header = {};
container.cached_load_commands_ = nullptr;
container.cached_string_table_ = nullptr;
container.cached_symbol_table_ = nullptr;
return *this;
}
size_t container::calculate_size(container::open_result &result) noexcept {
const auto position = ftell(stream);
if (fseek(stream, 0, SEEK_END) != 0) {
result = open_result::stream_seek_error;
return 0;
}
auto size = (size_t)ftell(stream);
if (size < base) {
result = open_result::invalid_range;
return size;
}
size -= base;
if (fseek(stream, position, SEEK_SET) != 0) {
result = open_result::stream_seek_error;
return size;
}
result = open_result::ok;
return size;
}
container::~container() {
auto &cached_load_commands = cached_load_commands_;
if (cached_load_commands != nullptr) {
delete[] cached_load_commands;
}
auto &cached_symbol_table = cached_symbol_table_;
if (cached_symbol_table != nullptr) {
delete[] cached_symbol_table;
}
auto &cached_string_table = cached_string_table_;
if (cached_string_table != nullptr) {
delete[] cached_string_table;
}
}
container::load_command_iteration_result container::iterate_load_commands(const std::function<bool (const struct load_command *, const struct load_command *)> &callback) noexcept {
const auto is_big_endian = this->is_big_endian();
const auto &ncmds = header.ncmds;
const auto &sizeofcmds = header.sizeofcmds;
auto &cached_load_commands = cached_load_commands_;
const auto created_cached_load_commands = !cached_load_commands;
auto size_used = 0;
if (!cached_load_commands) {
cached_load_commands = new uint8_t[sizeofcmds];
auto load_command_base = base + sizeof(header);
if (is_64_bit()) {
load_command_base += sizeof(uint32_t);
}
const auto position = ftell(stream);
if (fseek(stream, load_command_base, SEEK_SET) != 0) {
return load_command_iteration_result::stream_seek_error;
}
if (fread(cached_load_commands, sizeofcmds, 1, stream) != 1) {
return load_command_iteration_result::stream_read_error;
}
if (fseek(stream, position, SEEK_SET) != 0) {
return load_command_iteration_result::stream_seek_error;
}
}
auto should_callback = true;
for (auto i = 0, cached_load_commands_index = 0; i < ncmds; i++) {
auto load_cmd = (struct load_command *)&cached_load_commands[cached_load_commands_index];
auto swapped_load_command = *load_cmd;
if (is_big_endian) {
swap_load_command(&swapped_load_command);
}
const auto &cmdsize = swapped_load_command.cmdsize;
if (created_cached_load_commands) {
if (cmdsize < sizeof(struct load_command)) {
return load_command_iteration_result::load_command_is_too_small;
}
if (cmdsize >= sizeofcmds) {
return load_command_iteration_result::load_command_is_too_large;
}
size_used += cmdsize;
if (size_used > sizeofcmds) {
return load_command_iteration_result::load_command_is_too_large;
} else if (size_used == sizeofcmds && i != ncmds - 1) {
return load_command_iteration_result::load_command_is_too_large;
}
}
if (should_callback) {
should_callback = callback(&swapped_load_command, load_cmd);
}
if (!should_callback && !created_cached_load_commands) {
break;
}
cached_load_commands_index += cmdsize;
}
return load_command_iteration_result::ok;
}
container::symbols_iteration_result container::iterate_symbols(const std::function<bool (const struct nlist_64 &, const char *)> &callback) noexcept {
const auto is_big_endian = this->is_big_endian();
const auto position = ftell(stream);
auto &symbol_table = symbol_table_;
if (!symbol_table) {
iterate_load_commands([&](const struct load_command *load_cmd, const struct load_command *load_command) {
if (load_cmd->cmd != load_commands::symbol_table) {
return true;
}
symbol_table = (struct symtab_command *)load_command;
return false;
});
if (!symbol_table) {
return symbols_iteration_result::no_symbol_table_load_command;
}
}
auto &cached_string_table = cached_string_table_;
if (!cached_string_table) {
auto string_table_location = symbol_table->stroff;
if (is_big_endian) {
macho::swap_uint32(&string_table_location);
}
if (!string_table_location) {
return symbols_iteration_result::invalid_string_table;
}
if (string_table_location > size) {
return symbols_iteration_result::invalid_string_table;
}
const auto &string_table_size = symbol_table->strsize;
if (!string_table_size) {
return symbols_iteration_result::invalid_string_table;
}
if (string_table_size > size) {
return symbols_iteration_result::invalid_string_table;
}
const auto string_table_end = string_table_location + string_table_size;
if (string_table_end > size) {
return symbols_iteration_result::invalid_string_table;
}
cached_string_table = new char[string_table_size];
if (fseek(stream, base + string_table_location, SEEK_SET) != 0) {
return symbols_iteration_result::stream_seek_error;
}
if (fread(cached_string_table, string_table_size, 1, stream) != 1) {
return symbols_iteration_result::stream_read_error;
}
}
auto &cached_symbol_table = cached_symbol_table_;
if (!cached_symbol_table) {
auto symbol_table_count = symbol_table->nsyms;
auto symbol_table_location = symbol_table->symoff;
if (is_big_endian) {
macho::swap_uint32(&symbol_table_count);
macho::swap_uint32(&symbol_table_location);
}
if (!symbol_table_count) {
return symbols_iteration_result::no_symbols;
}
if (!symbol_table_location) {
return symbols_iteration_result::invalid_symbol_table;
}
if (symbol_table_location > size) {
return symbols_iteration_result::invalid_symbol_table;
}
if (fseek(stream, base + symbol_table_location, SEEK_SET) != 0) {
return symbols_iteration_result::stream_seek_error;
}
const auto is_64_bit = this->is_64_bit();
if (is_64_bit) {
const auto symbol_table_size = sizeof(struct nlist_64) * symbol_table_count;
if (symbol_table_size > size) {
return symbols_iteration_result::invalid_symbol_table;
}
const auto symbol_table_end = symbol_table_location + symbol_table_size;
if (symbol_table_end > size) {
return symbols_iteration_result::invalid_symbol_table;
}
cached_symbol_table = new uint8_t[symbol_table_size];
if (fread(cached_symbol_table, symbol_table_size, 1, stream) != 1) {
return symbols_iteration_result::stream_read_error;
}
if (is_big_endian) {
swap_nlist_64((struct nlist_64 *)cached_symbol_table, symbol_table_count);
}
} else {
const auto symbol_table_size = sizeof(struct nlist) * symbol_table_count;
if (symbol_table_size > size) {
return symbols_iteration_result::invalid_symbol_table;
}
const auto symbol_table_end = symbol_table_location + symbol_table_size;
if (symbol_table_end > size) {
return symbols_iteration_result::invalid_symbol_table;
}
cached_symbol_table = new uint8_t[symbol_table_size];
if (fread(cached_symbol_table, symbol_table_size, 1, stream) != 1) {
return symbols_iteration_result::stream_read_error;
}
if (is_big_endian) {
swap_nlist((struct nlist *)cached_symbol_table, symbol_table_count);
}
}
if (fseek(stream, position, SEEK_SET) != 0) {
return symbols_iteration_result::stream_seek_error;
}
}
const auto &symbol_table_count = symbol_table->nsyms;
const auto &string_table_size = symbol_table->strsize;
const auto string_table_max_index = string_table_size - 1;
const auto container_is_64_bit = this->is_64_bit();
if (container_is_64_bit) {
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = &((struct nlist_64 *)cached_symbol_table)[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry->n_un.n_strx;
if (symbol_table_entry_string_table_index > string_table_max_index) {
return symbols_iteration_result::invalid_symbol_table_entry;
}
const auto symbol_table_string_table_string = &cached_string_table[symbol_table_entry_string_table_index];
const auto result = callback(*symbol_table_entry, symbol_table_string_table_string);
if (!result) {
break;
}
}
} else {
for (auto i = 0; i < symbol_table_count; i++) {
const auto &symbol_table_entry = &((struct nlist *)cached_symbol_table)[i];
const auto &symbol_table_entry_string_table_index = symbol_table_entry->n_un.n_strx;
if (symbol_table_entry_string_table_index > string_table_max_index) {
return symbols_iteration_result::invalid_symbol_table_entry;
}
const struct nlist_64 symbol_table_entry_64 = { { symbol_table_entry->n_un.n_strx }, symbol_table_entry->n_type, symbol_table_entry->n_sect, (uint16_t)symbol_table_entry->n_desc, symbol_table_entry->n_value };
const auto symbol_table_string_table_string = &cached_string_table[symbol_table_entry_string_table_index];
const auto result = callback(symbol_table_entry_64, symbol_table_string_table_string);
if (!result) {
break;
}
}
}
return symbols_iteration_result::ok;
}
}
<|endoftext|> |
<commit_before>//============================================================================
// Name : Main.cpp
// Author : Wenzhao Sun
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include "MeshGen.h"
#include "commonData.h"
#include "CellInitHelper.h"
#include <vector>
#include "SimulationDomainGPU.h"
using namespace std;
GlobalConfigVars globalConfigVars;
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort =
true) {
if (code != cudaSuccess) {
fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file,
line);
if (abort)
exit(code);
}
}
void initializeSlurmConfig(int argc, char* argv[]) {
// read configuration.
ConfigParser parser;
std::string configFileNameDefault = "./resources/disc_M.cfg";
globalConfigVars = parser.parseConfigFile(configFileNameDefault);
std::string configFileNameBaseL = "./resources/disc_";
std::string configFileNameBaseR = ".cfg";
// Unknown number of input arguments.
if (argc != 1 && argc != 3) {
std::cout << "ERROR: Incorrect input argument count.\n"
<< "Expect either no command line argument or three arguments"
<< std::endl;
exit(0);
}
// one input argument. It has to be "-slurm".
else if (argc == 3) {
if (strcmp(argv[1], "-slurm") != 0) {
std::cout
<< "ERROR: one argument received from commandline but it's not recognized.\n"
<< "Currently, the argument value must be -slurm"
<< std::endl;
exit(0);
} else {
std::string configFileNameM(argv[2]);
std::string configFileNameCombined = configFileNameBaseL
+ configFileNameM + configFileNameBaseR;
parser.updateConfigFile(globalConfigVars, configFileNameCombined);
}
}
// no input argument. Take default.
else if (argc == 1) {
// set GPU device.
int myDeviceID =
globalConfigVars.getConfigValue("GPUDeviceNumber").toInt();
gpuErrchk(cudaSetDevice(myDeviceID));
}
}
void updateDivThres(double& curDivThred, uint& i, double& dt,
double& decayCoeff, double& divThreshold) {
double curTime = i * dt;
double decay = exp(-curTime * decayCoeff);
//curDivThred = 1.0 - (1.0 - divThreshold) * decay;
curDivThred = divThreshold ;
}
int main(int argc, char* argv[]) {
// initialize random seed.
srand(time(NULL));
// Slurm is computer-cluster management system.
initializeSlurmConfig(argc, argv);
// initialize simulation control related parameters from config file.
SimulationGlobalParameter mainPara;
mainPara.initFromConfig();
// initialize simulation initialization helper.
CellInitHelper initHelper;
// initialize simulation domain.
SimulationDomainGPU simuDomain;
SimulationInitData_V2_M initData = initHelper.initInput_M();
simuDomain.initialize_v2_M(initData);
std::string polyStatFileNameBase = globalConfigVars.getConfigValue(
"PolygonStatFileName").toString();
std::string uniqueSymbol =
globalConfigVars.getConfigValue("UniqueSymbol").toString();
std::string polyStatFileName = polyStatFileNameBase + uniqueSymbol + ".txt";
std::remove(polyStatFileName.c_str());
std::string detailStatFileNameBase = globalConfigVars.getConfigValue(
"DetailStatFileNameBase").toString() + uniqueSymbol;
double divThreshold =
globalConfigVars.getConfigValue("DivThreshold").toDouble();
double decayCoeff =
globalConfigVars.getConfigValue("ProlifDecayCoeff").toDouble();
double curDivThred;
int maxStepTraceBack =
globalConfigVars.getConfigValue("MaxStepTraceBack").toInt();
// preparation.
uint aniFrame = 0;
// main simulation steps.
for (uint i = 0; i <= (uint) (mainPara.totalTimeSteps); i++) {
if (i % mainPara.aniAuxVar == 0) {
std::cout << "substep 1 " << std::endl;
CellsStatsData polyData = simuDomain.outputPolyCountData();
std::cout << "substep 2 " << std::endl;
//////// update division threshold //////
updateDivThres(curDivThred, i, mainPara.dt, decayCoeff,
divThreshold);
std::cout << "substep 3 " << std::endl;
// prints brief polygon counting statistics to file
polyData.printPolyCountToFile(polyStatFileName, curDivThred);
// prints detailed individual cell statistics to file
polyData.printDetailStatsToFile(detailStatFileNameBase, aniFrame);
// prints the animation frames to file. They can be open by Paraview
//std::cout << "substep 4 " << std::endl;
//if (i != 0) {
//simuDomain.processT1Info(maxStepTraceBack, polyData);
//}
std::cout << "substep 5 " << std::endl;
//simuDomain.outputVtkFilesWithCri_M(mainPara.animationNameBase,
// aniFrame, mainPara.aniCri);
//simuDomain.outputVtkColorByCell_T1(mainPara.animationNameBase,
// aniFrame, mainPara.aniCri);
simuDomain.outputVtkColorByCell_polySide(mainPara.animationNameBase,
aniFrame, mainPara.aniCri);
// std::cout << "in ani step " << aniFrame << std::endl;
std::cout << "substep 6 " << std::endl;
aniFrame++;
}
simuDomain.runAllLogic_M(mainPara.dt);
}
return 0;
}
<commit_msg>test3<commit_after>//============================================================================
// Name : Main.cpp
// Author : Wenzhao Sun
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include "MeshGen.h"
#include "commonData.h"
#include "CellInitHelper.h"
#include <vector>
#include "SimulationDomainGPU.h"
using namespace std;
GlobalConfigVars globalConfigVars;
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort =
true) {
if (code != cudaSuccess) {
fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file,
line);
if (abort)
exit(code);
}
}
//test here
void initializeSlurmConfig(int argc, char* argv[]) {
// read configuration.
ConfigParser parser;
std::string configFileNameDefault = "./resources/disc_M.cfg";
globalConfigVars = parser.parseConfigFile(configFileNameDefault);
std::string configFileNameBaseL = "./resources/disc_";
std::string configFileNameBaseR = ".cfg";
// Unknown number of input arguments.
if (argc != 1 && argc != 3) {
std::cout << "ERROR: Incorrect input argument count.\n"
<< "Expect either no command line argument or three arguments"
<< std::endl;
exit(0);
}
// one input argument. It has to be "-slurm".
else if (argc == 3) {
if (strcmp(argv[1], "-slurm") != 0) {
std::cout
<< "ERROR: one argument received from commandline but it's not recognized.\n"
<< "Currently, the argument value must be -slurm"
<< std::endl;
exit(0);
} else {
std::string configFileNameM(argv[2]);
std::string configFileNameCombined = configFileNameBaseL
+ configFileNameM + configFileNameBaseR;
parser.updateConfigFile(globalConfigVars, configFileNameCombined);
}
}
// no input argument. Take default.
else if (argc == 1) {
// set GPU device.
int myDeviceID =
globalConfigVars.getConfigValue("GPUDeviceNumber").toInt();
gpuErrchk(cudaSetDevice(myDeviceID));
}
}
void updateDivThres(double& curDivThred, uint& i, double& dt,
double& decayCoeff, double& divThreshold) {
double curTime = i * dt;
double decay = exp(-curTime * decayCoeff);
//curDivThred = 1.0 - (1.0 - divThreshold) * decay;
curDivThred = divThreshold ;
}
int main(int argc, char* argv[]) {
// initialize random seed.
srand(time(NULL));
// Slurm is computer-cluster management system.
initializeSlurmConfig(argc, argv);
// initialize simulation control related parameters from config file.
SimulationGlobalParameter mainPara;
mainPara.initFromConfig();
// initialize simulation initialization helper.
CellInitHelper initHelper;
// initialize simulation domain.
SimulationDomainGPU simuDomain;
SimulationInitData_V2_M initData = initHelper.initInput_M();
simuDomain.initialize_v2_M(initData);
std::string polyStatFileNameBase = globalConfigVars.getConfigValue(
"PolygonStatFileName").toString();
std::string uniqueSymbol =
globalConfigVars.getConfigValue("UniqueSymbol").toString();
std::string polyStatFileName = polyStatFileNameBase + uniqueSymbol + ".txt";
std::remove(polyStatFileName.c_str());
std::string detailStatFileNameBase = globalConfigVars.getConfigValue(
"DetailStatFileNameBase").toString() + uniqueSymbol;
double divThreshold =
globalConfigVars.getConfigValue("DivThreshold").toDouble();
double decayCoeff =
globalConfigVars.getConfigValue("ProlifDecayCoeff").toDouble();
double curDivThred;
int maxStepTraceBack =
globalConfigVars.getConfigValue("MaxStepTraceBack").toInt();
// preparation.
uint aniFrame = 0;
// main simulation steps.
for (uint i = 0; i <= (uint) (mainPara.totalTimeSteps); i++) {
if (i % mainPara.aniAuxVar == 0) {
std::cout << "substep 1 " << std::endl;
CellsStatsData polyData = simuDomain.outputPolyCountData();
std::cout << "substep 2 " << std::endl;
//////// update division threshold //////
updateDivThres(curDivThred, i, mainPara.dt, decayCoeff,
divThreshold);
std::cout << "substep 3 " << std::endl;
// prints brief polygon counting statistics to file
polyData.printPolyCountToFile(polyStatFileName, curDivThred);
// prints detailed individual cell statistics to file
polyData.printDetailStatsToFile(detailStatFileNameBase, aniFrame);
// prints the animation frames to file. They can be open by Paraview
//std::cout << "substep 4 " << std::endl;
//if (i != 0) {
//simuDomain.processT1Info(maxStepTraceBack, polyData);
//}
std::cout << "substep 5 " << std::endl;
//simuDomain.outputVtkFilesWithCri_M(mainPara.animationNameBase,
// aniFrame, mainPara.aniCri);
//simuDomain.outputVtkColorByCell_T1(mainPara.animationNameBase,
// aniFrame, mainPara.aniCri);
simuDomain.outputVtkColorByCell_polySide(mainPara.animationNameBase,
aniFrame, mainPara.aniCri);
// std::cout << "in ani step " << aniFrame << std::endl;
std::cout << "substep 6 " << std::endl;
aniFrame++;
}
simuDomain.runAllLogic_M(mainPara.dt);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "Cistem.hpp"
#include <regex>
#include <algorithm>
using namespace std;
namespace Cistem {
wregex replacess(L"ß");
wregex replaceSch(L"sch");
wregex replaceSchBack(L"\\$");
wregex replaceEi(L"ei");
wregex replaceEiBack(L"%");
wregex replaceIe(L"ie");
wregex replaceIeBack(L"&");
wregex replacexx(L"(.)\\1");
wregex replacexxback(L"(.)\\*");
wregex stripge(L"^ge(.{4,})");
wregex stripemr(L"e[mr]$");
wregex stripnd(L"nd$");
wregex stript(L"t$");
wregex stripesn(L"[esn]$");
wstring stem(const wstring word, bool caseInsensitive) {
if (word.size() == 0) {
return L"";
}
bool uppercase = iswupper(word[0]);
wstring stem = word;
setlocale(LC_ALL, "de_DE.UTF-8");
transform(stem.begin(), stem.end(), stem.begin(), towlower);
replace(stem.begin(), stem.end(), L'ä', L'a');
replace(stem.begin(), stem.end(), L'ö', L'o');
replace(stem.begin(), stem.end(), L'ü', L'u');
stem = regex_replace(stem, replacess, L"ss");
stem = regex_replace(stem, stripge, L"$1");
stem = regex_replace(stem, replaceSch, L"$$");
stem = regex_replace(stem, replaceEi, L"%");
stem = regex_replace(stem, replaceIe, L"&");
stem = regex_replace(stem, replacexx, L"$1*");
bool match;
while (stem.size() > 3) {
if (stem.size() > 5) {
match = regex_search(stem, stripemr);
if (match) {
stem = regex_replace(stem, stripemr, L"");
continue;
}
match = regex_search(stem, stripnd);
if (match) {
stem = regex_replace(stem, stripnd, L"");
continue;
}
}
if (!uppercase || caseInsensitive) {
match = regex_search(stem, stript);
if (match) {
stem = regex_replace(stem, stript, L"");
continue;
}
}
match = regex_search(stem, stripesn);
if (match) {
stem = regex_replace(stem, stripesn, L"");
continue;
}
break;
}
stem = regex_replace(stem, replacexxback, L"$1$1");
stem = regex_replace(stem, replaceEiBack, L"ei");
stem = regex_replace(stem, replaceIeBack, L"ie");
stem = regex_replace(stem, replaceSchBack, L"sch");
return stem;
}
array<wstring,2> segment(const wstring word, bool caseInsensitive) {
array<wstring,2> result;
if (word.size() == 0) {
result[0] = L"";
result[1] = L"";
return result;
}
bool uppercase = iswupper(word[0]);
wstring stem = word;
setlocale(LC_ALL, "de_DE.UTF-8");
transform(stem.begin(), stem.end(), stem.begin(), towlower);
wstring original(stem);
stem = regex_replace(stem, replaceSch, L"$$");
stem = regex_replace(stem, replaceEi, L"%");
stem = regex_replace(stem, replaceIe, L"&");
stem = regex_replace(stem, replacexx, L"$1*");
bool match;
unsigned int restLength = 0;
while (stem.size() > 3) {
if (stem.size() > 5) {
match = regex_search(stem, stripemr);
if (match) {
stem = regex_replace(stem, stripemr, L"");
restLength += 2;
continue;
}
match = regex_search(stem, stripnd);
if (match) {
stem = regex_replace(stem, stripnd, L"");
restLength += 2;
continue;
}
}
if (!uppercase || caseInsensitive) {
match = regex_search(stem, stript);
if (match) {
stem = regex_replace(stem, stript, L"");
restLength += 1;
continue;
}
}
match = regex_search(stem, stripesn);
if (match) {
stem = regex_replace(stem, stripesn, L"");
restLength += 1;
continue;
}
break;
}
stem = regex_replace(stem, replacexxback, L"$1$1");
stem = regex_replace(stem, replaceEiBack, L"ei");
stem = regex_replace(stem, replaceIeBack, L"ie");
stem = regex_replace(stem, replaceSchBack, L"sch");
result[1] = original.substr(original.length() - restLength,
original.length());
result[0] = stem;
return result;
}
wstring stem(const wstring word) {
return stem(word, false);
}
array<wstring,2> segment(const wstring word) {
return segment(word, false);
}
}
<commit_msg>Update cistem.cpp<commit_after>#include "cistem.hpp"
#include <regex>
#include <algorithm>
using namespace std;
namespace Cistem {
wregex replacess(L"ß");
wregex replaceSch(L"sch");
wregex replaceSchBack(L"\\$");
wregex replaceEi(L"ei");
wregex replaceEiBack(L"%");
wregex replaceIe(L"ie");
wregex replaceIeBack(L"&");
wregex replacexx(L"(.)\\1");
wregex replacexxback(L"(.)\\*");
wregex stripge(L"^ge(.{4,})");
wregex stripemr(L"e[mr]$");
wregex stripnd(L"nd$");
wregex stript(L"t$");
wregex stripesn(L"[esn]$");
wstring stem(const wstring word, bool caseInsensitive) {
if (word.size() == 0) {
return L"";
}
bool uppercase = iswupper(word[0]);
wstring stem = word;
setlocale(LC_ALL, "de_DE.UTF-8");
transform(stem.begin(), stem.end(), stem.begin(), towlower);
replace(stem.begin(), stem.end(), L'ä', L'a');
replace(stem.begin(), stem.end(), L'ö', L'o');
replace(stem.begin(), stem.end(), L'ü', L'u');
stem = regex_replace(stem, replacess, L"ss");
stem = regex_replace(stem, stripge, L"$1");
stem = regex_replace(stem, replaceSch, L"$$");
stem = regex_replace(stem, replaceEi, L"%");
stem = regex_replace(stem, replaceIe, L"&");
stem = regex_replace(stem, replacexx, L"$1*");
bool match;
while (stem.size() > 3) {
if (stem.size() > 5) {
match = regex_search(stem, stripemr);
if (match) {
stem = regex_replace(stem, stripemr, L"");
continue;
}
match = regex_search(stem, stripnd);
if (match) {
stem = regex_replace(stem, stripnd, L"");
continue;
}
}
if (!uppercase || caseInsensitive) {
match = regex_search(stem, stript);
if (match) {
stem = regex_replace(stem, stript, L"");
continue;
}
}
match = regex_search(stem, stripesn);
if (match) {
stem = regex_replace(stem, stripesn, L"");
continue;
}
break;
}
stem = regex_replace(stem, replacexxback, L"$1$1");
stem = regex_replace(stem, replaceEiBack, L"ei");
stem = regex_replace(stem, replaceIeBack, L"ie");
stem = regex_replace(stem, replaceSchBack, L"sch");
return stem;
}
array<wstring,2> segment(const wstring word, bool caseInsensitive) {
array<wstring,2> result;
if (word.size() == 0) {
result[0] = L"";
result[1] = L"";
return result;
}
bool uppercase = iswupper(word[0]);
wstring stem = word;
setlocale(LC_ALL, "de_DE.UTF-8");
transform(stem.begin(), stem.end(), stem.begin(), towlower);
wstring original(stem);
stem = regex_replace(stem, replaceSch, L"$$");
stem = regex_replace(stem, replaceEi, L"%");
stem = regex_replace(stem, replaceIe, L"&");
stem = regex_replace(stem, replacexx, L"$1*");
bool match;
unsigned int restLength = 0;
while (stem.size() > 3) {
if (stem.size() > 5) {
match = regex_search(stem, stripemr);
if (match) {
stem = regex_replace(stem, stripemr, L"");
restLength += 2;
continue;
}
match = regex_search(stem, stripnd);
if (match) {
stem = regex_replace(stem, stripnd, L"");
restLength += 2;
continue;
}
}
if (!uppercase || caseInsensitive) {
match = regex_search(stem, stript);
if (match) {
stem = regex_replace(stem, stript, L"");
restLength += 1;
continue;
}
}
match = regex_search(stem, stripesn);
if (match) {
stem = regex_replace(stem, stripesn, L"");
restLength += 1;
continue;
}
break;
}
stem = regex_replace(stem, replacexxback, L"$1$1");
stem = regex_replace(stem, replaceEiBack, L"ei");
stem = regex_replace(stem, replaceIeBack, L"ie");
stem = regex_replace(stem, replaceSchBack, L"sch");
result[1] = original.substr(original.length() - restLength,
original.length());
result[0] = stem;
return result;
}
wstring stem(const wstring word) {
return stem(word, false);
}
array<wstring,2> segment(const wstring word) {
return segment(word, false);
}
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
// ROS libraries
#include <angles/angles.h>
#include <random_numbers/random_numbers.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_listener.h>
#include <message_filters/subscriber.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
// ROS messages
#include <std_msgs/Float32.h>
#include <std_msgs/Int16.h>
#include <std_msgs/UInt8.h>
#include <std_msgs/String.h>
#include <sensor_msgs/Joy.h>
#include <sensor_msgs/Range.h>
#include <geometry_msgs/Pose2D.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <apriltags_ros/AprilTagDetectionArray.h>
// Include Controllers
#include "LogicController.h"
#include <vector>
// To handle shutdown signals so the node quits
// properly in response to "rosnode kill"
#include <ros/ros.h>
#include <signal.h>
using namespace std;
// Random number generator
random_numbers::RandomNumberGenerator* rng;
// Create logic controller
LogicController logicController;
// Behaviours Logic Functions
void sendDriveCommand(double linearVel, double angularVel);
void openFingers(); // Open fingers to 90 degrees
void closeFingers();// Close fingers to 0 degrees
void raiseWrist(); // Return wrist back to 0 degrees
void lowerWrist(); // Lower wrist to 50 degrees
void resultHandler();
// Numeric Variables for rover positioning
geometry_msgs::Pose2D currentLocation;
geometry_msgs::Pose2D currentLocationMap;
geometry_msgs::Pose2D currentLocationAverage;
geometry_msgs::Pose2D centerLocation;
geometry_msgs::Pose2D centerLocationMap;
geometry_msgs::Pose2D centerLocationOdom;
int currentMode = 0;
const float behaviourLoopTimeStep = 0.1; // time between the behaviour loop calls
const float status_publish_interval = 1;
const float heartbeat_publish_interval = 2;
const float waypointTolerance = 0.1; //10 cm tolerance.
// used for calling code once but not in main
bool initilized = false;
float linearVelocity = 0;
float angularVelocity = 0;
float prevWrist = 0;
float prevFinger = 0;
Result result;
std_msgs::String msg;
geometry_msgs::Twist velocity;
char host[128];
string publishedName;
char prev_state_machine[128];
// Publishers
ros::Publisher stateMachinePublish;
ros::Publisher status_publisher;
ros::Publisher fingerAnglePublish;
ros::Publisher wristAnglePublish;
ros::Publisher infoLogPublisher;
ros::Publisher driveControlPublish;
ros::Publisher heartbeatPublisher;
// Subscribers
ros::Subscriber joySubscriber;
ros::Subscriber modeSubscriber;
ros::Subscriber targetSubscriber;
ros::Subscriber odometrySubscriber;
ros::Subscriber mapSubscriber;
// Timers
ros::Timer stateMachineTimer;
ros::Timer publish_status_timer;
ros::Timer publish_heartbeat_timer;
// records time for delays in sequanced actions, 1 second resolution.
time_t timerStartTime;
// An initial delay to allow the rover to gather enough position data to
// average its location.
unsigned int startDelayInSeconds = 1;
float timerTimeElapsed = 0;
//Transforms
tf::TransformListener *tfListener;
// OS Signal Handler
void sigintEventHandler(int signal);
//Callback handlers
void joyCmdHandler(const sensor_msgs::Joy::ConstPtr& message);
void modeHandler(const std_msgs::UInt8::ConstPtr& message);
void targetHandler(const apriltags_ros::AprilTagDetectionArray::ConstPtr& tagInfo);
void odometryHandler(const nav_msgs::Odometry::ConstPtr& message);
void mapHandler(const nav_msgs::Odometry::ConstPtr& message);
void behaviourStateMachine(const ros::TimerEvent&);
void publishStatusTimerEventHandler(const ros::TimerEvent& event);
void publishHeartBeatTimerEventHandler(const ros::TimerEvent& event);
void sonarHandler(const sensor_msgs::Range::ConstPtr& sonarLeft, const sensor_msgs::Range::ConstPtr& sonarCenter, const sensor_msgs::Range::ConstPtr& sonarRight);
// Converts the time passed as reported by ROS (which takes Gazebo simulation rate into account) into milliseconds as an integer.
long int getROSTimeInMilliSecs();
int main(int argc, char **argv) {
gethostname(host, sizeof (host));
string hostname(host);
if (argc >= 2) {
publishedName = argv[1];
cout << "Welcome to the world of tomorrow " << publishedName
<< "! Behaviour turnDirectionule started." << endl;
} else {
publishedName = hostname;
cout << "No Name Selected. Default is: " << publishedName << endl;
}
// NoSignalHandler so we can catch SIGINT ourselves and shutdown the node
ros::init(argc, argv, (publishedName + "_BEHAVIOUR"), ros::init_options::NoSigintHandler);
ros::NodeHandle mNH;
// Register the SIGINT event handler so the node can shutdown properly
signal(SIGINT, sigintEventHandler);
joySubscriber = mNH.subscribe((publishedName + "/joystick"), 10, joyCmdHandler);
modeSubscriber = mNH.subscribe((publishedName + "/mode"), 1, modeHandler);
targetSubscriber = mNH.subscribe((publishedName + "/targets"), 10, targetHandler);
odometrySubscriber = mNH.subscribe((publishedName + "/odom/filtered"), 10, odometryHandler);
mapSubscriber = mNH.subscribe((publishedName + "/odom/ekf"), 10, mapHandler);
message_filters::Subscriber<sensor_msgs::Range> sonarLeftSubscriber(mNH, (publishedName + "/sonarLeft"), 10);
message_filters::Subscriber<sensor_msgs::Range> sonarCenterSubscriber(mNH, (publishedName + "/sonarCenter"), 10);
message_filters::Subscriber<sensor_msgs::Range> sonarRightSubscriber(mNH, (publishedName + "/sonarRight"), 10);
status_publisher = mNH.advertise<std_msgs::String>((publishedName + "/status"), 1, true);
stateMachinePublish = mNH.advertise<std_msgs::String>((publishedName + "/state_machine"), 1, true);
fingerAnglePublish = mNH.advertise<std_msgs::Float32>((publishedName + "/fingerAngle/cmd"), 1, true);
wristAnglePublish = mNH.advertise<std_msgs::Float32>((publishedName + "/wristAngle/cmd"), 1, true);
infoLogPublisher = mNH.advertise<std_msgs::String>("/infoLog", 1, true);
driveControlPublish = mNH.advertise<geometry_msgs::Twist>((publishedName + "/driveControl"), 10);
heartbeatPublisher = mNH.advertise<std_msgs::String>((publishedName + "/behaviour/heartbeat"), 1, true);
publish_status_timer = mNH.createTimer(ros::Duration(status_publish_interval), publishStatusTimerEventHandler);
stateMachineTimer = mNH.createTimer(ros::Duration(behaviourLoopTimeStep), behaviourStateMachine);
publish_heartbeat_timer = mNH.createTimer(ros::Duration(heartbeat_publish_interval), publishHeartBeatTimerEventHandler);
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Range, sensor_msgs::Range, sensor_msgs::Range> sonarSyncPolicy;
message_filters::Synchronizer<sonarSyncPolicy> sonarSync(sonarSyncPolicy(10), sonarLeftSubscriber, sonarCenterSubscriber, sonarRightSubscriber);
sonarSync.registerCallback(boost::bind(&sonarHandler, _1, _2, _3));
tfListener = new tf::TransformListener();
std_msgs::String msg;
msg.data = "Log Started";
infoLogPublisher.publish(msg);
stringstream ss;
ss << "Rover start delay set to " << startDelayInSeconds << " seconds";
msg.data = ss.str();
infoLogPublisher.publish(msg);
timerStartTime = time(0);
ros::spin();
return EXIT_SUCCESS;
}
// This is the top-most logic control block organised as a state machine.
// This function calls the dropOff, pickUp, and search controllers.
// This block passes the goal location to the proportional-integral-derivative
// controllers in the abridge package.
void behaviourStateMachine(const ros::TimerEvent&) {
std_msgs::String stateMachineMsg;
// time since timerStartTime was set to current time
timerTimeElapsed = time(0) - timerStartTime;
// init code goes here. (code that runs only once at start of
// auto mode but wont work in main goes here)
if (!initilized) {
if (timerTimeElapsed > startDelayInSeconds) {
// initialization has run
initilized = true;
} else {
return;
}
}
// Robot is in automode
if (currentMode == 2 || currentMode == 3) {
Point centerOdom;
centerOdom.x = centerLocation.x;
centerOdom.y = centerLocation.y;
centerOdom.theta = centerLocation.theta;
logicController.setCenterLocationOdom(centerOdom);
Point centerMap;
centerMap.x = centerLocationMap.x;
centerMap.y = centerLocationMap.y;
centerMap.theta = centerLocationMap.theta;
logicController.setCenterLocationMap(centerMap);
logicController.setCurrentTimeInMilliSecs( getROSTimeInMilliSecs() );
result = logicController.DoWork();
bool skip = false;
if (result.type == behavior) {
if (result.b = wait) {
skip = true;
}
}
if (skip) {
sendDriveCommand(0.0,0.0);
std_msgs::Float32 angle;
angle.data = prevFinger;
fingerAnglePublish.publish(angle);
angle.data = prevWrist;
wristAnglePublish.publish(angle);
}
else {
sendDriveCommand(result.pd.left,result.pd.right);
std_msgs::Float32 angle;
if (result.fingerAngle != -1) {
angle.data = result.fingerAngle;
fingerAnglePublish.publish(angle);
prevFinger = result.fingerAngle;
}
if (result.wristAngle != -1) {
angle.data = result.wristAngle;
wristAnglePublish.publish(angle);
prevWrist = result.wristAngle;
}
}
//publishHandeling here
//logicController.getPublishData() suggested;
cout << endl;
}
// mode is NOT auto
else {
// publish current state for the operator to see
stateMachineMsg.data = "WAITING";
}
// publish state machine string for user, only if it has changed, though
if (strcmp(stateMachineMsg.data.c_str(), prev_state_machine) != 0) {
stateMachinePublish.publish(stateMachineMsg);
sprintf(prev_state_machine, "%s", stateMachineMsg.data.c_str());
}
//send pointer to connect centerLocation of searchController and droppOffController
}
void sendDriveCommand(double left, double right)
{
velocity.linear.x = left,
velocity.angular.z = right;
// publish the drive commands
driveControlPublish.publish(velocity);
}
/*************************
* ROS CALLBACK HANDLERS *
*************************/
void targetHandler(const apriltags_ros::AprilTagDetectionArray::ConstPtr& message) {
if (message->detections.size() > 0) {
vector<TagPoint> tags;
for (int i = 0; i < message->detections.size(); i++) {
TagPoint loc;
loc.id = message->detections[i].id;
geometry_msgs::PoseStamped tagPose = message->detections[i].pose;
loc.x = tagPose.pose.position.x;
loc.y = tagPose.pose.position.y;
loc.z = tagPose.pose.position.z;
//loc.theta =
tags.push_back(loc);
}
logicController.setAprilTags(tags);
}
}
void modeHandler(const std_msgs::UInt8::ConstPtr& message) {
currentMode = message->data;
sendDriveCommand(0.0, 0.0);
}
void sonarHandler(const sensor_msgs::Range::ConstPtr& sonarLeft, const sensor_msgs::Range::ConstPtr& sonarCenter, const sensor_msgs::Range::ConstPtr& sonarRight) {
logicController.setSonarData(sonarLeft->range, sonarCenter->range, sonarRight->range);
}
void odometryHandler(const nav_msgs::Odometry::ConstPtr& message) {
//Get (x,y) location directly from pose
currentLocation.x = message->pose.pose.position.x;
currentLocation.y = message->pose.pose.position.y;
//Get theta rotation by converting quaternion orientation to pitch/roll/yaw
tf::Quaternion q(message->pose.pose.orientation.x, message->pose.pose.orientation.y, message->pose.pose.orientation.z, message->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
currentLocation.theta = yaw;
linearVelocity = message->twist.twist.linear.x;
angularVelocity = message->twist.twist.angular.z;
Point currentLoc;
currentLoc.x = currentLocation.x;
currentLoc.y = currentLocation.y;
currentLoc.theta = currentLocation.theta;
logicController.setPositionData(currentLoc);
logicController.setVelocityData(linearVelocity, angularVelocity);
}
void mapHandler(const nav_msgs::Odometry::ConstPtr& message) {
//Get (x,y) location directly from pose
currentLocationMap.x = message->pose.pose.position.x;
currentLocationMap.y = message->pose.pose.position.y;
//Get theta rotation by converting quaternion orientation to pitch/roll/yaw
tf::Quaternion q(message->pose.pose.orientation.x, message->pose.pose.orientation.y, message->pose.pose.orientation.z, message->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
currentLocationMap.theta = yaw;
linearVelocity = message->twist.twist.linear.x;
angularVelocity = message->twist.twist.angular.z;
Point currentLoc;
currentLoc.x = currentLocation.x;
currentLoc.y = currentLocation.y;
currentLoc.theta = currentLocation.theta;
logicController.setPositionData(currentLoc);
logicController.setMapVelocityData(linearVelocity, angularVelocity);
}
void joyCmdHandler(const sensor_msgs::Joy::ConstPtr& message) {
if (currentMode == 0 || currentMode == 1) {
sendDriveCommand(abs(message->axes[4]) >= 0.1 ? message->axes[4] : 0, abs(message->axes[3]) >= 0.1 ? message->axes[3] : 0);
}
}
void publishStatusTimerEventHandler(const ros::TimerEvent&) {
std_msgs::String msg;
msg.data = "online";
status_publisher.publish(msg);
}
void sigintEventHandler(int sig) {
// All the default sigint handler does is call shutdown()
ros::shutdown();
}
void publishHeartBeatTimerEventHandler(const ros::TimerEvent&) {
std_msgs::String msg;
msg.data = "";
heartbeatPublisher.publish(msg);
}
long int getROSTimeInMilliSecs()
{
// Get the current time according to ROS (will be zero for simulated clock until the first time message is recieved).
ros::Time t = ros::Time::now();
// Convert from seconds and nanoseconds to milliseconds.
return t.sec*1e3 + t.nsec/1e6;
}
<commit_msg>Fixed indenting on ROS Adapter, removed extraniouse comment<commit_after>#include <ros/ros.h>
// ROS libraries
#include <angles/angles.h>
#include <random_numbers/random_numbers.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_listener.h>
#include <message_filters/subscriber.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
// ROS messages
#include <std_msgs/Float32.h>
#include <std_msgs/Int16.h>
#include <std_msgs/UInt8.h>
#include <std_msgs/String.h>
#include <sensor_msgs/Joy.h>
#include <sensor_msgs/Range.h>
#include <geometry_msgs/Pose2D.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <apriltags_ros/AprilTagDetectionArray.h>
// Include Controllers
#include "LogicController.h"
#include <vector>
// To handle shutdown signals so the node quits
// properly in response to "rosnode kill"
#include <ros/ros.h>
#include <signal.h>
using namespace std;
// Random number generator
random_numbers::RandomNumberGenerator* rng;
// Create logic controller
LogicController logicController;
// Behaviours Logic Functions
void sendDriveCommand(double linearVel, double angularVel);
void openFingers(); // Open fingers to 90 degrees
void closeFingers();// Close fingers to 0 degrees
void raiseWrist(); // Return wrist back to 0 degrees
void lowerWrist(); // Lower wrist to 50 degrees
void resultHandler();
// Numeric Variables for rover positioning
geometry_msgs::Pose2D currentLocation;
geometry_msgs::Pose2D currentLocationMap;
geometry_msgs::Pose2D currentLocationAverage;
geometry_msgs::Pose2D centerLocation;
geometry_msgs::Pose2D centerLocationMap;
geometry_msgs::Pose2D centerLocationOdom;
int currentMode = 0;
const float behaviourLoopTimeStep = 0.1; // time between the behaviour loop calls
const float status_publish_interval = 1;
const float heartbeat_publish_interval = 2;
const float waypointTolerance = 0.1; //10 cm tolerance.
// used for calling code once but not in main
bool initilized = false;
float linearVelocity = 0;
float angularVelocity = 0;
float prevWrist = 0;
float prevFinger = 0;
Result result;
std_msgs::String msg;
geometry_msgs::Twist velocity;
char host[128];
string publishedName;
char prev_state_machine[128];
// Publishers
ros::Publisher stateMachinePublish;
ros::Publisher status_publisher;
ros::Publisher fingerAnglePublish;
ros::Publisher wristAnglePublish;
ros::Publisher infoLogPublisher;
ros::Publisher driveControlPublish;
ros::Publisher heartbeatPublisher;
// Subscribers
ros::Subscriber joySubscriber;
ros::Subscriber modeSubscriber;
ros::Subscriber targetSubscriber;
ros::Subscriber odometrySubscriber;
ros::Subscriber mapSubscriber;
// Timers
ros::Timer stateMachineTimer;
ros::Timer publish_status_timer;
ros::Timer publish_heartbeat_timer;
// records time for delays in sequanced actions, 1 second resolution.
time_t timerStartTime;
// An initial delay to allow the rover to gather enough position data to
// average its location.
unsigned int startDelayInSeconds = 1;
float timerTimeElapsed = 0;
//Transforms
tf::TransformListener *tfListener;
// OS Signal Handler
void sigintEventHandler(int signal);
//Callback handlers
void joyCmdHandler(const sensor_msgs::Joy::ConstPtr& message);
void modeHandler(const std_msgs::UInt8::ConstPtr& message);
void targetHandler(const apriltags_ros::AprilTagDetectionArray::ConstPtr& tagInfo);
void odometryHandler(const nav_msgs::Odometry::ConstPtr& message);
void mapHandler(const nav_msgs::Odometry::ConstPtr& message);
void behaviourStateMachine(const ros::TimerEvent&);
void publishStatusTimerEventHandler(const ros::TimerEvent& event);
void publishHeartBeatTimerEventHandler(const ros::TimerEvent& event);
void sonarHandler(const sensor_msgs::Range::ConstPtr& sonarLeft, const sensor_msgs::Range::ConstPtr& sonarCenter, const sensor_msgs::Range::ConstPtr& sonarRight);
// Converts the time passed as reported by ROS (which takes Gazebo simulation rate into account) into milliseconds as an integer.
long int getROSTimeInMilliSecs();
int main(int argc, char **argv) {
gethostname(host, sizeof (host));
string hostname(host);
if (argc >= 2) {
publishedName = argv[1];
cout << "Welcome to the world of tomorrow " << publishedName
<< "! Behaviour turnDirectionule started." << endl;
} else {
publishedName = hostname;
cout << "No Name Selected. Default is: " << publishedName << endl;
}
// NoSignalHandler so we can catch SIGINT ourselves and shutdown the node
ros::init(argc, argv, (publishedName + "_BEHAVIOUR"), ros::init_options::NoSigintHandler);
ros::NodeHandle mNH;
// Register the SIGINT event handler so the node can shutdown properly
signal(SIGINT, sigintEventHandler);
joySubscriber = mNH.subscribe((publishedName + "/joystick"), 10, joyCmdHandler);
modeSubscriber = mNH.subscribe((publishedName + "/mode"), 1, modeHandler);
targetSubscriber = mNH.subscribe((publishedName + "/targets"), 10, targetHandler);
odometrySubscriber = mNH.subscribe((publishedName + "/odom/filtered"), 10, odometryHandler);
mapSubscriber = mNH.subscribe((publishedName + "/odom/ekf"), 10, mapHandler);
message_filters::Subscriber<sensor_msgs::Range> sonarLeftSubscriber(mNH, (publishedName + "/sonarLeft"), 10);
message_filters::Subscriber<sensor_msgs::Range> sonarCenterSubscriber(mNH, (publishedName + "/sonarCenter"), 10);
message_filters::Subscriber<sensor_msgs::Range> sonarRightSubscriber(mNH, (publishedName + "/sonarRight"), 10);
status_publisher = mNH.advertise<std_msgs::String>((publishedName + "/status"), 1, true);
stateMachinePublish = mNH.advertise<std_msgs::String>((publishedName + "/state_machine"), 1, true);
fingerAnglePublish = mNH.advertise<std_msgs::Float32>((publishedName + "/fingerAngle/cmd"), 1, true);
wristAnglePublish = mNH.advertise<std_msgs::Float32>((publishedName + "/wristAngle/cmd"), 1, true);
infoLogPublisher = mNH.advertise<std_msgs::String>("/infoLog", 1, true);
driveControlPublish = mNH.advertise<geometry_msgs::Twist>((publishedName + "/driveControl"), 10);
heartbeatPublisher = mNH.advertise<std_msgs::String>((publishedName + "/behaviour/heartbeat"), 1, true);
publish_status_timer = mNH.createTimer(ros::Duration(status_publish_interval), publishStatusTimerEventHandler);
stateMachineTimer = mNH.createTimer(ros::Duration(behaviourLoopTimeStep), behaviourStateMachine);
publish_heartbeat_timer = mNH.createTimer(ros::Duration(heartbeat_publish_interval), publishHeartBeatTimerEventHandler);
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Range, sensor_msgs::Range, sensor_msgs::Range> sonarSyncPolicy;
message_filters::Synchronizer<sonarSyncPolicy> sonarSync(sonarSyncPolicy(10), sonarLeftSubscriber, sonarCenterSubscriber, sonarRightSubscriber);
sonarSync.registerCallback(boost::bind(&sonarHandler, _1, _2, _3));
tfListener = new tf::TransformListener();
std_msgs::String msg;
msg.data = "Log Started";
infoLogPublisher.publish(msg);
stringstream ss;
ss << "Rover start delay set to " << startDelayInSeconds << " seconds";
msg.data = ss.str();
infoLogPublisher.publish(msg);
timerStartTime = time(0);
ros::spin();
return EXIT_SUCCESS;
}
// This is the top-most logic control block organised as a state machine.
// This function calls the dropOff, pickUp, and search controllers.
// This block passes the goal location to the proportional-integral-derivative
// controllers in the abridge package.
void behaviourStateMachine(const ros::TimerEvent&) {
std_msgs::String stateMachineMsg;
// time since timerStartTime was set to current time
timerTimeElapsed = time(0) - timerStartTime;
// init code goes here. (code that runs only once at start of
// auto mode but wont work in main goes here)
if (!initilized) {
if (timerTimeElapsed > startDelayInSeconds) {
// initialization has run
initilized = true;
} else {
return;
}
}
// Robot is in automode
if (currentMode == 2 || currentMode == 3) {
Point centerOdom;
centerOdom.x = centerLocation.x;
centerOdom.y = centerLocation.y;
centerOdom.theta = centerLocation.theta;
logicController.setCenterLocationOdom(centerOdom);
Point centerMap;
centerMap.x = centerLocationMap.x;
centerMap.y = centerLocationMap.y;
centerMap.theta = centerLocationMap.theta;
logicController.setCenterLocationMap(centerMap);
logicController.setCurrentTimeInMilliSecs( getROSTimeInMilliSecs() );
result = logicController.DoWork();
bool skip = false;
if (result.type == behavior) {
if (result.b = wait) {
skip = true;
}
}
if (skip) {
sendDriveCommand(0.0,0.0);
std_msgs::Float32 angle;
angle.data = prevFinger;
fingerAnglePublish.publish(angle);
angle.data = prevWrist;
wristAnglePublish.publish(angle);
}
else {
sendDriveCommand(result.pd.left,result.pd.right);
std_msgs::Float32 angle;
if (result.fingerAngle != -1) {
angle.data = result.fingerAngle;
fingerAnglePublish.publish(angle);
prevFinger = result.fingerAngle;
}
if (result.wristAngle != -1) {
angle.data = result.wristAngle;
wristAnglePublish.publish(angle);
prevWrist = result.wristAngle;
}
}
//publishHandeling here
//logicController.getPublishData() suggested;
cout << endl;
}
// mode is NOT auto
else {
// publish current state for the operator to see
stateMachineMsg.data = "WAITING";
}
// publish state machine string for user, only if it has changed, though
if (strcmp(stateMachineMsg.data.c_str(), prev_state_machine) != 0) {
stateMachinePublish.publish(stateMachineMsg);
sprintf(prev_state_machine, "%s", stateMachineMsg.data.c_str());
}
}
void sendDriveCommand(double left, double right)
{
velocity.linear.x = left,
velocity.angular.z = right;
// publish the drive commands
driveControlPublish.publish(velocity);
}
/*************************
* ROS CALLBACK HANDLERS *
*************************/
void targetHandler(const apriltags_ros::AprilTagDetectionArray::ConstPtr& message) {
if (message->detections.size() > 0) {
vector<TagPoint> tags;
for (int i = 0; i < message->detections.size(); i++) {
TagPoint loc;
loc.id = message->detections[i].id;
geometry_msgs::PoseStamped tagPose = message->detections[i].pose;
loc.x = tagPose.pose.position.x;
loc.y = tagPose.pose.position.y;
loc.z = tagPose.pose.position.z;
//loc.theta =
tags.push_back(loc);
}
logicController.setAprilTags(tags);
}
}
void modeHandler(const std_msgs::UInt8::ConstPtr& message) {
currentMode = message->data;
sendDriveCommand(0.0, 0.0);
}
void sonarHandler(const sensor_msgs::Range::ConstPtr& sonarLeft, const sensor_msgs::Range::ConstPtr& sonarCenter, const sensor_msgs::Range::ConstPtr& sonarRight) {
logicController.setSonarData(sonarLeft->range, sonarCenter->range, sonarRight->range);
}
void odometryHandler(const nav_msgs::Odometry::ConstPtr& message) {
//Get (x,y) location directly from pose
currentLocation.x = message->pose.pose.position.x;
currentLocation.y = message->pose.pose.position.y;
//Get theta rotation by converting quaternion orientation to pitch/roll/yaw
tf::Quaternion q(message->pose.pose.orientation.x, message->pose.pose.orientation.y, message->pose.pose.orientation.z, message->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
currentLocation.theta = yaw;
linearVelocity = message->twist.twist.linear.x;
angularVelocity = message->twist.twist.angular.z;
Point currentLoc;
currentLoc.x = currentLocation.x;
currentLoc.y = currentLocation.y;
currentLoc.theta = currentLocation.theta;
logicController.setPositionData(currentLoc);
logicController.setVelocityData(linearVelocity, angularVelocity);
}
void mapHandler(const nav_msgs::Odometry::ConstPtr& message) {
//Get (x,y) location directly from pose
currentLocationMap.x = message->pose.pose.position.x;
currentLocationMap.y = message->pose.pose.position.y;
//Get theta rotation by converting quaternion orientation to pitch/roll/yaw
tf::Quaternion q(message->pose.pose.orientation.x, message->pose.pose.orientation.y, message->pose.pose.orientation.z, message->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
currentLocationMap.theta = yaw;
linearVelocity = message->twist.twist.linear.x;
angularVelocity = message->twist.twist.angular.z;
Point currentLoc;
currentLoc.x = currentLocation.x;
currentLoc.y = currentLocation.y;
currentLoc.theta = currentLocation.theta;
logicController.setPositionData(currentLoc);
logicController.setMapVelocityData(linearVelocity, angularVelocity);
}
void joyCmdHandler(const sensor_msgs::Joy::ConstPtr& message) {
if (currentMode == 0 || currentMode == 1) {
sendDriveCommand(abs(message->axes[4]) >= 0.1 ? message->axes[4] : 0, abs(message->axes[3]) >= 0.1 ? message->axes[3] : 0);
}
}
void publishStatusTimerEventHandler(const ros::TimerEvent&) {
std_msgs::String msg;
msg.data = "online";
status_publisher.publish(msg);
}
void sigintEventHandler(int sig) {
// All the default sigint handler does is call shutdown()
ros::shutdown();
}
void publishHeartBeatTimerEventHandler(const ros::TimerEvent&) {
std_msgs::String msg;
msg.data = "";
heartbeatPublisher.publish(msg);
}
long int getROSTimeInMilliSecs()
{
// Get the current time according to ROS (will be zero for simulated clock until the first time message is recieved).
ros::Time t = ros::Time::now();
// Convert from seconds and nanoseconds to milliseconds.
return t.sec*1e3 + t.nsec/1e6;
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include <string>
#include <boost/variant.hpp>
namespace blackhole {
namespace attribute {
typedef boost::variant<
std::int32_t,
std::uint32_t,
long,
unsigned long,
std::int64_t,
std::uint64_t,
std::double_t,
std::string,
timeval
> value_t;
} // namespace attribute
typedef attribute::value_t attribute_value_t;
} // namespace blackhole
<commit_msg>[Aux] Half-way to the own underlying attribute typedefs.<commit_after>#pragma once
#include <cstdint>
#include <string>
#include <boost/variant.hpp>
namespace blackhole {
namespace attribute {
typedef boost::variant<
std::int32_t,
std::uint32_t,
long,
unsigned long,
std::int64_t,
std::uint64_t,
double,
std::string,
timeval
> value_t;
} // namespace attribute
typedef attribute::value_t attribute_value_t;
} // namespace blackhole
<|endoftext|> |
<commit_before>/*
This handles the downsampling of the data
*/
#pragma once
#include "vector.hpp"
#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"
namespace sim {
class FractalDownsampler {
public:
FractalDownsampler(double rt = 1.001, double lt = 1e6)
: ratio_threshold(rt)
, linear_threshold(lt)
{
}
bool operator()(const Vector& v)
{
cumulative_curve_dist += (v - last_v).norm();
float linear_dist = (v - last_sample_v).norm();
if (((cumulative_curve_dist / linear_dist) > ratio_threshold)
| (abs(cumulative_curve_dist - linear_dist) > linear_threshold)) {
accept_sample(v);
return true;
}
last_v = v;
return false;
}
// This is makes it look like we accepted last_v
std::optional<Vector> flush()
{
if (cumulative_curve_dist == 0) {
return {};
}
accept_sample(last_v);
return last_v;
}
private:
void accept_sample(const Vector& v)
{
cumulative_curve_dist = 0;
last_sample_v = v;
last_v = v;
}
double cumulative_curve_dist = 0;
Vector last_sample_v = { 0, 0, 0 };
Vector last_v = { 0, 0, 0 };
double ratio_threshold = 1.001;
double linear_threshold = 1e6;
};
} // namespace sim<commit_msg>Remove code for flushing<commit_after>/*
This handles the downsampling of the data
*/
#pragma once
#include "vector.hpp"
#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"
namespace sim {
class FractalDownsampler {
public:
FractalDownsampler(double rt = 1.001, double lt = 1e6)
: ratio_threshold(rt)
, linear_threshold(lt)
{
}
bool operator()(const Vector& v)
{
cumulative_curve_dist += (v - last_v).norm();
float linear_dist = (v - last_sample_v).norm();
if (((cumulative_curve_dist / linear_dist) > ratio_threshold)
| (abs(cumulative_curve_dist - linear_dist) > linear_threshold)) {
accept_sample(v);
return true;
}
last_v = v;
return false;
}
private:
void accept_sample(const Vector& v)
{
cumulative_curve_dist = 0;
last_sample_v = v;
last_v = v;
}
double cumulative_curve_dist = 0;
Vector last_sample_v = { 0, 0, 0 };
Vector last_v = { 0, 0, 0 };
double ratio_threshold = 1.001;
double linear_threshold = 1e6;
};
} // namespace sim<|endoftext|> |
<commit_before>#include <bitcoin/network/network.hpp>
#include <boost/lexical_cast.hpp>
#include <functional>
#include <algorithm>
#include <iostream>
#include <bitcoin/util/logger.hpp>
#include <bitcoin/dialect.hpp>
#include "channel.hpp"
using std::placeholders::_1;
using std::placeholders::_2;
namespace libbitcoin {
using boost::asio::socket_base;
network_impl::network_impl()
{
default_dialect_.reset(new original_dialect);
our_ip_address_ = message::ip_address{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0};
}
network_impl::~network_impl()
{
if (acceptor_)
acceptor_->close();
}
channel_handle network_impl::create_channel(socket_ptr socket)
{
channel_pimpl* channel_obj = new channel_pimpl(
shared_from_this(), default_dialect_, service(), socket);
channels_.push_back(channel_obj);
log_debug() << channels_.size() << " peers connected.";
return channel_obj->get_id();
}
void network_impl::handle_connect(const boost::system::error_code& ec,
socket_ptr socket, std::string hostname, connect_handler handle_connect)
{
if (ec)
{
log_error() << "Connecting to peer " << hostname
<< ": " << ec.message();
handle_connect(error::system_network_error, 0);
return;
}
channel_handle chanid = create_channel(socket);
handle_connect(std::error_code(), chanid);
}
void network_impl::connect(std::string hostname, unsigned short port,
connect_handler handle_connect)
{
socket_ptr socket(new tcp::socket(*service()));
tcp::resolver resolver(*service());
tcp::resolver::query query(hostname,
boost::lexical_cast<std::string>(port));
tcp::endpoint endpoint = *resolver.resolve(query);
socket->async_connect(endpoint, std::bind(
&network_impl::handle_connect, shared_from_this(),
_1, socket, hostname, handle_connect));
}
void network_impl::listen(connect_handler handle_connect)
{
strand()->post(
[&listeners_, handle_connect]
{
listeners_.push_back(handle_connect);
});
}
static void remove_matching_channels(channel_list* channels,
channel_handle chandle)
{
auto is_matching =
[chandle](channel_pimpl& channel_obj)
{
return channel_obj.get_id() == chandle;
};
channels->erase_if(is_matching);
log_debug() << channels->size() << " peers remaining.";
}
void network_impl::disconnect(channel_handle chandle)
{
strand()->post(
std::bind(remove_matching_channels, &channels_, chandle));
}
template<typename Callback, typename Registry>
void generic_subscribe(strand_ptr strand, channel_handle chandle,
Callback handle_message, Registry& registry)
{
strand->post(
[chandle, handle_message, ®istry]
{
registry.insert(std::make_pair(chandle, handle_message));
});
}
void network_impl::subscribe_version(channel_handle chandle,
receive_version_handler handle_receive)
{
generic_subscribe<receive_version_handler, version_registry_map>(
strand(), chandle, handle_receive, version_registry_);
}
void network_impl::subscribe_verack(channel_handle chandle,
receive_verack_handler handle_receive)
{
generic_subscribe<receive_verack_handler, verack_registry_map>(
strand(), chandle, handle_receive, verack_registry_);
}
void network_impl::subscribe_addr(channel_handle chandle,
receive_addr_handler handle_receive)
{
generic_subscribe<receive_addr_handler, addr_registry_map>(
strand(), chandle, handle_receive, addr_registry_);
}
void network_impl::subscribe_inv(channel_handle chandle,
receive_inv_handler handle_receive)
{
generic_subscribe<receive_inv_handler, inv_registry_map>(
strand(), chandle, handle_receive, inv_registry_);
}
void network_impl::subscribe_block(channel_handle chandle,
receive_block_handler handle_receive)
{
generic_subscribe<receive_block_handler, block_registry_map>(
strand(), chandle, handle_receive, block_registry_);
}
template<typename Message, typename Callback>
void perform_send(channel_handle chandle,
const Message packet, channel_list* channels, Callback handle_send)
{
auto is_matching =
[chandle](const channel_pimpl& channel_obj)
{
return channel_obj.get_id() == chandle;
};
auto it = std::find_if(channels->begin(), channels->end(), is_matching);
if (it == channels->end())
{
log_error() << "Non existant channel " << chandle << " for send.";
handle_send(error::network_channel_not_found);
return;
}
it->send(packet);
}
template<typename Message, typename Callback>
void generic_send(strand_ptr strand, channel_handle chandle,
const Message packet, channel_list* channels, Callback handle_send)
{
strand->post(std::bind(&perform_send<Message, Callback>,
chandle, packet, channels, handle_send));
}
void network_impl::send(channel_handle chandle,
const message::version& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, &channels_, handle_send);
}
void network_impl::send(channel_handle chandle,
const message::verack& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, &channels_, handle_send);
}
void network_impl::send(channel_handle chandle,
const message::getaddr& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, &channels_, handle_send);
}
void network_impl::send(channel_handle chandle,
const message::getdata& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, &channels_, handle_send);
}
void network_impl::send(channel_handle chandle,
const message::getblocks& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, &channels_, handle_send);
}
template<typename Message, typename Registry>
void perform_relay(channel_handle chandle,
const Message& packet, Registry& registry)
{
auto range = registry.equal_range(chandle);
for (auto it = range.first; it != range.second; ++it)
it->second(packet);
registry.erase(range.first, range.second);
}
template<typename Message, typename Registry>
void generic_relay(strand_ptr strand, channel_handle chandle,
const Message& packet, Registry& registry)
{
strand->post(std::bind(
&perform_relay<Message, Registry>, chandle, packet, registry));
}
void network_impl::relay(channel_handle chandle,
const message::version& packet)
{
generic_relay(strand(), chandle, packet, version_registry_);
}
void network_impl::relay(channel_handle chandle,
const message::verack& packet)
{
generic_relay(strand(), chandle, packet, verack_registry_);
}
void network_impl::relay(channel_handle chandle,
const message::addr& packet)
{
generic_relay(strand(), chandle, packet, addr_registry_);
}
void network_impl::relay(channel_handle chandle,
const message::inv& packet)
{
generic_relay(strand(), chandle, packet, inv_registry_);
}
void network_impl::relay(channel_handle chandle,
const message::block& packet)
{
generic_relay(strand(), chandle, packet, block_registry_);
}
size_t network_impl::connection_count() const
{
return channels_.size();
}
bool network_impl::start_accept()
{
acceptor_.reset(new tcp::acceptor(*service()));
socket_ptr socket(new tcp::socket(*service()));
try
{
tcp::endpoint endpoint(tcp::v4(), 8333);
acceptor_->open(endpoint.protocol());
acceptor_->set_option(tcp::acceptor::reuse_address(true));
acceptor_->bind(endpoint);
acceptor_->listen(socket_base::max_connections);
acceptor_->async_accept(*socket,
std::bind(&network_impl::handle_accept, shared_from_this(),
socket));
}
catch (std::exception& ex)
{
log_error() << "Accepting connections: " << ex.what();
return false;
}
return true;
}
void network_impl::handle_accept(socket_ptr socket)
{
tcp::endpoint remote_endpoint = socket->remote_endpoint();
log_debug() << "New incoming connection from "
<< remote_endpoint.address().to_string();
channel_handle chanid = create_channel(socket);
strand()->post(
[&listeners_, chanid]
{
for (connect_handler handle_connect: listeners_)
handle_connect(std::error_code(), chanid);
listeners_.clear();
});
socket.reset(new tcp::socket(*service()));
acceptor_->async_accept(*socket,
std::bind(&network_impl::handle_accept, shared_from_this(),
socket));
}
void network_impl::set_ip_address(std::string ip_addr)
{
//our_ip_address_ = ip_addr;
}
message::ip_address network_impl::get_ip_address() const
{
return our_ip_address_;
}
} // libbitcoin
<commit_msg>std::ref(...)'ize bound reference arguments.<commit_after>#include <bitcoin/network/network.hpp>
#include <boost/lexical_cast.hpp>
#include <functional>
#include <algorithm>
#include <iostream>
#include <bitcoin/util/logger.hpp>
#include <bitcoin/dialect.hpp>
#include "channel.hpp"
using std::placeholders::_1;
using std::placeholders::_2;
namespace libbitcoin {
using boost::asio::socket_base;
network_impl::network_impl()
{
default_dialect_.reset(new original_dialect);
our_ip_address_ = message::ip_address{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0};
}
network_impl::~network_impl()
{
if (acceptor_)
acceptor_->close();
}
channel_handle network_impl::create_channel(socket_ptr socket)
{
channel_pimpl* channel_obj = new channel_pimpl(
shared_from_this(), default_dialect_, service(), socket);
channels_.push_back(channel_obj);
log_debug() << channels_.size() << " peers connected.";
return channel_obj->get_id();
}
void network_impl::handle_connect(const boost::system::error_code& ec,
socket_ptr socket, std::string hostname, connect_handler handle_connect)
{
if (ec)
{
log_error() << "Connecting to peer " << hostname
<< ": " << ec.message();
handle_connect(error::system_network_error, 0);
return;
}
channel_handle chanid = create_channel(socket);
handle_connect(std::error_code(), chanid);
}
void network_impl::connect(std::string hostname, unsigned short port,
connect_handler handle_connect)
{
socket_ptr socket(new tcp::socket(*service()));
tcp::resolver resolver(*service());
tcp::resolver::query query(hostname,
boost::lexical_cast<std::string>(port));
tcp::endpoint endpoint = *resolver.resolve(query);
socket->async_connect(endpoint, std::bind(
&network_impl::handle_connect, shared_from_this(),
_1, socket, hostname, handle_connect));
}
void network_impl::listen(connect_handler handle_connect)
{
strand()->post(
[&listeners_, handle_connect]
{
listeners_.push_back(handle_connect);
});
}
static void remove_matching_channels(channel_list* channels,
channel_handle chandle)
{
auto is_matching =
[chandle](channel_pimpl& channel_obj)
{
return channel_obj.get_id() == chandle;
};
channels->erase_if(is_matching);
log_debug() << channels->size() << " peers remaining.";
}
void network_impl::disconnect(channel_handle chandle)
{
strand()->post(
std::bind(remove_matching_channels, &channels_, chandle));
}
template<typename Callback, typename Registry>
void perform_subscribe(channel_handle chandle,
Callback handle_message, Registry& registry)
{
registry.insert(std::make_pair(chandle, handle_message));
}
template<typename Callback, typename Registry>
void generic_subscribe(strand_ptr strand, channel_handle chandle,
Callback handle_message, Registry& registry)
{
strand->post(std::bind(&perform_subscribe<Callback, Registry>,
chandle, handle_message, std::ref(registry)));
}
void network_impl::subscribe_version(channel_handle chandle,
receive_version_handler handle_receive)
{
generic_subscribe<receive_version_handler, version_registry_map>(
strand(), chandle, handle_receive, version_registry_);
}
void network_impl::subscribe_verack(channel_handle chandle,
receive_verack_handler handle_receive)
{
generic_subscribe<receive_verack_handler, verack_registry_map>(
strand(), chandle, handle_receive, verack_registry_);
}
void network_impl::subscribe_addr(channel_handle chandle,
receive_addr_handler handle_receive)
{
generic_subscribe<receive_addr_handler, addr_registry_map>(
strand(), chandle, handle_receive, addr_registry_);
}
void network_impl::subscribe_inv(channel_handle chandle,
receive_inv_handler handle_receive)
{
generic_subscribe<receive_inv_handler, inv_registry_map>(
strand(), chandle, handle_receive, inv_registry_);
}
void network_impl::subscribe_block(channel_handle chandle,
receive_block_handler handle_receive)
{
generic_subscribe<receive_block_handler, block_registry_map>(
strand(), chandle, handle_receive, block_registry_);
}
template<typename Message, typename Callback>
void perform_send(channel_handle chandle,
const Message packet, channel_list& channels, Callback handle_send)
{
auto is_matching =
[chandle](const channel_pimpl& channel_obj)
{
return channel_obj.get_id() == chandle;
};
auto it = std::find_if(channels.begin(), channels.end(), is_matching);
if (it == channels.end())
{
log_error() << "Non existant channel " << chandle << " for send.";
handle_send(error::network_channel_not_found);
return;
}
it->send(packet);
}
template<typename Message, typename Callback>
void generic_send(strand_ptr strand, channel_handle chandle,
const Message packet, channel_list& channels, Callback handle_send)
{
strand->post(std::bind(&perform_send<Message, Callback>,
chandle, packet, std::ref(channels), handle_send));
}
void network_impl::send(channel_handle chandle,
const message::version& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, std::ref(channels_), handle_send);
}
void network_impl::send(channel_handle chandle,
const message::verack& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, std::ref(channels_), handle_send);
}
void network_impl::send(channel_handle chandle,
const message::getaddr& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, std::ref(channels_), handle_send);
}
void network_impl::send(channel_handle chandle,
const message::getdata& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, std::ref(channels_), handle_send);
}
void network_impl::send(channel_handle chandle,
const message::getblocks& packet, send_handler handle_send)
{
generic_send(strand(), chandle, packet, std::ref(channels_), handle_send);
}
template<typename Message, typename Registry>
void perform_relay(channel_handle chandle,
const Message& packet, Registry& registry)
{
auto range = registry.equal_range(chandle);
for (auto it = range.first; it != range.second; ++it)
it->second(packet);
registry.erase(range.first, range.second);
}
template<typename Message, typename Registry>
void generic_relay(strand_ptr strand, channel_handle chandle,
const Message& packet, Registry& registry)
{
strand->post(std::bind(&perform_relay<Message, Registry>,
chandle, packet, std::ref(registry)));
}
void network_impl::relay(channel_handle chandle,
const message::version& packet)
{
generic_relay(strand(), chandle, packet, version_registry_);
}
void network_impl::relay(channel_handle chandle,
const message::verack& packet)
{
generic_relay(strand(), chandle, packet, verack_registry_);
}
void network_impl::relay(channel_handle chandle,
const message::addr& packet)
{
generic_relay(strand(), chandle, packet, addr_registry_);
}
void network_impl::relay(channel_handle chandle,
const message::inv& packet)
{
generic_relay(strand(), chandle, packet, inv_registry_);
}
void network_impl::relay(channel_handle chandle,
const message::block& packet)
{
generic_relay(strand(), chandle, packet, block_registry_);
}
size_t network_impl::connection_count() const
{
return channels_.size();
}
bool network_impl::start_accept()
{
acceptor_.reset(new tcp::acceptor(*service()));
socket_ptr socket(new tcp::socket(*service()));
try
{
tcp::endpoint endpoint(tcp::v4(), 8333);
acceptor_->open(endpoint.protocol());
acceptor_->set_option(tcp::acceptor::reuse_address(true));
acceptor_->bind(endpoint);
acceptor_->listen(socket_base::max_connections);
acceptor_->async_accept(*socket,
std::bind(&network_impl::handle_accept, shared_from_this(),
socket));
}
catch (std::exception& ex)
{
log_error() << "Accepting connections: " << ex.what();
return false;
}
return true;
}
void network_impl::handle_accept(socket_ptr socket)
{
tcp::endpoint remote_endpoint = socket->remote_endpoint();
log_debug() << "New incoming connection from "
<< remote_endpoint.address().to_string();
channel_handle chanid = create_channel(socket);
strand()->post(
[&listeners_, chanid]
{
for (connect_handler handle_connect: listeners_)
handle_connect(std::error_code(), chanid);
listeners_.clear();
});
socket.reset(new tcp::socket(*service()));
acceptor_->async_accept(*socket,
std::bind(&network_impl::handle_accept, shared_from_this(),
socket));
}
void network_impl::set_ip_address(std::string ip_addr)
{
//our_ip_address_ = ip_addr;
}
message::ip_address network_impl::get_ip_address() const
{
return our_ip_address_;
}
} // libbitcoin
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>
/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
#include "GameKeeper.h"
// FIXME remove externs!
extern Address serverAddress;
extern PingPacket getTeamCounts();
extern uint16_t curMaxPlayers;
extern int getTarget(const char *victimname);
extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message);
ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
// parse url
std::string protocol, hostname, pathname;
int port = 80;
bool useDefault = false;
// use default if it can't be parsed
if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
useDefault = true;
// use default if wrong protocol or invalid port
if ((protocol != "http") || (port < 1) || (port > 65535))
useDefault = true;
// use default if bad address
Address address = Address::getHostAddress(hostname);
if (address.isAny())
useDefault = true;
// parse default list server URL if we need to; assume default works
if (useDefault) {
BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
}
// add to list
this->address = address;
this->port = port;
this->pathname = pathname;
this->hostname = hostname;
this->linkSocket = NotConnected;
this->publicizeAddress = publicizedAddress;
this->publicizeDescription = publicizedTitle;
this->publicizeServer = true; //if this c'tor is called, it's safe to publicize
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink()
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
this->linkSocket = NotConnected;
this->publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
TimeKeeper start = TimeKeeper::getCurrent();
do {
// compute timeout
float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
if (waitTime <= 0.0f)
break;
if (!isConnected()) //queueMessage should have connected us
break;
// check for list server socket connection
int fdMax = -1;
fd_set write_set;
fd_set read_set;
FD_ZERO(&write_set);
FD_ZERO(&read_set);
if (phase == ListServerLink::CONNECTING)
_FD_SET(linkSocket, &write_set);
else
_FD_SET(linkSocket, &read_set);
fdMax = linkSocket;
// wait for socket to connect or timeout
struct timeval timeout;
timeout.tv_sec = long(floorf(waitTime));
timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
0, &timeout);
if (nfound == 0)
// Time has gone, close and go
break;
// check for connection to list server
if (FD_ISSET(linkSocket, &write_set))
sendQueuedMessages();
else if (FD_ISSET(linkSocket, &read_set))
read();
} while (true);
// stop list server communication
closeLink();
}
void ListServerLink::closeLink()
{
if (isConnected()) {
close(linkSocket);
DEBUG4("Closing List Server\n");
linkSocket = NotConnected;
}
}
void ListServerLink::read()
{
if (isConnected()) {
char buf[2048];
int bytes = recv(linkSocket, buf, sizeof(buf)-1, 0);
// TODO don't close unless we've got it all
closeLink();
buf[bytes]=0;
char* base = buf;
static char *tokGoodIdentifier = "TOKGOOD: ";
static char *tokBadIdentifier = "TOKBAD: ";
// walks entire reply including HTTP headers
while (*base) {
// find next newline
char* scan = base;
while (*scan && *scan != '\r' && *scan != '\n') scan++;
// if no newline then no more complete replies
if (*scan != '\r' && *scan != '\n') break;
while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0';
DEBUG4("Got line: \"%s\"\n", base);
// TODO don't do this if we don't want central logins
if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) {
char *callsign, *group;
callsign = (char *)(base + strlen(tokGoodIdentifier));
int playerIndex = getTarget(callsign);
DEBUG3("Got: [%d] %s\n", playerIndex, base);
group = callsign;
while (*group && (*group != ':')) group++;
while (*group && (*group == ':')) *group++ = 0;
if (playerIndex < curMaxPlayers) {
GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);
if (!playerData->accessInfo.isRegistered())
playerData->accessInfo.storeInfo(NULL);
playerData->accessInfo.setPermissionRights();
while (*group) {
char *nextgroup = group;
while (*nextgroup && (*nextgroup != ':')) nextgroup++;
while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0;
playerData->accessInfo.addGroup(group);
//DEBUG3("Got: [%d] \"%s\" \"%s\"\n", playerIndex, callsign, group);
group = nextgroup;
}
sendMessage(ServerPlayer, playerIndex, "Global login approved!");
playerData->player.clearToken();
}
} else if (strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier)) == 0) {
char *callsign;
callsign = (char *)(base + strlen(tokBadIdentifier));
int playerIndex = getTarget(callsign);
DEBUG3("Got: [%d] %s\n", playerIndex, base);
if (playerIndex < curMaxPlayers) {
GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);
sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token.");
playerData->player.clearToken();
}
}
// next reply
base = scan;
}
if (nextMessageType != ListServerLink::NONE) {
// There was a pending request arrived after we write:
// we should redo all the stuff
openLink();
}
}
}
void ListServerLink::openLink()
{
// start opening connection if not already doing so
if (!isConnected()) {
linkSocket = socket(AF_INET, SOCK_STREAM, 0);
DEBUG4("Opening List Server\n");
if (!isConnected()) {
return;
}
// set to non-blocking for connect
if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
closeLink();
return;
}
// Make our connection come from our serverAddress in case we have
// multiple/masked IPs so the list server can verify us.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr = serverAddress;
// assign the address to the socket
if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
closeLink();
return;
}
// connect. this should fail with EINPROGRESS but check for
// success just in case.
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = address;
if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
if (getErrno() != EINPROGRESS) {
nerror("connecting to list server");
// try to lookup dns name again in case it moved
this->address = Address::getHostAddress(this->hostname);
closeLink();
} else {
phase = CONNECTING;
}
} else {
// shouldn't arrive here. Just in case, clean
DEBUG3("list server connect and close?\n");
closeLink();
}
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// Open network connection only if closed
if (!isConnected()) openLink();
// record next message to send.
nextMessageType = type;
}
void ListServerLink::sendQueuedMessages()
{
if (!isConnected())
return;
if (nextMessageType == ListServerLink::ADD) {
DEBUG3("Queuing ADD message to list server\n");
addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
DEBUG3("Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// TODO we probably should convert to a POST. List server now allows either
// send ADD message (must send blank line)
msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s",
pathname.c_str(), publicizedAddress.c_str(),
getServerVersion(), gameInfo,
getAppVersion());
msg += "&checktokens=";
for (int i = 0; i < curMaxPlayers; i++) {
GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i);
if (playerData && strlen(playerData->player.getCallSign()) && strlen(playerData->player.getToken())) {
msg += TextUtils::format(playerData->player.getCallSign());
msg += "=";
msg += TextUtils::format(playerData->player.getToken());
msg += "%0D%0A";
}
}
// TODO loop through groups we are interested in and request them
// *groups=GROUP0%0D%0AGROUP1%0D%0A
// see handleGrouplistCmd()
msg += "&groups=";
PlayerAccessMap::iterator itr = groupAccess.begin();
for ( ; itr != groupAccess.end(); itr++) {
msg += itr->first.c_str();
msg += "%0D%0A";
}
msg += TextUtils::format("&title=%s HTTP/1.1\r\n"
"User-Agent: bzfs %s\r\n"
"Host: %s\r\n"
"Cache-Control: no-cache\r\n"
"Connection: close\r\n"
"\r\n",
publicizedTitle.c_str(),
getAppVersion(),
hostname.c_str());
sendLSMessage(msg);
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
// send REMOVE (must send blank line)
msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
"User-Agent: bzfs %s\r\n"
"Host: %s\r\n"
"Cache-Control: no-cache\r\n"
"Connection: close\r\n"
"\r\n",
pathname.c_str(),
publicizedAddress.c_str(),
getAppVersion(),
hostname.c_str());
sendLSMessage(msg);
}
void ListServerLink::sendLSMessage(std::string message)
{
const int bufsize = 4096;
char msg[bufsize];
strncpy(msg, message.c_str(), bufsize);
msg[bufsize - 1] = 0;
if (strlen(msg) > 0) {
DEBUG3("%s\n", msg);
if (send(linkSocket, msg, strlen(msg), 0) == -1) {
perror("List server send failed");
DEBUG3("Unable to send to the list server!\n");
closeLink();
} else {
nextMessageType = ListServerLink::NONE;
phase = ListServerLink::WRITTEN;
}
} else {
closeLink();
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>fix player lookup<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>
/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
#include "GameKeeper.h"
// FIXME remove externs!
extern Address serverAddress;
extern PingPacket getTeamCounts();
extern uint16_t curMaxPlayers;
extern int getTarget(const char *victimname);
extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message);
ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
// parse url
std::string protocol, hostname, pathname;
int port = 80;
bool useDefault = false;
// use default if it can't be parsed
if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
useDefault = true;
// use default if wrong protocol or invalid port
if ((protocol != "http") || (port < 1) || (port > 65535))
useDefault = true;
// use default if bad address
Address address = Address::getHostAddress(hostname);
if (address.isAny())
useDefault = true;
// parse default list server URL if we need to; assume default works
if (useDefault) {
BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
}
// add to list
this->address = address;
this->port = port;
this->pathname = pathname;
this->hostname = hostname;
this->linkSocket = NotConnected;
this->publicizeAddress = publicizedAddress;
this->publicizeDescription = publicizedTitle;
this->publicizeServer = true; //if this c'tor is called, it's safe to publicize
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink()
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
this->linkSocket = NotConnected;
this->publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
TimeKeeper start = TimeKeeper::getCurrent();
do {
// compute timeout
float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
if (waitTime <= 0.0f)
break;
if (!isConnected()) //queueMessage should have connected us
break;
// check for list server socket connection
int fdMax = -1;
fd_set write_set;
fd_set read_set;
FD_ZERO(&write_set);
FD_ZERO(&read_set);
if (phase == ListServerLink::CONNECTING)
_FD_SET(linkSocket, &write_set);
else
_FD_SET(linkSocket, &read_set);
fdMax = linkSocket;
// wait for socket to connect or timeout
struct timeval timeout;
timeout.tv_sec = long(floorf(waitTime));
timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
0, &timeout);
if (nfound == 0)
// Time has gone, close and go
break;
// check for connection to list server
if (FD_ISSET(linkSocket, &write_set))
sendQueuedMessages();
else if (FD_ISSET(linkSocket, &read_set))
read();
} while (true);
// stop list server communication
closeLink();
}
void ListServerLink::closeLink()
{
if (isConnected()) {
close(linkSocket);
DEBUG4("Closing List Server\n");
linkSocket = NotConnected;
}
}
void ListServerLink::read()
{
if (isConnected()) {
char buf[2048];
int bytes = recv(linkSocket, buf, sizeof(buf)-1, 0);
// TODO don't close unless we've got it all
closeLink();
buf[bytes]=0;
char* base = buf;
static char *tokGoodIdentifier = "TOKGOOD: ";
static char *tokBadIdentifier = "TOKBAD: ";
// walks entire reply including HTTP headers
while (*base) {
// find next newline
char* scan = base;
while (*scan && *scan != '\r' && *scan != '\n') scan++;
// if no newline then no more complete replies
if (*scan != '\r' && *scan != '\n') break;
while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0';
DEBUG4("Got line: \"%s\"\n", base);
// TODO don't do this if we don't want central logins
if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) {
char *callsign, *group;
callsign = (char *)(base + strlen(tokGoodIdentifier));
DEBUG3("Got: %s\n", base);
group = callsign;
while (*group && (*group != ':')) group++;
while (*group && (*group == ':')) *group++ = 0;
int playerIndex = getTarget(callsign);
if (playerIndex < curMaxPlayers) {
GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);
if (!playerData->accessInfo.isRegistered())
playerData->accessInfo.storeInfo(NULL);
playerData->accessInfo.setPermissionRights();
while (*group) {
char *nextgroup = group;
while (*nextgroup && (*nextgroup != ':')) nextgroup++;
while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0;
playerData->accessInfo.addGroup(group);
//DEBUG3("Got: [%d] \"%s\" \"%s\"\n", playerIndex, callsign, group);
group = nextgroup;
}
sendMessage(ServerPlayer, playerIndex, "Global login approved!");
playerData->player.clearToken();
}
} else if (strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier)) == 0) {
char *callsign;
callsign = (char *)(base + strlen(tokBadIdentifier));
int playerIndex = getTarget(callsign);
DEBUG3("Got: [%d] %s\n", playerIndex, base);
if (playerIndex < curMaxPlayers) {
GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(playerIndex);
sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token.");
playerData->player.clearToken();
}
}
// next reply
base = scan;
}
if (nextMessageType != ListServerLink::NONE) {
// There was a pending request arrived after we write:
// we should redo all the stuff
openLink();
}
}
}
void ListServerLink::openLink()
{
// start opening connection if not already doing so
if (!isConnected()) {
linkSocket = socket(AF_INET, SOCK_STREAM, 0);
DEBUG4("Opening List Server\n");
if (!isConnected()) {
return;
}
// set to non-blocking for connect
if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
closeLink();
return;
}
// Make our connection come from our serverAddress in case we have
// multiple/masked IPs so the list server can verify us.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr = serverAddress;
// assign the address to the socket
if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
closeLink();
return;
}
// connect. this should fail with EINPROGRESS but check for
// success just in case.
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = address;
if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
if (getErrno() != EINPROGRESS) {
nerror("connecting to list server");
// try to lookup dns name again in case it moved
this->address = Address::getHostAddress(this->hostname);
closeLink();
} else {
phase = CONNECTING;
}
} else {
// shouldn't arrive here. Just in case, clean
DEBUG3("list server connect and close?\n");
closeLink();
}
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// Open network connection only if closed
if (!isConnected()) openLink();
// record next message to send.
nextMessageType = type;
}
void ListServerLink::sendQueuedMessages()
{
if (!isConnected())
return;
if (nextMessageType == ListServerLink::ADD) {
DEBUG3("Queuing ADD message to list server\n");
addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
DEBUG3("Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// TODO we probably should convert to a POST. List server now allows either
// send ADD message (must send blank line)
msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s",
pathname.c_str(), publicizedAddress.c_str(),
getServerVersion(), gameInfo,
getAppVersion());
msg += "&checktokens=";
for (int i = 0; i < curMaxPlayers; i++) {
GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i);
if (playerData && strlen(playerData->player.getCallSign()) && strlen(playerData->player.getToken())) {
msg += TextUtils::format(playerData->player.getCallSign());
msg += "=";
msg += TextUtils::format(playerData->player.getToken());
msg += "%0D%0A";
}
}
// TODO loop through groups we are interested in and request them
// *groups=GROUP0%0D%0AGROUP1%0D%0A
// see handleGrouplistCmd()
msg += "&groups=";
PlayerAccessMap::iterator itr = groupAccess.begin();
for ( ; itr != groupAccess.end(); itr++) {
msg += itr->first.c_str();
msg += "%0D%0A";
}
msg += TextUtils::format("&title=%s HTTP/1.1\r\n"
"User-Agent: bzfs %s\r\n"
"Host: %s\r\n"
"Cache-Control: no-cache\r\n"
"Connection: close\r\n"
"\r\n",
publicizedTitle.c_str(),
getAppVersion(),
hostname.c_str());
sendLSMessage(msg);
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
// send REMOVE (must send blank line)
msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
"User-Agent: bzfs %s\r\n"
"Host: %s\r\n"
"Cache-Control: no-cache\r\n"
"Connection: close\r\n"
"\r\n",
pathname.c_str(),
publicizedAddress.c_str(),
getAppVersion(),
hostname.c_str());
sendLSMessage(msg);
}
void ListServerLink::sendLSMessage(std::string message)
{
const int bufsize = 4096;
char msg[bufsize];
strncpy(msg, message.c_str(), bufsize);
msg[bufsize - 1] = 0;
if (strlen(msg) > 0) {
DEBUG3("%s\n", msg);
if (send(linkSocket, msg, strlen(msg), 0) == -1) {
perror("List server send failed");
DEBUG3("Unable to send to the list server!\n");
closeLink();
} else {
nextMessageType = ListServerLink::NONE;
phase = ListServerLink::WRITTEN;
}
} else {
closeLink();
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* implementation headers */
#include <string.h>
#include <math.h>
#include <errno.h>
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
extern Address serverAddress;
extern PingPacket getTeamCounts();
ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
// parse url
std::string protocol, hostname, pathname;
int port = 80;
bool useDefault = false;
// use default if it can't be parsed
if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
useDefault = true;
// use default if wrong protocol or invalid port
if ((protocol != "http") || (port < 1) || (port > 65535))
useDefault = true;
// use default if bad address
Address address = Address::getHostAddress(hostname.c_str());
if (address.isAny())
useDefault = true;
// parse default list server URL if we need to; assume default works
if (useDefault) {
BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
}
// add to list
this->address = address;
this->port = port;
this->pathname = pathname;
this->hostname = hostname;
this->linkSocket = NotConnected;
this->publicizeAddress = publicizedAddress;
this->publicizeDescription = publicizedTitle;
this->publicizeServer = true; //if this c'tor is called, it's safe to publicize
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink()
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
this->linkSocket = NotConnected;
this->publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
TimeKeeper start = TimeKeeper::getCurrent();
do {
// compute timeout
float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
if (waitTime <= 0.0f)
break;
if (!isConnected()) //queueMessage should have connected us
break;
// check for list server socket connection
int fdMax = -1;
fd_set write_set;
fd_set read_set;
FD_ZERO(&write_set);
FD_ZERO(&read_set);
if (phase == ListServerLink::CONNECTING)
_FD_SET(linkSocket, &write_set);
else
_FD_SET(linkSocket, &read_set);
fdMax = linkSocket;
// wait for socket to connect or timeout
struct timeval timeout;
timeout.tv_sec = long(floorf(waitTime));
timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
0, &timeout);
if (nfound == 0)
// Time has gone, close and go
break;
// check for connection to list server
if (FD_ISSET(linkSocket, &write_set))
sendQueuedMessages();
else if (FD_ISSET(linkSocket, &read_set))
read();
} while (true);
// stop list server communication
closeLink();
}
void ListServerLink::closeLink()
{
if (isConnected()) {
close(linkSocket);
DEBUG4("Closing List Server\n");
linkSocket = NotConnected;
}
}
void ListServerLink::read()
{
if (isConnected()) {
char buf[256];
recv(linkSocket, buf, sizeof(buf), 0);
closeLink();
if (nextMessageType != ListServerLink::NONE)
// There was a pending request arrived after we write:
// we should redo all the stuff
openLink();
}
}
void ListServerLink::openLink()
{
// start opening connection if not already doing so
if (!isConnected()) {
linkSocket = socket(AF_INET, SOCK_STREAM, 0);
DEBUG4("Opening List Server\n");
if (!isConnected()) {
return;
}
// set to non-blocking for connect
if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
closeLink();
return;
}
// Make our connection come from our serverAddress in case we have
// multiple/masked IPs so the list server can verify us.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr = serverAddress;
// assign the address to the socket
if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
closeLink();
return;
}
// connect. this should fail with EINPROGRESS but check for
// success just in case.
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = address;
if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
if (getErrno() != EINPROGRESS) {
nerror("connecting to list server");
// TODO should try to lookup dns name again, but we don't have it anymore
closeLink();
} else {
phase = CONNECTING;
}
} else {
// shouldn't arrive here. Just in case, clean
closeLink();
}
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// Open network connection only if closed
if (!isConnected()) openLink();
// record next message to send.
nextMessageType = type;
}
void ListServerLink::sendQueuedMessages()
{
if (!isConnected())
return;
if (nextMessageType == ListServerLink::ADD) {
DEBUG3("Queuing ADD message to list server\n");
addMe(getTeamCounts(), publicizeAddress, url_encode(publicizeDescription));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
DEBUG3("Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// send ADD message (must send blank line)
msg = string_util::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(), publicizedAddress.c_str(),
getServerVersion(), gameInfo,
getAppVersion(),
publicizedTitle.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
// send REMOVE (must send blank line)
msg = string_util::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(),
publicizedAddress.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::sendMessage(std::string message)
{
const int bufsize = 4096;
char msg[bufsize];
strncpy(msg, message.c_str(),
((int) message.length() > bufsize) ? bufsize : message.length());
if (strlen(msg) > 0) {
DEBUG3("%s\n",msg);
if (send(linkSocket, msg, strlen(msg), 0) == -1) {
perror("List server send failed");
DEBUG3("Unable to send to the list server!\n");
closeLink();
} else {
nextMessageType = ListServerLink::NONE;
phase = ListServerLink::WRITTEN;
}
} else {
closeLink();
}
}
<commit_msg>we like that null, thanx.<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* implementation headers */
#include <string.h>
#include <math.h>
#include <errno.h>
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
extern Address serverAddress;
extern PingPacket getTeamCounts();
ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
// parse url
std::string protocol, hostname, pathname;
int port = 80;
bool useDefault = false;
// use default if it can't be parsed
if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
useDefault = true;
// use default if wrong protocol or invalid port
if ((protocol != "http") || (port < 1) || (port > 65535))
useDefault = true;
// use default if bad address
Address address = Address::getHostAddress(hostname.c_str());
if (address.isAny())
useDefault = true;
// parse default list server URL if we need to; assume default works
if (useDefault) {
BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
}
// add to list
this->address = address;
this->port = port;
this->pathname = pathname;
this->hostname = hostname;
this->linkSocket = NotConnected;
this->publicizeAddress = publicizedAddress;
this->publicizeDescription = publicizedTitle;
this->publicizeServer = true; //if this c'tor is called, it's safe to publicize
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink()
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
this->linkSocket = NotConnected;
this->publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
TimeKeeper start = TimeKeeper::getCurrent();
do {
// compute timeout
float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
if (waitTime <= 0.0f)
break;
if (!isConnected()) //queueMessage should have connected us
break;
// check for list server socket connection
int fdMax = -1;
fd_set write_set;
fd_set read_set;
FD_ZERO(&write_set);
FD_ZERO(&read_set);
if (phase == ListServerLink::CONNECTING)
_FD_SET(linkSocket, &write_set);
else
_FD_SET(linkSocket, &read_set);
fdMax = linkSocket;
// wait for socket to connect or timeout
struct timeval timeout;
timeout.tv_sec = long(floorf(waitTime));
timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
0, &timeout);
if (nfound == 0)
// Time has gone, close and go
break;
// check for connection to list server
if (FD_ISSET(linkSocket, &write_set))
sendQueuedMessages();
else if (FD_ISSET(linkSocket, &read_set))
read();
} while (true);
// stop list server communication
closeLink();
}
void ListServerLink::closeLink()
{
if (isConnected()) {
close(linkSocket);
DEBUG4("Closing List Server\n");
linkSocket = NotConnected;
}
}
void ListServerLink::read()
{
if (isConnected()) {
char buf[256];
recv(linkSocket, buf, sizeof(buf), 0);
closeLink();
if (nextMessageType != ListServerLink::NONE)
// There was a pending request arrived after we write:
// we should redo all the stuff
openLink();
}
}
void ListServerLink::openLink()
{
// start opening connection if not already doing so
if (!isConnected()) {
linkSocket = socket(AF_INET, SOCK_STREAM, 0);
DEBUG4("Opening List Server\n");
if (!isConnected()) {
return;
}
// set to non-blocking for connect
if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
closeLink();
return;
}
// Make our connection come from our serverAddress in case we have
// multiple/masked IPs so the list server can verify us.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr = serverAddress;
// assign the address to the socket
if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
closeLink();
return;
}
// connect. this should fail with EINPROGRESS but check for
// success just in case.
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = address;
if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
if (getErrno() != EINPROGRESS) {
nerror("connecting to list server");
// TODO should try to lookup dns name again, but we don't have it anymore
closeLink();
} else {
phase = CONNECTING;
}
} else {
// shouldn't arrive here. Just in case, clean
closeLink();
}
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// Open network connection only if closed
if (!isConnected()) openLink();
// record next message to send.
nextMessageType = type;
}
void ListServerLink::sendQueuedMessages()
{
if (!isConnected())
return;
if (nextMessageType == ListServerLink::ADD) {
DEBUG3("Queuing ADD message to list server\n");
addMe(getTeamCounts(), publicizeAddress, url_encode(publicizeDescription));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
DEBUG3("Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// send ADD message (must send blank line)
msg = string_util::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(), publicizedAddress.c_str(),
getServerVersion(), gameInfo,
getAppVersion(),
publicizedTitle.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
// send REMOVE (must send blank line)
msg = string_util::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(),
publicizedAddress.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::sendMessage(std::string message)
{
const int bufsize = 4096;
char msg[bufsize];
strncpy(msg, message.c_str(), bufsize);
msg[bufsize - 1] = 0;
if (strlen(msg) > 0) {
DEBUG3("%s\n", msg);
if (send(linkSocket, msg, strlen(msg), 0) == -1) {
perror("List server send failed");
DEBUG3("Unable to send to the list server!\n");
closeLink();
} else {
nextMessageType = ListServerLink::NONE;
phase = ListServerLink::WRITTEN;
}
} else {
closeLink();
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.